python3.7下,orm用的是flasksqlalchemy,权限信息是放在mysql里的,有个adapter的库:casbin-sqlalchemy-adapter,不过当时使用有报错, 就参考着写了一下,主要就是实现一下persist.Adapter,先建一个model,用来存权限信息
# model.py
class CasbinRule(db.Model):
__tablename__ = 'casbin_rule'
id = Column("id", Integer, primary_key=True, autoincrement=True)
ptype = Column(String(255))
v0 = Column(String(255))
v1 = Column(String(255))
v2 = Column(String(255))
v3 = Column(String(255))
v4 = Column(String(255))
v5 = Column(String(255))
def __str__(self):
arr = [self.ptype]
for v in (self.v0, self.v1, self.v2, self.v3, self.v4, self.v5):
if v is None:
break
arr.append(v)
return ', '.join(arr)
def __repr__(self):
return ''.format(self.id, str(self))
数据库adaper,对上面model的存取操作
# casbin_adapter.py
import casbin
from casbin import persist
from alita.inc import db
from models import CasbinRule
class Adapter(persist.Adapter):
"""the interface for Casbin adapters."""
def __init__(self, engine):
self._engine = engine
self._session = engine.session
def load_policy(self, model):
"""loads all policy rules from the storage."""
lines = self._session.query(CasbinRule).all()
for line in lines:
persist.load_policy_line(str(line), model)
def _save_policy_line(self, ptype, rule):
line = CasbinRule(ptype=ptype)
for i, v in enumerate(rule):
setattr(line, 'v{}'.format(i), v)
self._session.add(line)
def _commit(self):
self._session.commit()
def save_policy(self, model):
"""saves all policy rules to the storage."""
query = self._session.query(CasbinRule)
query.delete()
for sec in ["p", "g"]:
if sec not in model.model.keys():
continue
for ptype, ast in model.model[sec].items():
for rule in ast.policy:
self._save_policy_line(ptype, rule)
self._commit()
return True
def add_policy(self, sec, ptype, rule):
"""adds a policy rule to the storage."""
self._save_policy_line(ptype, rule)
self._commit()
def remove_policy(self, sec, ptype, rule):
"""removes a policy rule from the storage."""
query = self._session.query(CasbinRule)
query = query.filter(CasbinRule.ptype == ptype)
for i, v in enumerate(rule):
query = query.filter(getattr(CasbinRule, 'v{}'.format(i)) == v)
r = query.delete()
self._commit()
return True if r > 0 else False
def remove_filtered_policy(self, sec, ptype, field_index, *field_values):
"""removes policy rules that match the filter from the storage.
This is part of the Auto-Save feature.
"""
query = self._session.query(CasbinRule)
query = query.filter(CasbinRule.ptype == ptype)
if not (0 <= field_index <= 5):
return False
if not (1 <= field_index + len(field_values) <= 6):
return False
for i, v in enumerate(field_values):
query = query.filter(getattr(CasbinRule, 'v{}'.format(field_index + i)) == v)
r = query.delete()
self._commit()
return True if r > 0 else False
def __del__(self):
self._session.close()
adapter = Adapter(db)
rbac = casbin.Enforcer('./rbac_model.conf', adapter, True)
然后搞一个装饰器,使用就在接口上带上就行,不再举例
# decorator.py
def verify_permission(func):
@wraps(func)
def wapper(*args, **kwargs):
role_id = current_identity.get('role_id')
# 这里我设置第一个角色是root,在配置里可以配置root不受任何限制
role = role_id ==1 and 'root' or str(role_id)
isok = rbac.enforce(role, request.path, str.lower(request.method))
if isok:
return func(*args, **kwargs)
else:
return jsonify(code='2000', msg='权限校验失败!')# code 自定义
return wapper
权限的配置和获取
# proc.py
def get_roles(school_id, page, per_page):
pagination = db.session.query(Role)\
.filter(Role.id > 1)\
.paginate(page=page, per_page=per_page, error_out=False)
ret = []
for item in pagination.items:
# 这个0是field_index
permissions = rbac.get_filtered_policy(0, str(item.id))
ret.append({
"id": item.id,
"name": item.name,
"permissions": [p[1] for p in permissions],
})
return pagination.total, ret
def modify_role(_id, **kwargs):
name = kwargs.get('name')
state = kwargs.get('state')
permissions = kwargs.get('permissions')
r = db.session.query(Role).filter(Role.id==_id).first()
if not r:
r = Role()
if name and r.name != name:
r1 = db.session.query(Role).filter(Role.name==name).first()
if r1:
return False, '此角色已存在!'
r.name = name
r.state = state or r.state
db.session.add(r)
db.session.commit()
# 修改权限就是全部重置
rbac.remove_filtered_policy(0, str(r.id))
for item in permissions:
rbac.add_policy(str(r.id), item.get('path'), item.get('method'))
return True, r
配置
# rbac_model.conf
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act || r.sub == "root"
end