From 08da7a23f4bce1a376dfb090d894d0321d77a976 Mon Sep 17 00:00:00 2001 From: Stefan Haun Date: Sun, 23 Aug 2020 22:07:20 +0200 Subject: [PATCH] Add authentication --- README.md | 9 +++++++++ app.py | 6 ++++-- auth.py | 31 +++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 auth.py diff --git a/README.md b/README.md index bce88ed..a6d6afb 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,12 @@ # Entities Service Query and manipulate the Netz39 entities database. + +## Running the Service + +### Configuration + +The service is configured via the following environment variables: +* `PORT`: Service port. defaults to 8080 +* `AUTH`: Authentication tokens, defaults to None. Example Configuration : `AUTH={"token_1": "user_1", "token_2": "user_2"}` + diff --git a/app.py b/app.py index 2510298..7bff5b8 100644 --- a/app.py +++ b/app.py @@ -11,6 +11,7 @@ import isodate import json import util +from auth import AuthProvider startup_timestamp = datetime.now() @@ -68,7 +69,7 @@ class Oas3Handler(tornado.web.RequestHandler, metaclass=ABCMeta): self.finish() -def make_app(): +def make_app(_auth_provider=None): version_path = r"/v[0-9]" return tornado.web.Application([ (version_path + r"/health", HealthHandler), @@ -80,8 +81,9 @@ def main(): port = util.load_env('PORT', 8080) # Setup + auth_provider = AuthProvider.from_environment() - util.run_tornado_server(make_app(), + util.run_tornado_server(make_app(auth_provider), server_port=port) # Teardown diff --git a/auth.py b/auth.py new file mode 100644 index 0000000..66be0f5 --- /dev/null +++ b/auth.py @@ -0,0 +1,31 @@ +import json +from util import load_env + + +class AuthProvider(object): + @staticmethod + def from_environment(): + auth = load_env("AUTH", None) + + return AuthProvider(auth) + + def __init__(self, auth_token_config): + if auth_token_config == "": + self.auth_token_pool = [] + print("Service started without Authentication") + return + + try: + self.auth_token_pool = json.loads(auth_token_config) + except ValueError as e: + raise ValueError("Authentication configuration could not be parsed") from e + + def validate_token(self, token): + """Validate a token for fabrication functions""" + if token in self.auth_token_pool or not self.auth_token_pool: + return True + + return False + + def user_for_token(self, token): + return self.auth_token_pool.get(token)