ki-backend/ki/auth.py

46 lines
1.0 KiB
Python

import uuid
import yaml
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:
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
else:
user = User.query.filter(User.auth_id.__eq__(username)).first()
token = Token(token=str(uuid.uuid4()), user=user)
db.session.add(token)
db.session.commit()
return token