Coverage for django_napse/api/custom_permissions.py: 31%

54 statements  

« prev     ^ index     » next       coverage.py v7.4.3, created at 2024-03-12 13:49 +0000

1from django.forms import ValidationError 

2from rest_framework.permissions import BasePermission 

3from rest_framework_api_key.permissions import HasAPIKey # noqa 

4 

5from django_napse.core.models import NapseSpace 

6from django_napse.utils.constants import PERMISSION_TYPES 

7from django_napse.utils.errors import APIError 

8 

9 

10def check_for_space(request): 

11 if "space" not in request.query_params: 

12 raise APIError.MissingSpace() 

13 try: 

14 return NapseSpace.objects.get(uuid=request.query_params["space"]) 

15 except NapseSpace.DoesNotExist as e: 

16 raise APIError.InvalidSpace() from e 

17 except ValidationError as e: 

18 raise APIError.InvalidSpace() from e 

19 

20 

21class HasAdminPermission(BasePermission): 

22 def has_permission(self, request, view): 

23 space = check_for_space(request) 

24 

25 api_key = view.get_api_key(request) 

26 if api_key.is_master_key: 

27 return True 

28 if any( 

29 permission.permission_type == PERMISSION_TYPES.ADMIN 

30 for permission in api_key.permissions.filter( 

31 space=space, 

32 approved=True, 

33 revoked=False, 

34 ) 

35 ): 

36 return True 

37 raise APIError.InvalidPermissions() 

38 

39 

40class HasFullAccessPermission(BasePermission): 

41 def has_permission(self, request, view): 

42 space = check_for_space(request) 

43 

44 api_key = view.get_api_key(request) 

45 if api_key.is_master_key: 

46 return True 

47 for permission in api_key.permissions.filter( 

48 space=space, 

49 approved=True, 

50 revoked=False, 

51 ): 

52 if permission.permission_type in [PERMISSION_TYPES.ADMIN, PERMISSION_TYPES.FULL_ACCESS]: 

53 return True 

54 raise APIError.InvalidPermissions() 

55 

56 

57class HasReadPermission(BasePermission): 

58 def has_permission(self, request, view): 

59 space = check_for_space(request) 

60 

61 api_key = view.get_api_key(request) 

62 if api_key.is_master_key: 

63 return True 

64 for permission in api_key.permissions.filter( 

65 space=space, 

66 approved=True, 

67 revoked=False, 

68 ): 

69 if permission.permission_type in [PERMISSION_TYPES.ADMIN, PERMISSION_TYPES.FULL_ACCESS, PERMISSION_TYPES.READ_ONLY]: 

70 return True 

71 raise APIError.InvalidPermissions() 

72 

73 

74class HasSpace(BasePermission): 

75 def has_permission(self, request, view): 

76 check_for_space(request) 

77 return True 

78 

79 

80class HasMasterKey(BasePermission): 

81 def has_permission(self, request, view): 

82 api_key = view.get_api_key(request) 

83 if api_key.is_master_key: 

84 return True 

85 raise APIError.InvalidPermissions()