|
| 1 | +from django.conf import settings |
| 2 | +from django.db import connection |
| 3 | +from django.db.utils import OperationalError, ProgrammingError |
| 4 | + |
| 5 | +from casbin import Enforcer |
| 6 | + |
| 7 | +from .adapter import Adapter |
| 8 | + |
| 9 | + |
| 10 | +class ProxyEnforcer(Enforcer): |
| 11 | + _initialized = False |
| 12 | + |
| 13 | + def __init__(self, *args, **kwargs): |
| 14 | + if self._initialized: |
| 15 | + super().__init__(*args, **kwargs) |
| 16 | + |
| 17 | + def _load(self): |
| 18 | + if self._initialized == False: |
| 19 | + self._initialized = True |
| 20 | + model = getattr(settings, 'CASBIN_MODEL') |
| 21 | + enable_log = getattr(settings, 'CASBIN_LOG_ENABLED', False) |
| 22 | + adapter = Adapter() |
| 23 | + |
| 24 | + super().__init__(model, adapter, enable_log) |
| 25 | + |
| 26 | + watcher = getattr(settings, 'CASBIN_WATCHER', None) |
| 27 | + if watcher: |
| 28 | + self.set_watcher(watcher) |
| 29 | + |
| 30 | + role_manager = getattr(settings, 'CASBIN_ROLE_MANAGER', None) |
| 31 | + if role_manager: |
| 32 | + self.set_role_manager(role_manager) |
| 33 | + |
| 34 | + def __getattribute__(self, name): |
| 35 | + safe_methods = ['__init__', '_load', '_initialized'] |
| 36 | + if not super().__getattribute__('_initialized') and name not in safe_methods: |
| 37 | + initialize_enforcer() |
| 38 | + if not super().__getattribute__('_initialized'): |
| 39 | + raise Exception(( |
| 40 | + "Calling enforcer attributes before django registry is ready. " |
| 41 | + "Prevent making any calls to the enforcer on import/startup" |
| 42 | + )) |
| 43 | + |
| 44 | + return super().__getattribute__(name) |
| 45 | + |
| 46 | + |
| 47 | +enforcer = ProxyEnforcer() |
| 48 | + |
| 49 | + |
| 50 | +def initialize_enforcer(): |
| 51 | + try: |
| 52 | + with connection.cursor() as cursor: |
| 53 | + cursor.execute( |
| 54 | + """ |
| 55 | + SELECT app, name applied FROM django_migrations |
| 56 | + WHERE app = 'casbin_adapter' AND name = '0001_initial'; |
| 57 | + """ |
| 58 | + ) |
| 59 | + row = cursor.fetchone() |
| 60 | + if row: |
| 61 | + enforcer._load() |
| 62 | + except (OperationalError, ProgrammingError): |
| 63 | + pass |
| 64 | + |
0 commit comments