Files
authorizer/server/resolvers/update_profile.go

297 lines
11 KiB
Go
Raw Normal View History

package resolvers
import (
"context"
2023-08-14 12:01:37 +05:30
"encoding/json"
2022-07-29 19:49:50 +05:30
"errors"
"fmt"
"strings"
"time"
2022-05-24 12:42:29 +05:30
log "github.com/sirupsen/logrus"
2022-01-17 11:32:13 +05:30
"github.com/authorizerdev/authorizer/server/constants"
"github.com/authorizerdev/authorizer/server/cookie"
2022-02-28 21:26:49 +05:30
"github.com/authorizerdev/authorizer/server/crypto"
2021-07-23 21:57:44 +05:30
"github.com/authorizerdev/authorizer/server/db"
2022-01-21 13:34:04 +05:30
"github.com/authorizerdev/authorizer/server/db/models"
2022-01-17 11:32:13 +05:30
"github.com/authorizerdev/authorizer/server/email"
2021-07-23 21:57:44 +05:30
"github.com/authorizerdev/authorizer/server/graph/model"
2022-05-27 23:20:38 +05:30
"github.com/authorizerdev/authorizer/server/memorystore"
2022-05-30 11:54:16 +05:30
"github.com/authorizerdev/authorizer/server/parsers"
2022-07-15 22:11:08 +05:30
"github.com/authorizerdev/authorizer/server/refs"
"github.com/authorizerdev/authorizer/server/token"
2021-07-23 21:57:44 +05:30
"github.com/authorizerdev/authorizer/server/utils"
2022-05-30 11:54:16 +05:30
"github.com/authorizerdev/authorizer/server/validators"
)
2022-01-17 11:32:13 +05:30
// UpdateProfileResolver is resolver for update profile mutation
func UpdateProfileResolver(ctx context.Context, params model.UpdateProfileInput) (*model.Response, error) {
var res *model.Response
2022-05-24 12:42:29 +05:30
gc, err := utils.GinContextFromContext(ctx)
if err != nil {
2022-05-25 12:30:22 +05:30
log.Debug("Failed to get GinContext: ", err)
return res, err
}
2023-12-14 22:12:03 +05:30
tokenData, err := token.GetUserIDFromSessionOrAccessToken(gc)
2022-03-02 17:42:31 +05:30
if err != nil {
log.Debug("Failed GetUserIDFromSessionOrAccessToken: ", err)
return res, err
}
// validate if all params are not empty
2023-08-14 12:01:37 +05:30
if params.GivenName == nil && params.FamilyName == nil && params.Picture == nil && params.MiddleName == nil && params.Nickname == nil && params.OldPassword == nil && params.Email == nil && params.Birthdate == nil && params.Gender == nil && params.PhoneNumber == nil && params.NewPassword == nil && params.ConfirmNewPassword == nil && params.IsMultiFactorAuthEnabled == nil && params.AppData == nil {
2022-05-25 12:30:22 +05:30
log.Debug("All params are empty")
return res, fmt.Errorf("please enter at least one param to update")
}
2022-05-24 12:42:29 +05:30
log := log.WithFields(log.Fields{
2023-12-14 22:12:03 +05:30
"user_id": tokenData.UserID,
2022-05-24 12:42:29 +05:30
})
2023-12-14 22:12:03 +05:30
user, err := db.Provider.GetUserByID(ctx, tokenData.UserID)
if err != nil {
2022-05-25 12:30:22 +05:30
log.Debug("Failed to get user by id: ", err)
return res, err
}
2022-07-15 22:11:08 +05:30
if params.GivenName != nil && refs.StringValue(user.GivenName) != refs.StringValue(params.GivenName) {
2021-12-22 15:31:45 +05:30
user.GivenName = params.GivenName
}
2022-07-15 22:11:08 +05:30
if params.FamilyName != nil && refs.StringValue(user.FamilyName) != refs.StringValue(params.FamilyName) {
2021-12-22 15:31:45 +05:30
user.FamilyName = params.FamilyName
}
2022-07-15 22:11:08 +05:30
if params.MiddleName != nil && refs.StringValue(user.MiddleName) != refs.StringValue(params.MiddleName) {
2021-12-22 15:31:45 +05:30
user.MiddleName = params.MiddleName
}
2022-07-15 22:11:08 +05:30
if params.Nickname != nil && refs.StringValue(user.Nickname) != refs.StringValue(params.Nickname) {
2021-12-22 15:31:45 +05:30
user.Nickname = params.Nickname
}
2022-07-15 22:11:08 +05:30
if params.Birthdate != nil && refs.StringValue(user.Birthdate) != refs.StringValue(params.Birthdate) {
2021-12-22 15:31:45 +05:30
user.Birthdate = params.Birthdate
}
2022-07-15 22:11:08 +05:30
if params.Gender != nil && refs.StringValue(user.Gender) != refs.StringValue(params.Gender) {
2021-12-22 15:31:45 +05:30
user.Gender = params.Gender
}
2022-07-15 22:11:08 +05:30
if params.PhoneNumber != nil && refs.StringValue(user.PhoneNumber) != refs.StringValue(params.PhoneNumber) {
2022-12-25 03:22:42 +05:30
// verify if phone number is unique
if _, err := db.Provider.GetUserByPhoneNumber(ctx, strings.TrimSpace(refs.StringValue(params.PhoneNumber))); err == nil {
log.Debug("user with given phone number already exists")
return nil, errors.New("user with given phone number already exists")
}
2021-12-22 15:31:45 +05:30
user.PhoneNumber = params.PhoneNumber
}
2022-07-15 22:11:08 +05:30
if params.Picture != nil && refs.StringValue(user.Picture) != refs.StringValue(params.Picture) {
2021-12-22 15:31:45 +05:30
user.Picture = params.Picture
}
2023-08-14 12:01:37 +05:30
if params.AppData != nil {
appDataString := ""
appDataBytes, err := json.Marshal(params.AppData)
if err != nil {
log.Debug("failed to marshall source app_data: ", err)
return nil, errors.New("malformed app_data")
}
appDataString = string(appDataBytes)
user.AppData = &appDataString
}
// Check if the user is trying to enable or disable multi-factor authentication (MFA)
2022-07-23 15:26:44 +05:30
if params.IsMultiFactorAuthEnabled != nil && refs.BoolValue(user.IsMultiFactorAuthEnabled) != refs.BoolValue(params.IsMultiFactorAuthEnabled) {
// Check if totp, email or sms is enabled
isMailOTPEnvServiceDisabled, err := memorystore.Provider.GetBoolStoreEnvVariable(constants.EnvKeyDisableMailOTPLogin)
if err != nil {
log.Debug("Error getting mail otp disabled: ", err)
isMailOTPEnvServiceDisabled = false
}
isTOTPEnvServiceDisabled, _ := memorystore.Provider.GetBoolStoreEnvVariable(constants.EnvKeyDisableTOTPLogin)
if err != nil {
log.Debug("Error getting totp disabled: ", err)
isTOTPEnvServiceDisabled = false
}
isSMSOTPEnvServiceDisabled, _ := memorystore.Provider.GetBoolStoreEnvVariable(constants.EnvKeyDisablePhoneVerification)
if err != nil {
log.Debug("Error getting sms otp disabled: ", err)
isSMSOTPEnvServiceDisabled = false
}
// Initialize a flag to check if enabling Mail OTP is required
if isMailOTPEnvServiceDisabled && isTOTPEnvServiceDisabled && isSMSOTPEnvServiceDisabled {
log.Debug("Cannot enable mfa service as all mfa services are disabled")
return nil, errors.New("cannot enable multi factor authentication as all mfa services are disabled")
2022-07-29 19:49:50 +05:30
}
2022-08-03 23:20:23 +05:30
isMFAEnforced, err := memorystore.Provider.GetBoolStoreEnvVariable(constants.EnvKeyEnforceMultiFactorAuthentication)
if err != nil {
log.Debug("MFA service not enabled: ", err)
isMFAEnforced = false
}
if isMFAEnforced && !refs.BoolValue(params.IsMultiFactorAuthEnabled) {
log.Debug("Cannot disable mfa service as it is enforced:")
return nil, errors.New("cannot disable multi factor authentication as it is enforced by organization")
}
user.IsMultiFactorAuthEnabled = params.IsMultiFactorAuthEnabled
2022-07-23 15:26:44 +05:30
}
isPasswordChanging := false
if params.NewPassword != nil && params.ConfirmNewPassword == nil {
isPasswordChanging = true
log.Debug("confirm password is empty")
return res, fmt.Errorf("confirm password is required")
}
if params.ConfirmNewPassword != nil && params.NewPassword == nil {
isPasswordChanging = true
log.Debug("new password is empty")
return res, fmt.Errorf("new password is required")
}
if params.NewPassword != nil && params.ConfirmNewPassword != nil {
isPasswordChanging = true
}
if isPasswordChanging && user.Password != nil && params.OldPassword == nil {
log.Debug("old password is empty")
return res, fmt.Errorf("old password is required")
}
if isPasswordChanging && user.Password != nil && params.OldPassword != nil {
2024-01-04 22:15:22 +03:00
if err = crypto.VerifyPassword(refs.StringValue(user.Password), refs.StringValue(params.OldPassword)); err != nil {
2022-05-25 12:30:22 +05:30
log.Debug("Failed to compare hash and old password: ", err)
return res, fmt.Errorf("incorrect old password")
}
}
shouldAddBasicSignUpMethod := false
isBasicAuthDisabled, err := memorystore.Provider.GetBoolStoreEnvVariable(constants.EnvKeyDisableBasicAuthentication)
if err != nil {
log.Debug("Error getting basic auth disabled: ", err)
isBasicAuthDisabled = true
}
2022-12-21 23:14:24 +05:30
isMobileBasicAuthDisabled, err := memorystore.Provider.GetBoolStoreEnvVariable(constants.EnvKeyDisableMobileBasicAuthentication)
if err != nil {
log.Debug("Error getting mobile basic auth disabled: ", err)
isBasicAuthDisabled = true
}
if params.NewPassword != nil && params.ConfirmNewPassword != nil {
2022-12-21 23:14:24 +05:30
if isBasicAuthDisabled || isMobileBasicAuthDisabled {
log.Debug("Cannot update password as basic authentication is disabled")
return res, fmt.Errorf(`basic authentication is disabled for this instance`)
}
2022-07-15 22:11:08 +05:30
if refs.StringValue(params.ConfirmNewPassword) != refs.StringValue(params.NewPassword) {
2022-05-24 12:42:29 +05:30
log.Debug("Failed to compare new password and confirm new password")
return res, fmt.Errorf(`password and confirm password does not match`)
}
2022-07-15 22:11:08 +05:30
if user.Password == nil || refs.StringValue(user.Password) == "" {
shouldAddBasicSignUpMethod = true
}
2022-07-15 22:11:08 +05:30
if err := validators.IsValidPassword(refs.StringValue(params.NewPassword)); err != nil {
log.Debug("Invalid password")
return res, err
}
2022-07-15 22:11:08 +05:30
password, _ := crypto.EncryptPassword(refs.StringValue(params.NewPassword))
2021-12-22 15:31:45 +05:30
user.Password = &password
if shouldAddBasicSignUpMethod {
user.SignupMethods = user.SignupMethods + "," + constants.AuthRecipeMethodBasicAuth
}
}
hasEmailChanged := false
2023-10-26 00:55:10 +05:30
if params.Email != nil && refs.StringValue(user.Email) != refs.StringValue(params.Email) {
// check if valid email
2022-05-30 11:54:16 +05:30
if !validators.IsValidEmail(*params.Email) {
2022-07-15 22:11:08 +05:30
log.Debug("Failed to validate email: ", refs.StringValue(params.Email))
return res, fmt.Errorf("invalid email address")
}
newEmail := strings.ToLower(*params.Email)
2022-05-25 12:30:22 +05:30
// check if valid email
2022-05-30 11:54:16 +05:30
if !validators.IsValidEmail(newEmail) {
2022-05-25 12:30:22 +05:30
log.Debug("Failed to validate new email: ", newEmail)
return res, fmt.Errorf("invalid new email address")
}
// check if user with new email exists
2022-07-10 21:49:33 +05:30
_, err := db.Provider.GetUserByEmail(ctx, newEmail)
// err = nil means user exists
if err == nil {
2022-05-25 12:30:22 +05:30
log.Debug("Failed to get user by email: ", newEmail)
return res, fmt.Errorf("user with this email address already exists")
}
2022-06-11 19:10:39 +05:30
go memorystore.Provider.DeleteAllUserSessions(user.ID)
2022-05-24 12:42:29 +05:30
go cookie.DeleteSession(gc)
2023-10-26 00:55:10 +05:30
user.Email = &newEmail
2022-05-30 09:19:55 +05:30
isEmailVerificationDisabled, err := memorystore.Provider.GetBoolStoreEnvVariable(constants.EnvKeyDisableEmailVerification)
if err != nil {
log.Debug("Failed to get disable email verification env variable: ", err)
return res, err
}
if !isEmailVerificationDisabled {
2022-05-30 11:54:16 +05:30
hostname := parsers.GetHost(gc)
2022-03-02 17:42:31 +05:30
user.EmailVerifiedAt = nil
hasEmailChanged = true
// insert verification request
_, nonceHash, err := utils.GenerateNonce()
2022-03-02 17:42:31 +05:30
if err != nil {
2022-05-25 12:30:22 +05:30
log.Debug("Failed to generate nonce: ", err)
2022-03-02 17:42:31 +05:30
return res, err
}
verificationType := constants.VerificationTypeUpdateEmail
2022-05-30 11:54:16 +05:30
redirectURL := parsers.GetAppURL(gc)
verificationToken, err := token.CreateVerificationToken(newEmail, verificationType, hostname, nonceHash, redirectURL)
2022-03-02 17:42:31 +05:30
if err != nil {
2022-05-25 12:30:22 +05:30
log.Debug("Failed to create verification token: ", err)
2022-05-24 12:42:29 +05:30
return res, err
2022-03-02 17:42:31 +05:30
}
_, err = db.Provider.AddVerificationRequest(ctx, &models.VerificationRequest{
Token: verificationToken,
Identifier: verificationType,
ExpiresAt: time.Now().Add(time.Minute * 30).Unix(),
Email: newEmail,
Nonce: nonceHash,
RedirectURI: redirectURL,
2022-03-02 17:42:31 +05:30
})
2022-05-24 12:42:29 +05:30
if err != nil {
2022-05-25 12:30:22 +05:30
log.Debug("Failed to add verification request: ", err)
2022-05-24 12:42:29 +05:30
return res, err
}
2022-03-02 17:42:31 +05:30
2022-08-09 01:43:37 +05:30
// exec it as go routine so that we can reduce the api latency
2023-10-26 00:55:10 +05:30
go email.SendEmail([]string{refs.StringValue(user.Email)}, verificationType, map[string]interface{}{
2022-08-09 01:43:37 +05:30
"user": user.ToMap(),
"organization": utils.GetOrganization(),
"verification_url": utils.GetEmailVerificationURL(verificationToken, hostname, redirectURL),
2022-08-09 01:43:37 +05:30
})
2022-03-02 17:42:31 +05:30
}
}
2022-07-10 21:49:33 +05:30
_, err = db.Provider.UpdateUser(ctx, user)
if err != nil {
2022-05-25 12:30:22 +05:30
log.Debug("Failed to update user: ", err)
return res, err
}
message := `Profile details updated successfully.`
if hasEmailChanged {
message += `For the email change we have sent new verification email, please verify and continue`
}
res = &model.Response{
Message: message,
}
return res, nil
}