sio-2425/delivery2/server/utils/perms.py

60 lines
1.6 KiB
Python

from enum import Enum
class Perm(Enum):
DOC_ACL = 0b000000000001
DOC_READ = 0b000000000010
DOC_DELETE = 0b000000000100
ROLE_ACL = 0b000000001000
SUBJECT_NEW = 0b000000010000
SUBJECT_DOWN = 0b000000100000
SUBJECT_UP = 0b000001000000
DOC_NEW = 0b000010000000
ROLE_NEW = 0b000100000000
ROLE_DOWN = 0b001000000000
ROLE_UP = 0b010000000000
ROLE_MOD = 0b100000000000
def __str__(self):
bit = 0
value = self.value
while not value & 0b1:
bit += 1
value >>= 1
return f"{self.name}({bit})"
@staticmethod
def from_str(perm_name):
for perm in Perm:
if perm.name == perm_name:
return perm
@staticmethod
def get_perms(bit_array: int, return_str=False):
perms = []
bit = 0b1
for perm in Perm:
if (bit_array & bit) == (perm.value & 0b1):
perms.append(perm)
bit >>= 1
return [str(p) for p in perms] if return_str else perms
@staticmethod
def get_int(perms):
if isinstance(perms, list):
return sum([p.value for p in perms if isinstance(p, Perm)])
return perms.value if isinstance(perms, Perm) else 0
@staticmethod
def check_perm(perms_array: int, perm_to_check: int):
return perms_array & perm_to_check == perm_to_check
class PermOperation(Enum):
ADD = 0
REMOVE = 1
@staticmethod
def calc(bit_array: int, perm: Perm, operation) -> int:
if operation == PermOperation.ADD:
return bit_array | perm.value
return bit_array & ~perm.value