Skip to content

Commit

Permalink
ci: code reformatted and linter tests added (#11)
Browse files Browse the repository at this point in the history
Signed-off-by: ffyuanda <46557895+ffyuanda@users.noreply.github.com>
  • Loading branch information
ffyuanda committed Jul 28, 2021
1 parent 9297043 commit d3cb83a
Show file tree
Hide file tree
Showing 5 changed files with 187 additions and 144 deletions.
14 changes: 14 additions & 0 deletions .github/workflows/main.yml
Expand Up @@ -46,6 +46,20 @@ jobs:
COVERALLS_FLAG_NAME: ${{ matrix.os }} - ${{ matrix.python-version }}
COVERALLS_PARALLEL: true

lint:
name: Run Linters
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2

- name: Super-Linter
uses: github/super-linter@v4.2.2
env:
VALIDATE_PYTHON_BLACK: true
DEFAULT_BRANCH: master
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

coveralls:
name: Indicate completion to coveralls.io
needs: test
Expand Down
2 changes: 1 addition & 1 deletion casbin_pymongo_adapter/__init__.py
@@ -1 +1 @@
from .adapter import Adapter
from .adapter import Adapter
64 changes: 38 additions & 26 deletions casbin_pymongo_adapter/adapter.py
@@ -1,12 +1,15 @@
from casbin import persist
from pymongo import MongoClient


class CasbinRule:
'''
"""
CasbinRule model
'''
"""

def __init__(self, ptype = None, v0 = None, v1 = None, v2 = None, v3 = None, v4 = None, v5 = None):
def __init__(
self, ptype=None, v0=None, v1=None, v2=None, v3=None, v4=None, v5=None
):
self.ptype = ptype
self.v0 = v0
self.v1 = v1
Expand All @@ -16,28 +19,33 @@ def __init__(self, ptype = None, v0 = None, v1 = None, v2 = None, v3 = None, v4
self.v5 = v5

def dict(self):
d = {'ptype': self.ptype}
d = {"ptype": self.ptype}

for value in dir(self):
if getattr(self, value) is not None and value.startswith('v') and value[1:].isnumeric():
if (
getattr(self, value) is not None
and value.startswith("v")
and value[1:].isnumeric()
):
d[value] = getattr(self, value)

return d

def __str__(self):
return ', '.join(self.dict().values())
return ", ".join(self.dict().values())

def __repr__(self):
return '<CasbinRule :"{}">'.format(str(self))


class Adapter(persist.Adapter):
"""the interface for Casbin adapters."""

def __init__(self, uri, dbname, collection="casbin_rule"):
"""Create an adapter for Mongodb
Args:
uri (str): This should be the same requiement as pymongo Client's 'uri' parameter.
uri (str): This should be the same requiement as pymongo Client's 'uri' parameter.
See https://pymongo.readthedocs.io/en/stable/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient.
dbname (str): Database to store policy.
collection (str, optional): Collection of the choosen database. Defaults to "casbin_rule".
Expand All @@ -54,9 +62,9 @@ def load_policy(self, model):
"""

for line in self._collection.find():
if 'ptype' not in line:
if "ptype" not in line:
continue
rule = CasbinRule(line['ptype'])
rule = CasbinRule(line["ptype"])
for key, value in line.items():
setattr(rule, key, value)

Expand All @@ -65,20 +73,20 @@ def load_policy(self, model):
def _save_policy_line(self, ptype, rule):
line = CasbinRule(ptype=ptype)
for index, value in enumerate(rule):
setattr(line, f'v{index}', value)
setattr(line, f"v{index}", value)
self._collection.insert_one(line.dict())

def _find_policy_lines(self, ptype, rule):
line = CasbinRule(ptype=ptype)
for index, value in enumerate(rule):
setattr(line, f'v{index}', value)
setattr(line, f"v{index}", value)
return self._collection.find(line.dict())

def _delete_policy_lines(self, ptype, rule):
line = CasbinRule(ptype=ptype)
for index, value in enumerate(rule):
setattr(line, f'v{index}', value)
setattr(line, f"v{index}", value)

# if rule is empty, do nothing
# else find all given rules and delete them
if len(line.dict()) == 0:
Expand All @@ -87,16 +95,19 @@ def _delete_policy_lines(self, ptype, rule):
line_dict = line.dict()
line_dict_keys_len = len(line_dict)
results = self._collection.find(line_dict)
to_delete = [result['_id'] for result in results
if line_dict_keys_len == len(result.keys()) - 1]
results = self._collection.delete_many({'_id' : {'$in': to_delete}})
to_delete = [
result["_id"]
for result in results
if line_dict_keys_len == len(result.keys()) - 1
]
results = self._collection.delete_many({"_id": {"$in": to_delete}})
return results.deleted_count

def save_policy(self, model) -> bool:
"""Implement add Interface for casbin. Save the policy in mongodb
Args:
model (Class Model): Casbin Model which loads from .conf file usually.
model (Class Model): Casbin Model which loads from .conf file usually.
Returns:
bool: True if succeed
Expand Down Expand Up @@ -129,7 +140,7 @@ def remove_policy(self, sec, ptype, rule):
Args:
ptype (str): Policy type, 'g', 'g2', 'p', etc.
rule (CasbinRule): Casbin rule if it is exactly same as will be removed.
Returns:
Number: Number of policies be removed
"""
Expand All @@ -144,17 +155,18 @@ def remove_filtered_policy(self, sec, ptype, field_index, *field_values):
ptype (str): Policy type, 'g', 'g2', 'p', etc.
rule (CasbinRule): Casbin rule will be removed
field_index (int): The policy index at which the filed_values begins filtering. Its range is [0, 5]
field_values(List[str]): A list of rules to filter policy which starts from
field_values(List[str]): A list of rules to filter policy which starts from
Returns:
bool: True if succeed else False
"""
if not (0 <= field_index <=5):
if not (0 <= field_index <= 5):
return False
if not (1 <= field_index + len(field_values) <= 6):
return False
query = {f'v{index + field_index}' : value
for index, value in enumerate(field_values)}
query['ptype'] = ptype
query = {
f"v{index + field_index}": value for index, value in enumerate(field_values)
}
query["ptype"] = ptype
results = self._collection.delete_many(query)
return results.deleted_count > 0
13 changes: 11 additions & 2 deletions setup.py
Expand Up @@ -24,7 +24,16 @@
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/pycasbin/pymongo-adapter",
keywords=["casbin", "pymongo", "casbin-adapter", "rbac", "access control", "abac", "acl", "permission"],
keywords=[
"casbin",
"pymongo",
"casbin-adapter",
"rbac",
"access control",
"abac",
"acl",
"permission",
],
packages=find_packages(),
install_requires=install_requires,
python_requires=">=3.6",
Expand All @@ -37,4 +46,4 @@
"Operating System :: OS Independent",
],
data_files=[desc_file],
)
)

0 comments on commit d3cb83a

Please sign in to comment.