-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathpermissions.py
More file actions
70 lines (54 loc) · 2.22 KB
/
permissions.py
File metadata and controls
70 lines (54 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""Public API for permissions management.
A permission is the authorization granted by a policy. It represents the
allowed actions(s) a subject can perform on an object. In Casbin, permissions
are not explicitly defined, but are inferred from the policy rules.
"""
from openedx_authz.api.data import (
ActionData,
PermissionData,
PolicyIndex,
ScopeData,
SubjectData,
)
from openedx_authz.engine.enforcer import enforcer
__all__ = [
"get_permission_from_policy",
"get_all_permissions_in_scope",
"has_permission",
]
def get_permission_from_policy(policy: list[str]) -> PermissionData:
"""Convert a Casbin policy list to a PermissionData object.
Args:
policy: A list representing a Casbin policy.
Returns:
PermissionData: The corresponding PermissionData object or an empty PermissionData if the policy is invalid.
"""
if len(policy) < 4: # Do not count ptype
return PermissionData(action=ActionData(namespaced_key=""), effect="allow")
return PermissionData(
action=ActionData(namespaced_key=policy[PolicyIndex.ACT.value]),
effect=policy[PolicyIndex.EFFECT.value],
)
def get_all_permissions_in_scope(scope: ScopeData) -> list[PermissionData]:
"""Retrieve all permissions associated with a specific scope.
Args:
scope: The scope to filter permissions by.
Returns:
list of PermissionData: A list of PermissionData objects associated with the given scope.
"""
actions = enforcer.get_filtered_policy(PolicyIndex.SCOPE.value, scope.namespaced_key)
return [get_permission_from_policy(action) for action in actions]
def has_permission(
subject: SubjectData,
action: ActionData,
scope: ScopeData,
) -> bool:
"""Check if a subject has a specific permission in a given scope.
Args:
subject: The subject to check (e.g., user or service).
action: The action to check (e.g., 'view_course').
scope: The scope in which to check the permission (e.g., 'course-v1:edX+DemoX+2021_T1').
Returns:
bool: True if the subject has the specified permission in the scope, False otherwise.
"""
return enforcer.enforce(subject.namespaced_key, action.namespaced_key, scope.namespaced_key)