[middleware] convert acl_middleware function to class

This commit is contained in:
Maxime Alves LIRMM 2020-07-07 11:20:24 +02:00
parent 65e0d09ff8
commit 26e0bb8716
1 changed files with 23 additions and 21 deletions

View File

@ -1,31 +1,33 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from starlette.requests import Request from starlette.requests import Request
from starlette.exceptions import HTTPException from starlette.exceptions import HTTPException
from starlette.middleware.base import BaseHTTPMiddleware
async def acl_middleware(request: Request, call_next): class AclMiddleware(BaseHTTPMiddleware):
""" Checks the "acls" key in the scope and applies the async def dispatch(self, request: Request, call_next):
corresponding functions in the current module's acl lib. """ Checks the "acls" key in the scope and applies the
corresponding functions in the current module's acl lib.
Raises an exception if no acl function returns True Raises an exception if no acl function returns True
""" """
print(f'Hit acl {__name__} middleware') print(f'Hit acl {__name__} middleware')
for acl_fnct_name in request.scope['acls']: for acl_fnct_name in request.scope['acls']:
print(f'Will apply {acl_fnct_name}') print(f'Will apply {acl_fnct_name}')
try: try:
fct = getattr(acl, acl_fct_name) fct = getattr(acl, acl_fct_name)
if fct(request) is True: if fct(request) is True:
print(f'{fct} : {fct(request)}\n') print(f'{fct} : {fct(request)}\n')
return await call_next(request) return await call_next(request)
except AttributeError as e: except AttributeError as e:
print(f'No ACL function "{acl_fct_name}" in {__name__} module') print(f'No ACL function "{acl_fct_name}" in {__name__} module')
print(e) print(e)
break break
except Exception as e: except Exception as e:
print(e) print(e)
raise HTTPException(500) raise HTTPException(500)
raise HTTPException(401) raise HTTPException(401)