11from casbin import persist
22from pymongo import MongoClient
33
4+
45class CasbinRule :
5- '''
6+ """
67 CasbinRule model
7- '''
8+ """
89
9- def __init__ (self , ptype = None , v0 = None , v1 = None , v2 = None , v3 = None , v4 = None , v5 = None ):
10+ def __init__ (
11+ self , ptype = None , v0 = None , v1 = None , v2 = None , v3 = None , v4 = None , v5 = None
12+ ):
1013 self .ptype = ptype
1114 self .v0 = v0
1215 self .v1 = v1
@@ -16,28 +19,33 @@ def __init__(self, ptype = None, v0 = None, v1 = None, v2 = None, v3 = None, v4
1619 self .v5 = v5
1720
1821 def dict (self ):
19- d = {' ptype' : self .ptype }
22+ d = {" ptype" : self .ptype }
2023
2124 for value in dir (self ):
22- if getattr (self , value ) is not None and value .startswith ('v' ) and value [1 :].isnumeric ():
25+ if (
26+ getattr (self , value ) is not None
27+ and value .startswith ("v" )
28+ and value [1 :].isnumeric ()
29+ ):
2330 d [value ] = getattr (self , value )
2431
2532 return d
2633
2734 def __str__ (self ):
28- return ', ' .join (self .dict ().values ())
35+ return ", " .join (self .dict ().values ())
2936
3037 def __repr__ (self ):
3138 return '<CasbinRule :"{}">' .format (str (self ))
3239
40+
3341class Adapter (persist .Adapter ):
3442 """the interface for Casbin adapters."""
3543
3644 def __init__ (self , uri , dbname , collection = "casbin_rule" ):
3745 """Create an adapter for Mongodb
3846
3947 Args:
40- uri (str): This should be the same requiement as pymongo Client's 'uri' parameter.
48+ uri (str): This should be the same requiement as pymongo Client's 'uri' parameter.
4149 See https://pymongo.readthedocs.io/en/stable/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient.
4250 dbname (str): Database to store policy.
4351 collection (str, optional): Collection of the choosen database. Defaults to "casbin_rule".
@@ -54,9 +62,9 @@ def load_policy(self, model):
5462 """
5563
5664 for line in self ._collection .find ():
57- if ' ptype' not in line :
65+ if " ptype" not in line :
5866 continue
59- rule = CasbinRule (line [' ptype' ])
67+ rule = CasbinRule (line [" ptype" ])
6068 for key , value in line .items ():
6169 setattr (rule , key , value )
6270
@@ -65,20 +73,20 @@ def load_policy(self, model):
6573 def _save_policy_line (self , ptype , rule ):
6674 line = CasbinRule (ptype = ptype )
6775 for index , value in enumerate (rule ):
68- setattr (line , f' v{ index } ' , value )
76+ setattr (line , f" v{ index } " , value )
6977 self ._collection .insert_one (line .dict ())
70-
78+
7179 def _find_policy_lines (self , ptype , rule ):
7280 line = CasbinRule (ptype = ptype )
7381 for index , value in enumerate (rule ):
74- setattr (line , f' v{ index } ' , value )
82+ setattr (line , f" v{ index } " , value )
7583 return self ._collection .find (line .dict ())
76-
84+
7785 def _delete_policy_lines (self , ptype , rule ):
7886 line = CasbinRule (ptype = ptype )
7987 for index , value in enumerate (rule ):
80- setattr (line , f' v{ index } ' , value )
81-
88+ setattr (line , f" v{ index } " , value )
89+
8290 # if rule is empty, do nothing
8391 # else find all given rules and delete them
8492 if len (line .dict ()) == 0 :
@@ -87,16 +95,19 @@ def _delete_policy_lines(self, ptype, rule):
8795 line_dict = line .dict ()
8896 line_dict_keys_len = len (line_dict )
8997 results = self ._collection .find (line_dict )
90- to_delete = [result ['_id' ] for result in results
91- if line_dict_keys_len == len (result .keys ()) - 1 ]
92- results = self ._collection .delete_many ({'_id' : {'$in' : to_delete }})
98+ to_delete = [
99+ result ["_id" ]
100+ for result in results
101+ if line_dict_keys_len == len (result .keys ()) - 1
102+ ]
103+ results = self ._collection .delete_many ({"_id" : {"$in" : to_delete }})
93104 return results .deleted_count
94-
105+
95106 def save_policy (self , model ) -> bool :
96107 """Implement add Interface for casbin. Save the policy in mongodb
97108
98109 Args:
99- model (Class Model): Casbin Model which loads from .conf file usually.
110+ model (Class Model): Casbin Model which loads from .conf file usually.
100111
101112 Returns:
102113 bool: True if succeed
@@ -129,7 +140,7 @@ def remove_policy(self, sec, ptype, rule):
129140 Args:
130141 ptype (str): Policy type, 'g', 'g2', 'p', etc.
131142 rule (CasbinRule): Casbin rule if it is exactly same as will be removed.
132-
143+
133144 Returns:
134145 Number: Number of policies be removed
135146 """
@@ -144,17 +155,18 @@ def remove_filtered_policy(self, sec, ptype, field_index, *field_values):
144155 ptype (str): Policy type, 'g', 'g2', 'p', etc.
145156 rule (CasbinRule): Casbin rule will be removed
146157 field_index (int): The policy index at which the filed_values begins filtering. Its range is [0, 5]
147- field_values(List[str]): A list of rules to filter policy which starts from
158+ field_values(List[str]): A list of rules to filter policy which starts from
148159
149160 Returns:
150161 bool: True if succeed else False
151162 """
152- if not (0 <= field_index <= 5 ):
163+ if not (0 <= field_index <= 5 ):
153164 return False
154165 if not (1 <= field_index + len (field_values ) <= 6 ):
155166 return False
156- query = {f'v{ index + field_index } ' : value
157- for index , value in enumerate (field_values )}
158- query ['ptype' ] = ptype
167+ query = {
168+ f"v{ index + field_index } " : value for index , value in enumerate (field_values )
169+ }
170+ query ["ptype" ] = ptype
159171 results = self ._collection .delete_many (query )
160172 return results .deleted_count > 0
0 commit comments