// VerifyPhoneNumber is the handler for PUT /users/{username}/phonenumbers/{label}/validate
177829
func (api UsersAPI) VerifyPhoneNumber(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]
	label := mux.Vars(r)["label"]
	userMgr := user.NewManager(r)

	values := struct {
		Smscode       string `json:"smscode"`
		ValidationKey string `json:"validationkey"`
	}{}
	if err := json.NewDecoder(r.Body).Decode(&values); err != nil {
		log.Debug("Error decoding the ProcessPhonenumberConfirmation request:", err)
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}
	userobj, err := userMgr.GetByName(username)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	_, err = userobj.GetPhonenumberByLabel(label)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	err = api.PhonenumberValidationService.ConfirmValidation(r, values.ValidationKey, values.Smscode)
	if err != nil {
		log.Debug(err)
		if err == validation.ErrInvalidCode || err == validation.ErrInvalidOrExpiredKey {
			writeErrorResponse(w, 422, err.Error())
		} else {
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		}
		return
	}
	userMgr.RemoveExpireDate(username)
	w.WriteHeader(http.StatusNoContent)
}
168831
func (s *NumberValidateRequest) SetPhoneNumber(v string) *NumberValidateRequest {
	s.PhoneNumber = &v
	return s
}
1230461
func (s *ListPhoneNumbersOutput) SetPhoneNumbers(v []*PhoneNumber) *ListPhoneNumbersOutput {
	s.PhoneNumbers = v
	return s
}
940233
func (manager *Manager) GetValidatedPhoneNumbersByUsernames(usernames []string) (validatedPhonenumbers []ValidatedPhonenumber, err error) {
	mgoCollection := db.GetCollection(manager.session, mongoValidatedPhonenumbers)
	qry := bson.M{
		"username": bson.M{
			"$in": usernames,
		},
	}
	err = mgoCollection.Find(qry).All(&validatedPhonenumbers)
	return
}
199038
func (o *InvitationManager) GetByPhonenumber(phonenumber string) ([]JoinOrganizationInvitation, error) {
	orgRequests := []JoinOrganizationInvitation{}
	err := o.collection.Find(bson.M{"phonenumber": phonenumber}).All(&orgRequests)
	return orgRequests, err
}
312315
func (p Phonenumber) Validate() bool {
	return validator.Validate(p) == nil &&
		regexp.MustCompile(`^[a-zA-Z\d\-_\s]{2,50}$`).MatchString(p.Label) &&
		regexp.MustCompile(`\+[0-9]{6,50}`).MatchString(p.Phonenumber)
}
1170358
func (s *DisassociatePhoneNumbersFromVoiceConnectorOutput) SetPhoneNumberErrors(v []*PhoneNumberError) *DisassociatePhoneNumbersFromVoiceConnectorOutput {
	s.PhoneNumberErrors = v
	return s
}
11382
func (authy *Authy) StartPhoneVerification(countryCode int, phoneNumber string, via string, params url.Values) (*PhoneVerificationStart, error) {
	params.Set("country_code", strconv.Itoa(countryCode))
	params.Set("phone_number", phoneNumber)
	params.Set("via", via)

	path := fmt.Sprintf("/protected/json/phones/verification/start")
	response, err := authy.DoRequest("POST", path, params)
	if err != nil {
		return nil, err
	}

	defer closeResponseBody(response)
	return NewPhoneVerificationStart(response)
}
1328716
func (service *Service) PhonenumberRegistrationValidation(w http.ResponseWriter, r *http.Request) {
	service.handlePhoneValidation(w, r, true)
}
693050
func (ref *Ref) Verify(serializedID []byte, msg []byte, sig []byte) error {
	membership, err := ref.get()
	if err != nil {
		return err
	}
	return membership.Verify(serializedID, msg, sig)
}
149031
func RequiredNumber(path, in string, data float64) *errors.Validation {
	if data == 0 {
		return errors.Required(path, in)
	}
	return nil
}
131627
func (service *Service) ProcessPhonenumberConfirmationForm(w http.ResponseWriter, r *http.Request) {
	values := struct {
		Smscode string `json:"smscode"`
	}{}

	response := struct {
		Error     string `json:"error"`
		Confirmed bool   `json:"confirmed"`
	}{}

	if err := json.NewDecoder(r.Body).Decode(&values); err != nil {
		log.Debug("Error decoding the ProcessPhonenumberConfirmation request:", err)
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	if values.Smscode == "" {
		log.Debug("Tried to confirm phone number with empty sms code")
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	registrationSession, err := service.GetSession(r, SessionForRegistration, "registrationdetails")
	if err != nil {
		log.Debug("Failed to get registration session: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	if registrationSession.IsNew {
		sessions.Save(r, w)
		log.Debug("Registration session expired")
		http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
		return
	}

	sessionKey, _ := registrationSession.Values["sessionkey"].(string)
	if sessionKey == "" {
		log.Debug("Trying to confirm phone number without session key")
		sessions.Save(r, w)
		http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
		return
	}

	registeringUser, err := registration.NewManager(r).GetRegisteringUserBySessionKey(sessionKey)
	if err != nil {
		log.Error("Failed to load registering user object: ", err)
		sessions.Save(r, w)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	logMgr := persistentlog.NewManager(r)
	if isConfirmed, _ := service.phonenumberValidationService.IsConfirmed(r, registeringUser.PhoneValidationKey); isConfirmed {
		logMgr.SaveLog(persistentlog.New(sessionKey, persistentlog.RegistrationFlow, "User processed phone number form, but phone is already confirmed"))
		response.Confirmed = true
		w.WriteHeader(http.StatusOK)
		json.NewEncoder(w).Encode(response)
		return
	}

	err = service.phonenumberValidationService.ConfirmRegistrationValidation(r, registeringUser.PhoneValidationKey, values.Smscode)
	if err == validation.ErrInvalidCode {
		logMgr.SaveLog(persistentlog.New(sessionKey, persistentlog.RegistrationFlow, "User processed phone number form with invalid code"))
		w.WriteHeader(http.StatusUnprocessableEntity)
		response.Error = "invalid_sms_code"
		json.NewEncoder(w).Encode(&response)
		return
	}
	if err == validation.ErrInvalidOrExpiredKey {
		logMgr.SaveLog(persistentlog.New(sessionKey, persistentlog.RegistrationFlow, "User processed phone number form, but key is expired"))
		sessions.Save(r, w)
		http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
		json.NewEncoder(w).Encode(&response)
		return
	} else if err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	logMgr.SaveLog(persistentlog.New(sessionKey, persistentlog.RegistrationFlow, "User processed phone number form successfully, phone is confirmed"))
	response.Confirmed = true
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(response)
}
865430
func (s *UpdatePhoneNumberInput) SetPhoneNumberId(v string) *UpdatePhoneNumberInput {
	s.PhoneNumberId = &v
	return s
}
1076006
func (auth *Auth) GetUserByPhoneNumber(ctx context.Context, phoneNumber string) (*UserRecord, error) {
	users, err := auth.GetUsersByPhoneNumber(ctx, []string{phoneNumber})
	if err != nil {
		return nil, err
	}
	if len(users) == 0 {
		return nil, ErrUserNotFound
	}
	return users[0], nil
}
940585
func (service *Service) ValidateEmail(w http.ResponseWriter, r *http.Request) {
	body := struct {
		Username string `json:"username"`
		LangKey  string `json:"langkey"`
	}{}

	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		log.Debug("Error decoding the validte email request:", err)
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	// try to load the username if it is a validated phone number
	valMgr := validationdb.NewManager(r)
	userFromPhone, err := valMgr.GetByPhoneNumber(body.Username)
	if err != nil && !db.IsNotFound(err) {
		log.Error("Error while retrieving username from phone number: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	if !db.IsNotFound(err) {
		body.Username = userFromPhone.Username
	}

	userMgr := user.NewManager(r)
	user, err := userMgr.GetByName(body.Username)
	if err != nil {
		if db.IsNotFound(err) {
			http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
			return
		}
		log.Error("Error while retrieving username: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	if len(user.EmailAddresses) < 1 {
		log.Debug("User does not have any email addresses.")
		http.Error(w, http.StatusText(http.StatusPreconditionFailed), http.StatusPreconditionFailed)
		return
	}

	// Don't send verification if at least 1 email address is already verified
	ve, err := valMgr.GetByUsernameValidatedEmailAddress(body.Username)
	if err != nil && !db.IsNotFound(err) {
		log.Error("Error while retrieving verified email addresses: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	//User has verified email addresses
	if err == nil && len(ve) > 0 {
		log.Debug("User has verified email addresses, rejecting validate request")
		http.Error(w, http.StatusText(http.StatusConflict), http.StatusConflict)
		return
	}
	// Don't send verification if one is already ongoing
	ov, err := valMgr.GetOngoingEmailAddressValidationByUser(body.Username)
	if err != nil && !db.IsNotFound(err) {
		log.Error("Error while checking ongoing email address verifications: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	if err == nil && len(ov) > 0 {
		log.Debug("User has ongoing email address verifications, rejecting validate request")
		http.Error(w, http.StatusText(http.StatusConflict), http.StatusConflict)
		return
	}

	for _, email := range user.EmailAddresses {
		_, err = service.emailaddressValidationService.RequestValidation(r, body.Username, email.EmailAddress, fmt.Sprintf("https://%s/emailvalidation", r.Host), body.LangKey)
		if err != nil {
			log.Error("Failed to validate email address: ", err)
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
	}

	w.WriteHeader(http.StatusOK)
}
495193
func (s *CheckIfPhoneNumberIsOptedOutInput) SetPhoneNumber(v string) *CheckIfPhoneNumberIsOptedOutInput {
	s.PhoneNumber = &v
	return s
}
603815
func GetPhoneNumbers(mctx libkb.MetaContext) ([]keybase1.UserPhoneNumber, error) {
	arg := libkb.APIArg{
		Endpoint:    "user/phone_numbers",
		SessionType: libkb.APISessionTypeREQUIRED,
	}
	var resp phoneNumbersResponse
	err := mctx.G().API.GetDecode(mctx, arg, &resp)
	if err != nil {
		return nil, err
	}
	return resp.PhoneNumbers, nil
}