aboutsummaryrefslogtreecommitdiffstats
path: root/permission.py
blob: 310cef29ee8a58240b4f52cd2e366407a760d516 (plain)
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
# -*- coding: utf-8 -*-
#TODO : move the globals to a config file (use the config file parser module)
PERM_LIST=['READ','MODIFY','APPEND'] #just add a string here to define a new permission
PERMS = len(PERM_LIST)
MAX = (1<<PERMS)-1

class PermissionError(Exception) :
    def __init__(self,error_string) :
        self.error = error_string
        
    def __str__(self) :
        str(self.error)

class Permission :
    
    def __init__(self,init) : 
        if isinstance(init,int) :
            if (init > MAX) or (init < 0) :
                raise PermissionError('Permission int not in correct range')
            result = []
            for shift in range(PERMS-1,-1,-1) :
                if init>>shift :
                    result.append(PERM_LIST[shift])
                    init = init-(1<<shift)
            self.perm_list = result
        elif isinstance(init,list) :
            if (set(init) <= set(PERM_LIST)) :
                self.perm_list = init
            else :
                raise PermissionError('Undefined permission')
            
    def __str__(self) :
        return str(self.perm_list)
        
    def toInt(self) :
        result = 0
        for i,perm in enumerate(PERM_LIST) :
            if perm in self.perm_list :
                result += 1<<i
        return result
        
if __name__== '__main__' :
    for i in range(MAX+1) :
        print i, Permission(i), Permission(i).toInt()