Skip to content

Commit 9367895

Browse files
Fixed permission mutaiton with toggling
1 parent 48b2ac3 commit 9367895

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

nxtbn/users/admin_mutation.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def mutate(self, info, refresh_token):
112112

113113

114114

115-
class AttachPermissionMutation(graphene.Mutation):
115+
class TogglePermissionMutation(graphene.Mutation):
116116
class Arguments:
117117
user_id = graphene.Int(required=True)
118118
permission_codename = graphene.String(required=True)
@@ -124,22 +124,26 @@ def mutate(self, info, user_id, permission_codename):
124124
try:
125125
user = User.objects.get(id=user_id)
126126
except User.DoesNotExist:
127-
return AttachPermissionMutation(success=False, message="User not found")
127+
return TogglePermissionMutation(success=False, message="User not found")
128128

129129
try:
130130
permission = Permission.objects.get(codename=permission_codename)
131131
except Permission.DoesNotExist:
132-
return AttachPermissionMutation(success=False, message="Permission not found")
132+
return TogglePermissionMutation(success=False, message="Permission not found")
133133

134-
# Add the permission to the user
135-
user.user_permissions.add(permission)
134+
if user.user_permissions.filter(id=permission.id).exists():
135+
# If the permission is already assigned, remove it
136+
user.user_permissions.remove(permission)
137+
return TogglePermissionMutation(success=True, message="Permission removed successfully")
138+
else:
139+
# Otherwise, add the permission
140+
user.user_permissions.add(permission)
141+
return TogglePermissionMutation(success=True, message="Permission assigned successfully")
136142

137-
return AttachPermissionMutation(success=True, message="Permission assigned successfully")
138-
139143

140144
class AdminUserMutation(graphene.ObjectType):
141145
login = AdminLoginMutation.Field()
142146
refresh_token = AdminTokenRefreshMutation.Field()
143-
attach_permission = AttachPermissionMutation.Field()
147+
toggle_permission = TogglePermissionMutation.Field()
144148

145149

0 commit comments

Comments
 (0)