From 35cafe17801447b9b2855f2573e12c817bfa309d Mon Sep 17 00:00:00 2001 From: Frank Lanitz Date: Mon, 21 Jun 2021 16:01:29 +0200 Subject: [PATCH] auth.py: Make usage of exceptions instead of if-else-blocks --- ki/auth.py | 43 ++++++++++++++++++++++++++++--------------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/ki/auth.py b/ki/auth.py index b5e346f..e28fba1 100644 --- a/ki/auth.py +++ b/ki/auth.py @@ -5,28 +5,41 @@ from app import app, db from ki.models import User, Token +class UserWrongCredentialsException(Exception): + pass + + +class UserAllreadyLoggedInException(Exception): + pass + + def auth(username, password): auth_file_path = app.config["KI_DATA_DIR"] + "/auth.yml" with open(auth_file_path, "r") as auth_file_stream: - users = yaml.safe_load(auth_file_stream) - if username not in users: + try: + users = yaml.safe_load(auth_file_stream) + + except yaml.YAMLError: + print('Could not parse auth.yml.') + + try: + auth_user = users[username] + + if auth_user["password"] != password: + raise UserWrongCredentialsException + + except (UserWrongCredentialsException, KeyError): + print('Wrong username/password combination') return None - auth_user = users[username] + else: + user = User.query.filter(User.auth_id.__eq__(username)).first() - if auth_user["password"] != password: - return None + token = Token(token=str(uuid.uuid4()), user=user) - user = User.query.filter(User.auth_id.__eq__(username)).first() + db.session.add(token) + db.session.commit() - if user is None: - user = User(auth_id=username) - db.session.add(user) - - token = Token(token=str(uuid.uuid4()), user=user) - db.session.add(token) - db.session.commit() - - return token + return token