def get_enforcer(): adapter = Adapter('mongodb://localhost:27017', 'casbin_test') e = casbin.Enforcer(get_fixture('rbac_model.conf'), adapter, True) model = e.get_model() model.clear_policy() model.add_policy('p', 'p', ['alice', 'data1', 'read']) adapter.save_policy(model) model.clear_policy() model.add_policy('p', 'p', ['bob', 'data2', 'write']) adapter.save_policy(model) model.clear_policy() model.add_policy('p', 'p', ['data2_admin', 'data2', 'read']) adapter.save_policy(model) model.clear_policy() model.add_policy('p', 'p', ['data2_admin', 'data2', 'write']) adapter.save_policy(model) model.clear_policy() model.add_policy('g', 'g', ['alice', 'data2_admin']) adapter.save_policy(model) return casbin.Enforcer(get_fixture('rbac_model.conf'), adapter, True)
def __init__(self, get_response): self.get_response = get_response # Initialize the Casbin enforcer, executed only on once. self.enforcer = casbin.Enforcer("casbin_middleware/authz_model.conf", "casbin_middleware/authz_policy2.csv") a = mysqladapter.DBAdapter( "mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/") e = casbin.Enforcer("path/to/basic_model.conf", a)
def test_save_policy(self): model = casbin.Enforcer(get_fixture('rbac_model.conf'), get_fixture('rbac_policy.csv')).model self.adapter.save_policy(model) e = casbin.Enforcer(get_fixture('rbac_model.conf'), self.adapter) self.assertTrue(e.enforce('alice', 'data1', 'read')) self.assertFalse(e.enforce('bob', 'data1', 'read')) self.assertTrue(e.enforce('bob', 'data2', 'write')) self.assertTrue(e.enforce('alice', 'data2', 'read')) self.assertTrue(e.enforce('alice', 'data2', 'write'))
def test_save_policy(self): ''' test save_policy ''' model = casbin.Enforcer(get_fixture('rbac_model.conf'), get_fixture('rbac_policy.csv')).model adapter = Adapter(dbname='casbin_test', host='mongodb://localhost:27017') adapter.save_policy(model) e = casbin.Enforcer(get_fixture('rbac_model.conf'), adapter) self.assertTrue(e.enforce('alice', 'data1', 'read')) self.assertFalse(e.enforce('bob', 'data1', 'read')) self.assertTrue(e.enforce('bob', 'data2', 'write')) self.assertTrue(e.enforce('alice', 'data2', 'read')) self.assertTrue(e.enforce('alice', 'data2', 'write'))
def verify_permission(*args): # username, path, method adapter = DjangoAdapter(CasBinPermissionRule, RoleBind) model_conf_file = os.path.join(settings.BASE_DIR, "conf", "rbac_model.conf") e = casbin.Enforcer(model_conf_file, adapter=adapter) return e.enforce(*args)
def test_filtered_adapter_empty_filepath(self): adapter = casbin.persist.adapters.FilteredAdapter("") e = casbin.Enforcer(get_examples("rbac_with_domains_model.conf"), adapter) with self.assertRaises(RuntimeError): e.load_filtered_policy(None)
def verify_permission(username, uri, method): # username, path, method adapter = DjangoAdapter(CasbinRule) model_conf_file = os.path.join(BASE_DIR, "config", "keymatch_model.conf") e = casbin.Enforcer(model_conf_file, adapter=adapter) # e = casbin.Enforcer("path/to/model.conf", "path/to/policy.csv") return e.enforce(username, uri, method) # e.enforce(username, uri, method)
def test_load_filtered_policy(self): adapter = casbin.persist.adapters.FilteredAdapter( get_examples("rbac_with_domains_policy.csv")) e = casbin.Enforcer(get_examples("rbac_with_domains_model.conf"), adapter) filter = Filter() filter.P = ["", "domain1"] filter.G = ["", "", "domain1"] try: e.load_policy() except: raise RuntimeError("unexpected error in LoadFilteredPolicy") self.assertTrue(e.has_policy(["admin", "domain1", "data1", "read"])) self.assertTrue(e.has_policy(["admin", "domain2", "data2", "read"])) try: e.load_filtered_policy(filter) except: raise RuntimeError("unexpected error in LoadFilteredPolicy") if not e.is_filtered: raise RuntimeError( "adapter did not set the filtered flag correctly") self.assertTrue(e.has_policy(["admin", "domain1", "data1", "read"])) self.assertFalse(e.has_policy(["admin", "domain2", "data2", "read"])) with self.assertRaises(RuntimeError): e.save_policy() with self.assertRaises(RuntimeError): e.get_adapter().save_policy(e.get_model())
def init_app(self, app): self.app = app self.e = casbin.Enforcer(app.config.get("CASBIN_MODEL"), self.adapter) if self.watcher: self.e.set_watcher(self.watcher) self.user_name_headers = app.config.get("CASBIN_USER_NAME_HEADERS", None)
def test_add_policy(self): ''' test add_policy ''' adapter = Adapter('mongodb://localhost:27017', 'casbin_rule') e = casbin.Enforcer(get_fixture('rbac_model.conf'), adapter, True) adapter.add_policy(sec=None, ptype='p', rule=['alice', 'data1', 'read']) adapter.add_policy(sec=None, ptype='p', rule=['bob', 'data2', 'write']) adapter.add_policy(sec=None, ptype='p', rule=['data2_admin', 'data2', 'read']) adapter.add_policy(sec=None, ptype='p', rule=['data2_admin', 'data2', 'write']) adapter.add_policy(sec=None, ptype='g', rule=['alice', 'data2_admin']) e.load_policy() self.assertFalse(e.enforce('alice', 'data1', 'write')) self.assertFalse(e.enforce('bob', 'data1', 'read')) self.assertTrue(e.enforce('bob', 'data2', 'write')) self.assertTrue(e.enforce('alice', 'data2', 'read')) self.assertTrue(e.enforce('alice', 'data2', 'write')) self.assertFalse(e.enforce('bogus', 'data2', 'write'))
def test_filtered_adapter_invalid_filepath(self): adapter = casbin.persist.adapters.FilteredAdapter( "examples/does_not_exist_policy.csv") e = casbin.Enforcer("examples/rbac_with_domains_model.conf", adapter) with self.assertRaises(FileNotFoundError): e.load_filtered_policy(None)
def verify_permission(*args): # username, path, method adapter = DjangoAdapter(PermRule, RoleBind) model_conf_file = os.path.join(settings.ROOT_DIR, "config", "keymatch_model.conf") e = casbin.Enforcer(model_conf_file, adapter=adapter) return e.enforce(*args)
def test_append_filtered_policy(self): adapter = casbin.persist.adapters.FilteredAdapter( "examples/rbac_with_domains_policy.csv") e = casbin.Enforcer("examples/rbac_with_domains_model.conf", adapter) filter = Filter() filter.P = ["", "domain1"] filter.G = ["", "", "domain1"] try: e.load_policy() except: raise RuntimeError("nexpected error in LoadFilteredPolicy") self.assertTrue(e.has_policy(['admin', 'domain1', 'data1', 'read'])) self.assertTrue(e.has_policy(['admin', 'domain2', 'data2', 'read'])) try: e.load_filtered_policy(filter) except: raise RuntimeError("unexpected error in LoadFilteredPolicy") if not e.is_filtered: raise RuntimeError( "adapter did not set the filtered flag correctly") self.assertTrue(e.has_policy(['admin', 'domain1', 'data1', 'read'])) self.assertFalse(e.has_policy(['admin', 'domain2', 'data2', 'read'])) filter.P = ["", "domain2"] filter.G = ["", "", "domain2"] try: e.load_increment_filtered_policy(filter) except: raise RuntimeError("unexpected error in LoadFilteredPolicy") self.assertTrue(e.has_policy(['admin', 'domain1', 'data1', 'read'])) self.assertTrue(e.has_policy(['admin', 'domain2', 'data2', 'read']))
def test_add_policy(self): adapter = Adapter('sqlite://') e = casbin.Enforcer(get_fixture('rbac_model.conf'), adapter, True) try: self.assertFalse(e.enforce('alice', 'data1', 'read')) self.assertFalse(e.enforce('bob', 'data1', 'read')) self.assertFalse(e.enforce('bob', 'data2', 'write')) self.assertFalse(e.enforce('alice', 'data2', 'read')) self.assertFalse(e.enforce('alice', 'data2', 'write')) except simpleeval.NameNotDefined: # This is caused by an upstream bug when there is no policy loaded # Should be resolved in pycasbin >= 0.3 pass adapter.add_policy(sec=None, ptype='p', rule=['alice', 'data1', 'read']) adapter.add_policy(sec=None, ptype='p', rule=['bob', 'data2', 'write']) adapter.add_policy(sec=None, ptype='p', rule=['data2_admin', 'data2', 'read']) adapter.add_policy(sec=None, ptype='p', rule=['data2_admin', 'data2', 'write']) adapter.add_policy(sec=None, ptype='g', rule=['alice', 'data2_admin']) e.load_policy() self.assertTrue(e.enforce('alice', 'data1', 'read')) self.assertFalse(e.enforce('bob', 'data1', 'read')) self.assertTrue(e.enforce('bob', 'data2', 'write')) self.assertTrue(e.enforce('alice', 'data2', 'read')) self.assertTrue(e.enforce('alice', 'data2', 'write')) self.assertFalse(e.enforce('bogus', 'data2', 'write'))
def get(self, request, *args, **kwargs): """ casbin - http://casbin.51reboot.com/api/v1/auth http://casbin.51reboot.com/api/v1/auth?token=xxx&path=xxx&method=xxx """ data = request.query_params path, method = data.get('path', None), data.get('method', None) if not path or not method: return JSONApiResponse(code=400, message='path and method is required.') adapter_rule = DjangoAdapter(CasbinRule) e = casbin.Enforcer( 'permission/rbac_model2.conf', adapter=adapter_rule, enable_log=False, ) e.add_function("keyMatchMethod", key_match_method_func) print("casbin: ", request.user.username, path, method) if e.enforce(request.user.username, path, method): return JSONApiResponse(code=0, message='Permission auth ok..') else: return JSONApiResponse(code=-1, message='Permission auth fail.')
def get_casbin() -> casbin.Enforcer: adapter = casbin_sqlalchemy_adapter.Adapter(engine) e = casbin.Enforcer(settings.CASBIN_MODEL_PATH, adapter, True) # e.add_function("ParamsMatch", params_match_func) return e
def create_app(config=None): """ initialize application """ global app, db app = Flask(__name__) print("create app(%s) id:%s" % (__name__, id(app))) assert config # load config path x = app.config.from_pyfile(config, silent=False) # --------- DB ----------------- db = SQLAlchemy(app) print("create db id:%s via %r" % (id(db), SQLAlchemy)) from inc import casbin_adapter install_models(app.config['INSTALLED_APPS']) assert db db.create_all() casbin_adapter.adapter = casbin_adapter.Adapter(db) casbin_adapter.rbac = casbin.Enforcer(app.config["CASBIN_CONFIG_PATH"], casbin_adapter.adapter, False) install() if app.config.get('DEBUG'): app.before_request(befor_request_callbacks) app.after_request(after_request_callbacks) return app
def init_auth(self, app): from casbin_test.auth.casbin_adapter import CasbinAdapter adapter = CasbinAdapter(app) file_path = os.path.join(os.getcwd(),'casbin_test','auth','policy.conf') enforcer = casbin.Enforcer(file_path, adapter) self.enforcer = enforcer self.enforcer.auto_save = True
def IsPermissionVerify(username, path, method): adapter_rule = DjangoAdapter(CasbinRule) model_conf_file = os.path.join(settings.BASE_DIR, "conf", "keymatch_model.conf") print("model_conf_file", model_conf_file) print(username, path, method) e = casbin.Enforcer(model_conf_file, adapter=adapter_rule) # e.add_function("keyMatchMethod", key_match_method_func) return e.enforce(username, path, method)
def test_unsupported_filtered_policy(self): e = casbin.Enforcer("examples/rbac_with_domains_model.conf", "examples/rbac_with_domains_policy.csv") filter = Filter() filter.P = ["", "domain1"] filter.G = ["", "", "domain1"] with self.assertRaises(ValueError): e.load_filtered_policy(filter)
def test_filtered_policy_invalid_filter(self): adapter = casbin.persist.adapters.FilteredAdapter( "examples/rbac_with_domains_policy.csv") e = casbin.Enforcer("examples/rbac_with_domains_model.conf", adapter) filter = ["", "domain1"] with self.assertRaises(RuntimeError): e.load_filtered_policy(filter)
def test_autosave_on_persists_to_db(self): adapter = Adapter() e = casbin.Enforcer(get_fixture('rbac_model.conf'), adapter) e.enable_auto_save(True) e.add_policy('alice', 'data1', 'write') e.load_policy() policies = e.get_policy() self.assertListEqual(policies, [['alice', 'data1', 'write']])
def get_casbin() -> casbin.Enforcer: adapter = casbin_sqlalchemy_adapter.Adapter(engine) # path = settings.CASBIN_MODEL_PATH # with open(path,'r') as f: # data = f.read() # print(data) e = casbin.Enforcer(settings.CASBIN_MODEL_PATH, adapter) # e.add_function("ParamsMatch", params_match_func) return e
def app_fixture(): enforcer = casbin.Enforcer(get_examples("rbac_model.conf"), get_examples("rbac_policy.csv")) app = FastAPI() app.add_middleware(CasbinMiddleware, enforcer=enforcer) app.add_middleware(AuthenticationMiddleware, backend=BasicAuth()) yield app
def _load_policy(self): ctx = _request_ctx_stack.top if self.policy_callback is None: raise Exception("No policy_loader has been installed for this " "CasbinManager.") ctx.enforcer = casbin.Enforcer( current_app.config.get("CASBIN_MODEL_CONF"), self.policy_callback(), )
def __init__(self, app, adapter, watcher=None): """ Args: app (object): Flask App object to get Casbin Model adapter (object): Casbin Adapter """ self.app = app self.adapter = adapter self.e = casbin.Enforcer(app.config.get("CASBIN_MODEL"), self.adapter, True) if watcher: self.e.set_watcher(watcher)
def get_enforcer(): adapter = Adapter() CasbinRule.objects.bulk_create([ CasbinRule(ptype='p', v0='alice', v1='data1', v2='read'), CasbinRule(ptype='p', v0='bob', v1='data2', v2='write'), CasbinRule(ptype='p', v0='data2_admin', v1='data2', v2='read'), CasbinRule(ptype='p', v0='data2_admin', v1='data2', v2='write'), CasbinRule(ptype='g', v0='alice', v1='data2_admin'), ]) return casbin.Enforcer(get_fixture('rbac_model.conf'), adapter, True)
def get_enforcer(): con_string = "sqlite:/:memory:" adapter = Adapter(con_string) CasbinRule.createTable(ifNotExists=True) CasbinRule(ptype="p", v0="alice", v1="data1", v2="read") CasbinRule(ptype="p", v0="bob", v1="data2", v2="write") CasbinRule(ptype="p", v0="data2_admin", v1="data2", v2="read") CasbinRule(ptype="p", v0="data2_admin", v1="data2", v2="write") CasbinRule(ptype="g", v0="alice", v1="data2_admin") return casbin.Enforcer(get_fixture("rbac_model.conf"), adapter)
def update_item_state(): """This is where the user will attempt to make specific access requests and will have to face ACL """ try: input = RSAMethods.decrypt(request.get_data()) print(input) req = json.loads(input) print(req) except: print("ERROR: Request was not parsed from JSON") add_request_data("Item_Request", "Update_Item_State", "2", "Not_Correctly_Encrypted", time.time()) return "2" try: val = req["key"] opt = req["option"] sub = req["subject"] obj = req["object"] act = req["action"] except: add_request_data("Item_Request", "Update_Item_State", "3", "Lacking_Policy_Credentials", time.time()) print("ERROR: Policy Credentials not found") return "3" print("Enforcement Point") if obj == "items": print("Is Object") e = casbin.Enforcer("acl.conf", "policies.csv") if e.enforce(sub, obj, act): print("Successful Access") print(val) print(str(opt).upper()) r = requests.post("http://localhost:8080/rest/items/" + str(val), data=str(opt).upper()) print(r.text) add_request_data("Item_Request", "Update_Item_State", "1", "NULL", time.time()) print("Item Option Updated") return "1" else: add_request_data("Item_Request", "Update_Item_State", "4", "Insufficient_Access_Credentials", time.time()) # deny the request, show an error print("Request Denied Due To Lack Of Permissions") return "4" else: return "3" return "6"
def __init__(self, app, adapter, watcher=None): """ Args: app (object): Flask App object to get Casbin Model adapter (object): Casbin Adapter """ self.app = app self.adapter = adapter self.e = casbin.Enforcer(app.config.get("CASBIN_MODEL"), self.adapter) if watcher: self.e.set_watcher(watcher) self._owner_loader = None self.user_name_headers = app.config.get("CASBIN_USER_NAME_HEADERS", None)