diff --git a/TODO.md b/TODO.md index 0fd5d66..5e6b62d 100644 --- a/TODO.md +++ b/TODO.md @@ -8,6 +8,7 @@ For the first version we will only support setting roles master list via env - [x] `ROLES` -> comma separated list of role names - [x] `DEFAULT_ROLE` -> default role to assign to users - [x] Add roles input for signup +- [x] Add roles to update profile mutation - [ ] Add roles input for login - [ ] Return roles to user - [ ] Return roles in users list for super admin diff --git a/server/resolvers/signup.go b/server/resolvers/signup.go index c6ceb87..f333b88 100644 --- a/server/resolvers/signup.go +++ b/server/resolvers/signup.go @@ -35,7 +35,7 @@ func Signup(ctx context.Context, params model.SignUpInput) (*model.AuthResponse, return res, fmt.Errorf(`invalid email address`) } - if len(params.Roles) > 0 { + if params.Roles != nil && len(params.Roles) > 0 { // check if roles exists if !utils.IsValidRolesArray(params.Roles) { return res, fmt.Errorf(`invalid roles`) diff --git a/server/resolvers/updateProfile.go b/server/resolvers/updateProfile.go index db4da8d..42ebfec 100644 --- a/server/resolvers/updateProfile.go +++ b/server/resolvers/updateProfile.go @@ -39,7 +39,7 @@ func UpdateProfile(ctx context.Context, params model.UpdateProfileInput) (*model } // validate if all params are not empty - if params.FirstName == nil && params.LastName == nil && params.Image == nil && params.OldPassword == nil && params.Email == nil { + if params.FirstName == nil && params.LastName == nil && params.Image == nil && params.OldPassword == nil && params.Email == nil && params.Roles != nil { return res, fmt.Errorf("please enter atleast one param to update") } @@ -120,7 +120,22 @@ func UpdateProfile(ctx context.Context, params model.UpdateProfileInput) (*model go func() { utils.SendVerificationMail(newEmail, token) }() + } + rolesToSave := "" + if params.Roles != nil && len(params.Roles) > 0 { + currentRoles := strings.Split(user.Roles, ",") + inputRoles := []string{} + for _, item := range params.Roles { + inputRoles = append(inputRoles, *item) + } + if !utils.IsStringArrayEqual(inputRoles, currentRoles) && utils.IsValidRolesArray(params.Roles) { + rolesToSave = strings.Join(inputRoles, ",") + } + } + + if rolesToSave != "" { + user.Roles = rolesToSave } _, err = db.Mgr.UpdateUser(user) diff --git a/server/utils/validator.go b/server/utils/validator.go index 05397bb..63bb92a 100644 --- a/server/utils/validator.go +++ b/server/utils/validator.go @@ -55,3 +55,15 @@ func IsValidRolesArray(roles []*string) bool { } return valid } + +func IsStringArrayEqual(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i, v := range a { + if v != b[i] { + return false + } + } + return true +}