Browse Source

Add has_role method to MemberManager

pull/1627/head
Hironsan 2 years ago
parent
commit
2118ab73a2
3 changed files with 22 additions and 11 deletions
  1. 3
      backend/roles/models.py
  2. 13
      backend/roles/permissions.py
  3. 17
      backend/roles/tests.py

3
backend/roles/models.py

@ -41,6 +41,9 @@ class MemberManager(Manager):
return False
return True
def has_role(self, project_id: int, user: User, role_name: str):
return self.filter(project=project_id, user=user, role__name=role_name).exists()
class Member(models.Model):
user = models.ForeignKey(

13
backend/roles/permissions.py

@ -1,8 +1,7 @@
from django.conf import settings
from django.db.models import Subquery
from rest_framework.permissions import BasePermission, SAFE_METHODS
from .models import Member, Role
from .models import Member
class RolePermission(BasePermission):
@ -25,7 +24,7 @@ class RolePermission(BasePermission):
if not project_id and request.method in SAFE_METHODS:
return True
return is_in_role(self.role_name, request.user.id, project_id)
return Member.objects.has_role(project_id, request.user, self.role_name)
class IsProjectAdmin(RolePermission):
@ -51,13 +50,5 @@ class IsAnnotationApprover(RolePermission):
role_name = settings.ROLE_ANNOTATION_APPROVER
def is_in_role(role_name, user_id, project_id):
return Member.objects.filter(
user_id=user_id,
project_id=project_id,
role_id=Subquery(Role.objects.filter(name=role_name).values('id')),
).exists()
IsInProjectReadOnlyOrAdmin = (IsAnnotatorAndReadOnly | IsAnnotationApproverAndReadOnly | IsProjectAdmin)
IsInProjectOrAdmin = (IsAnnotator | IsAnnotationApprover | IsProjectAdmin)

17
backend/roles/tests.py

@ -127,3 +127,20 @@ class TestMemberRoleFilter(CRUDMixin):
def test_filter_role_by_user_id(self):
response = self.assert_fetch(self.project.users[0], status.HTTP_200_OK)
self.assertEqual(len(response.data), 1)
class TestMemberManager(CRUDMixin):
def setUp(self):
pass
def test_has_role(self):
project = prepare_project()
admin = project.users[0]
expected = [
(settings.ROLE_PROJECT_ADMIN, True),
(settings.ROLE_ANNOTATION_APPROVER, False),
(settings.ROLE_ANNOTATOR, False)
]
for role, expect in expected:
self.assertEqual(Member.objects.has_role(project.item, admin, role), expect)
Loading…
Cancel
Save