Skip to content

Commit

Permalink
Merge pull request #439 from team-scaletech/fix/role-deletion
Browse files Browse the repository at this point in the history
role deletion
  • Loading branch information
lakhansamani authored Jan 19, 2024
2 parents b1bfaf6 + 40a0a2f commit 747c82f
Show file tree
Hide file tree
Showing 4 changed files with 211 additions and 11 deletions.
83 changes: 72 additions & 11 deletions server/resolvers/update_env.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"reflect"
"strings"
"time"

log "github.com/sirupsen/logrus"

Expand Down Expand Up @@ -93,6 +94,53 @@ func clearSessionIfRequired(currentData, updatedData map[string]interface{}) {
}
}

// updateRoles will update DB for user roles, if a role is deleted by admin
// then this function will those roles from user roles if exists
func updateRoles(ctx context.Context, deletedRoles []string) error {
data, err := db.Provider.ListUsers(ctx, &model.Pagination{
Limit: 1,
Offset: 1,
})
if err != nil {
return err
}

allData, err := db.Provider.ListUsers(ctx, &model.Pagination{
Limit: data.Pagination.Total,
})
if err != nil {
return err
}

chunkSize := 1000
totalUsers := len(allData.Users)

for start := 0; start < totalUsers; start += chunkSize {
end := start + chunkSize
if end > totalUsers {
end = totalUsers
}

chunkUsers := allData.Users[start:end]

for i := range chunkUsers {
roles := utils.DeleteFromArray(chunkUsers[i].Roles, deletedRoles)
if len(chunkUsers[i].Roles) != len(roles) {
updatedValues := map[string]interface{}{
"roles": strings.Join(roles, ","),
"updated_at": time.Now().Unix(),
}
id := []string{chunkUsers[i].ID}
err = db.Provider.UpdateUsers(ctx, updatedValues, id)
if err != nil {
return err
}
}
}
}
return nil
}

// UpdateEnvResolver is a resolver for update config mutation
// This is admin only mutation
func UpdateEnvResolver(ctx context.Context, params model.UpdateEnvInput) (*model.Response, error) {
Expand Down Expand Up @@ -291,28 +339,41 @@ func UpdateEnvResolver(ctx context.Context, params model.UpdateEnvInput) (*model
}, nil)
}

previousRoles := strings.Split(currentData[constants.EnvKeyRoles].(string), ",")
previousProtectedRoles := strings.Split(currentData[constants.EnvKeyProtectedRoles].(string), ",")
updatedRoles := strings.Split(updatedData[constants.EnvKeyRoles].(string), ",")
updatedDefaultRoles := strings.Split(updatedData[constants.EnvKeyDefaultRoles].(string), ",")
updatedProtectedRoles := strings.Split(updatedData[constants.EnvKeyProtectedRoles].(string), ",")
// check the roles change
if len(params.Roles) > 0 {
if len(params.DefaultRoles) > 0 {
// should be subset of roles
for _, role := range params.DefaultRoles {
if !utils.StringSliceContains(params.Roles, role) {
log.Debug("Default roles should be subset of roles")
return res, fmt.Errorf("default role %s is not in roles", role)
}
if len(updatedRoles) > 0 && len(updatedDefaultRoles) > 0 {
// should be subset of roles
for _, role := range updatedDefaultRoles {
if !utils.StringSliceContains(updatedRoles, role) {
log.Debug("Default roles should be subset of roles")
return res, fmt.Errorf("default role %s is not in roles", role)
}
}
}

if len(params.ProtectedRoles) > 0 {
for _, role := range params.ProtectedRoles {
if utils.StringSliceContains(params.Roles, role) || utils.StringSliceContains(params.DefaultRoles, role) {
if len(updatedProtectedRoles) > 0 {
for _, role := range updatedProtectedRoles {
if utils.StringSliceContains(updatedRoles, role) || utils.StringSliceContains(updatedDefaultRoles, role) {
log.Debug("Protected roles should not be in roles or default roles")
return res, fmt.Errorf("protected role %s found roles or default roles", role)
}
}
}

deletedRoles := utils.FindDeletedValues(previousRoles, updatedRoles)
if len(deletedRoles) > 0 {
go updateRoles(ctx, deletedRoles)
}

deletedProtectedRoles := utils.FindDeletedValues(previousProtectedRoles, updatedProtectedRoles)
if len(deletedProtectedRoles) > 0 {
go updateRoles(ctx, deletedProtectedRoles)
}

// Update local store
memorystore.Provider.UpdateEnvStore(updatedData)
jwk, err := crypto.GenerateJWKBasedOnEnv()
Expand Down
1 change: 1 addition & 0 deletions server/test/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ func TestResolvers(t *testing.T) {
updateEmailTemplateTest(t, s)
emailTemplatesTest(t, s)
deleteEmailTemplateTest(t, s)
RoleDeletionTest(t, s)

// user resolvers tests
loginTests(t, s)
Expand Down
98 changes: 98 additions & 0 deletions server/test/role_deletion_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package test

import (
"fmt"
"github.com/authorizerdev/authorizer/server/crypto"
"strings"
"testing"

"github.com/stretchr/testify/assert"

"github.com/authorizerdev/authorizer/server/constants"
"github.com/authorizerdev/authorizer/server/graph/model"
"github.com/authorizerdev/authorizer/server/memorystore"
"github.com/authorizerdev/authorizer/server/refs"
"github.com/authorizerdev/authorizer/server/resolvers"
)

func RoleDeletionTest(t *testing.T, s TestSetup) {
t.Helper()
t.Run(`should complete role deletion`, func(t *testing.T) {
// login as admin
req, ctx := createContext(s)

_, err := resolvers.AdminLoginResolver(ctx, model.AdminLoginInput{
AdminSecret: "admin_test",
})
assert.NotNil(t, err)

adminSecret, err := memorystore.Provider.GetStringStoreEnvVariable(constants.EnvKeyAdminSecret)
assert.Nil(t, err)
_, err = resolvers.AdminLoginResolver(ctx, model.AdminLoginInput{
AdminSecret: adminSecret,
})
assert.Nil(t, err)

h, err := crypto.EncryptPassword(adminSecret)
assert.Nil(t, err)
req.Header.Set("Cookie", fmt.Sprintf("%s=%s", constants.AdminCookieName, h))

// add new default role to get role, if not present in roles
originalDefaultRoles, err := memorystore.Provider.GetStringStoreEnvVariable(constants.EnvKeyDefaultRoles)
assert.Nil(t, err)
originalDefaultRolesSlice := strings.Split(originalDefaultRoles, ",")

data := model.UpdateEnvInput{
DefaultRoles: append(originalDefaultRolesSlice, "abc"),
}
_, err = resolvers.UpdateEnvResolver(ctx, data)
assert.Error(t, err)

// add new role
originalRoles, err := memorystore.Provider.GetStringStoreEnvVariable(constants.EnvKeyRoles)
assert.Nil(t, err)
originalRolesSlice := strings.Split(originalRoles, ",")
roleToBeAdded := "abc"
newRoles := append(originalRolesSlice, roleToBeAdded)
data = model.UpdateEnvInput{
Roles: newRoles,
}
_, err = resolvers.UpdateEnvResolver(ctx, data)
assert.Nil(t, err)

// register a user with all roles
email := "update_user." + s.TestInfo.Email
_, err = resolvers.SignupResolver(ctx, model.SignUpInput{
Email: refs.NewStringRef(email),
Password: s.TestInfo.Password,
ConfirmPassword: s.TestInfo.Password,
Roles: newRoles,
})
assert.Nil(t, err)

regUserDetails, _ := resolvers.UserResolver(ctx, model.GetUserRequest{
Email: refs.NewStringRef(email),
})

// update env by removing role "abc"
var newRolesAfterDeletion []string
for _, value := range newRoles {
if value != roleToBeAdded {
newRolesAfterDeletion = append(newRolesAfterDeletion, value)
}
}
data = model.UpdateEnvInput{
Roles: newRolesAfterDeletion,
}
_, err = resolvers.UpdateEnvResolver(ctx, data)
assert.Nil(t, err)

// check user if role still exist
userDetails, err := resolvers.UserResolver(ctx, model.GetUserRequest{
Email: refs.NewStringRef(email),
})
assert.Nil(t, err)
assert.Equal(t, newRolesAfterDeletion, userDetails.Roles)
assert.NotEqual(t, newRolesAfterDeletion, regUserDetails.Roles)
})
}
40 changes: 40 additions & 0 deletions server/utils/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,43 @@ func GetInviteVerificationURL(verificationURL, token, redirectURI string) string
func GetEmailVerificationURL(token, hostname, redirectURI string) string {
return hostname + "/verify_email?token=" + token + "&redirect_uri=" + redirectURI
}

// FindDeletedValues find deleted values between original and updated one
func FindDeletedValues(original, updated []string) []string {
deletedValues := make([]string, 0)

// Create a map to store elements of the updated array for faster lookups
updatedMap := make(map[string]bool)
for _, value := range updated {
updatedMap[value] = true
}

// Check for deleted values in the original array
for _, value := range original {
if _, found := updatedMap[value]; !found {
deletedValues = append(deletedValues, value)
}
}

return deletedValues
}

// DeleteFromArray will delete array from an array
func DeleteFromArray(original, valuesToDelete []string) []string {
result := make([]string, 0)

// Create a map to store values to delete for faster lookups
valuesToDeleteMap := make(map[string]bool)
for _, value := range valuesToDelete {
valuesToDeleteMap[value] = true
}

// Check if each element in the original array should be deleted
for _, value := range original {
if _, found := valuesToDeleteMap[value]; !found {
result = append(result, value)
}
}

return result
}

0 comments on commit 747c82f

Please sign in to comment.