[exceptions] add exception handlers, moved AclCallerMiddleware to lib

This commit is contained in:
Maxime Alves LIRMM 2020-07-08 12:45:01 +02:00 committed by Maxime Alves LIRMM@home
parent 3fda051180
commit 24673e4408
2 changed files with 44 additions and 14 deletions

View File

@ -20,10 +20,11 @@ RequestResponseEndpoint = Callable[ [Request], Awaitable[Response] ]
from .models.api.domain import Domain
# module libraries
from .lib.responses import *
from .lib.jwt_middleware import JWTAuthenticationBackend
from .lib.acl_caller_middleware import AclCallerMiddleware
from .lib.responses import *
def mount_domains(app: ASGIApp, domains: list):
""" Procedure to mount the registered domains on their prefixes
@ -89,7 +90,7 @@ async def root(request):
def check_conf():
if not environ.get('HALFORM_SECRET', False):
environ['HALFORM_SECRET'] = 'secret'
environ['HALFORM_SECRET'] = open('/etc/half_orm/secret').read()
print('Missing HALFORM_SECRET variable from configuration, seting to default')
if not environ.get('HALFORM_DSN', False):
@ -100,5 +101,11 @@ app = Starlette(
Middleware(AuthenticationMiddleware, backend=JWTAuthenticationBackend(secret_key=environ.get('HALFORM_SECRET'))),
Middleware(AclCallerMiddleware),
],
on_startup=[startup]
exception_handlers={
401: UnauthorizedResponse,
404: NotFoundResponse,
500: InternalServerErrorResponse,
501: NotImplementedResponse
},
on_startup=[startup],
)

View File

@ -7,17 +7,11 @@ from io import TextIOBase, StringIO
# asgi framework
from starlette.responses import Response
class NotFoundResponse(Response):
""" The 404 Not Found default Response
"""
def __init__(self):
super().__init__(status_code=404)
class ForbiddenResponse(Response):
""" The 401 Not Found default Response
"""
def __init__(self):
super().__init__(status_code = 401)
__all__ = ['CSVResponse',
'InternalServerErrorResponse',
'NotFoundResponse',
'NotImplementedResponse',
'UnauthorizedResponse']
class CSVResponse(Response):
def __init__(self, obj):
@ -33,3 +27,32 @@ class CSVResponse(Response):
'Content-Type': 'text/csv; charset=UTF-8',
'Content-Disposition': f'attachment; filename="{filename}"'},
status_code = 200)
class InternalServerErrorResponse(Response):
""" The 500 Internal Server Error default Response
"""
def __init__(self):
super().__init__(status_code=500)
class NotFoundResponse(Response):
""" The 404 Not Found default Response
"""
def __init__(self):
super().__init__(status_code=404)
class NotImplementedResponse(Response):
""" The 501 Not Implemented default Response
"""
def __init__(self):
super().__init__(status_code=501)
class UnauthorizedResponse(Response):
""" The 401 Not Found default Response
"""
def __init__(self):
super().__init__(status_code = 401)