fate_casbin.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import casbin
  2. import casbin_sqlalchemy_adapter
  3. import pymysql
  4. from fate_flow.db.db_models import singleton
  5. from fate_flow.settings import CASBIN_MODEL_CONF, DATABASE, CASBIN_TABLE_NAME, PERMISSION_SWITCH
  6. from sqlalchemy import Column, Integer, String, TEXT, create_engine
  7. pymysql.install_as_MySQLdb()
  8. class FateCasbinRule(casbin_sqlalchemy_adapter.Base):
  9. __tablename__ = CASBIN_TABLE_NAME
  10. id = Column(Integer, primary_key=True)
  11. ptype = Column(String(255))
  12. v0 = Column(String(255))
  13. v1 = Column(String(255))
  14. v2 = Column(TEXT())
  15. v3 = Column(Integer())
  16. v4 = Column(String(255))
  17. v5 = Column(String(255))
  18. def __str__(self):
  19. arr = [self.ptype]
  20. for v in (self.v0, self.v1, self.v2, self.v3, self.v4, self.v5):
  21. if v is None:
  22. break
  23. arr.append(v)
  24. return ", ".join(arr)
  25. def __repr__(self):
  26. return '<FateCasbinRule {}: "{}">'.format(self.id, str(self))
  27. @singleton
  28. class FateCasbin():
  29. def __init__(self):
  30. self.engine = create_engine(
  31. f"mysql://{DATABASE.get('user')}:{DATABASE.get('passwd')}@{DATABASE.get('host')}:{DATABASE.get('port')}/{DATABASE.get('name')}")
  32. self.adapter = casbin_sqlalchemy_adapter.Adapter(self.engine, FateCasbinRule)
  33. self.e = casbin.Enforcer(CASBIN_MODEL_CONF, self.adapter)
  34. def query(self, party_id):
  35. self.e.load_policy()
  36. return self.e.get_permissions_for_user(party_id)
  37. def delete(self, party_id, type, value):
  38. self.e.load_policy()
  39. return self.e.delete_permission_for_user(party_id, type, value)
  40. def delete_all(self, party_id, type):
  41. self.e.load_policy()
  42. return self.e.remove_filtered_policy(0, party_id, type)
  43. def grant(self, party_id, type, value):
  44. self.e.load_policy()
  45. return self.e.add_permission_for_user(party_id, type, value)
  46. def enforce(self, party_id, type, value):
  47. self.e.load_policy()
  48. try:
  49. return self.e.enforce(party_id, type, str(value))
  50. except Exception as e:
  51. raise Exception(f"{party_id}, {type}, {value} {e}")
  52. CB = FateCasbin() if PERMISSION_SWITCH else None