diff --git a/halfapi/app.py b/halfapi/app.py index a251e20..00d5397 100644 --- a/halfapi/app.py +++ b/halfapi/app.py @@ -48,7 +48,7 @@ def mount_domains(app: ASGIApp, domains: list): print(f'Will import {domain["name"]}.app:app') # @TODO 4-configuration # Store domain-specific information in a configuration file - environ["HALFORM_DSN"] = "dbname=si user=si" + domain_mod = importlib.import_module( f'{domain["name"]}.app') domain_app = domain_mod.app @@ -89,29 +89,41 @@ def startup(): sys.stderr.write('Error in the *domains* retrieval\n') raise e -async def root(request): - return JSONResponse({'payload': request.payload}) -def check_conf(): - if not environ.get('HALFORM_SECRET', False): - environ['HALFORM_SECRET'] = open('/etc/half_orm/secret').read() - print('Missing HALFORM_SECRET variable from configuration, seting to default') +# Configuration +CONFIG={} +CONFIG['DEBUG'] = environ.get('DEBUG', False) +CONFIG['DEBUG_ACL'] = environ.get('DEBUG_ACL', False) +CONFIG['HALFORM_SECRET'] = environ.get('HALFORM_SECRET', False) + +if not CONFIG['HALFORM_SECRET']: + try: + CONFIG['HALFORM_SECRET'] = open('/etc/half_orm/secret').read() + print('Missing HALFORM_SECRET variable from configuration, \ + read it from /etc/half_orm/secret') + except FileNotFoundError: + print('No HALFORM_SECRET variable set, and /etc/half_orm/secret \ + inaccessible.') + sys.exit(1) + except PermissionError: + print("You don't have the right to read /etc/half_orm/secret") + sys.exit(1) -CONFIG={ - 'DEBUG' : 'DEBUG' in environ.keys() -} debug_routes = [ Route('/', lambda request, *args, **kwargs: PlainTextResponse('It Works!')), - Route('/user', lambda request, *args, **kwargs: JSONResponse({'user':str(request.user)})), + Route('/user', lambda request, *args, **kwargs: + JSONResponse({'user':request.user.json})), Route('/payload', lambda request, *args, **kwargs: JSONResponse({'payload':str(request.payload)})) -] if CONFIG['DEBUG'] is True else [] +] if CONFIG['DEBUG'] else [] + app = Starlette( debug=CONFIG['DEBUG'], routes=debug_routes, middleware=[ - Middleware(AuthenticationMiddleware, backend=JWTAuthenticationBackend(secret_key=environ.get('HALFORM_SECRET'))), + Middleware(AuthenticationMiddleware, + backend=JWTAuthenticationBackend(secret_key=CONFIG['HALFORM_SECRET'])), Middleware(AclCallerMiddleware), ], exception_handlers={ diff --git a/halfapi/cli.py b/halfapi/cli.py index 8e11db6..c8b9ba4 100755 --- a/halfapi/cli.py +++ b/halfapi/cli.py @@ -17,8 +17,6 @@ from .models.api.route import Route from .models.api.acl_function import AclFunction from .models.api.acl import Acl -# module libraries -from .app import check_conf HALFORM_DSN='' HALFORM_SECRET='' @@ -59,8 +57,6 @@ def run(envfile, host, port): click.echo('Launching application') - check_conf() - sys.path.insert(0, os.getcwd()) click.echo(f'current python_path : {sys.path}') diff --git a/halfapi/lib/jwt_middleware.py b/halfapi/lib/jwt_middleware.py index f980b33..d5c9551 100644 --- a/halfapi/lib/jwt_middleware.py +++ b/halfapi/lib/jwt_middleware.py @@ -44,11 +44,16 @@ class JWTUser(BaseUser): self.payload = payload def __str__(self): - return str({ + return str(self.json) + + @property + def json(self): + return { 'id' : str(self.__id), 'token': self.token, 'payload': self.payload - }) + } + @property def is_authenticated(self) -> bool: return True @@ -60,6 +65,8 @@ class JWTUser(BaseUser): class JWTAuthenticationBackend(AuthenticationBackend): def __init__(self, secret_key: str, algorithm: str = 'HS256', prefix: str = 'JWT', name: str = 'name'): + if secret_key is None: + raise Exception('Missing secret_key argument for JWTAuthenticationBackend') self.secret_key = secret_key self.algorithm = algorithm self.prefix = prefix @@ -76,6 +83,7 @@ class JWTAuthenticationBackend(AuthenticationBackend): raise AuthenticationError(str(e)) except Exception as e: print(e) + raise e return AuthCredentials(["authenticated"]), JWTUser( diff --git a/tests/test_jwt_middleware.py b/tests/test_jwt_middleware.py index 4e49bbf..d80ff9e 100644 --- a/tests/test_jwt_middleware.py +++ b/tests/test_jwt_middleware.py @@ -50,7 +50,6 @@ def test_token(token): raise Exception('Malformed response from /user request') assert 'user' in res.keys() - print(res['user']) assert 'id' in res['user'].keys() assert 'token' in res['user'].keys() assert 'payload' in res['user'].keys()