2021-06-12 13:24:26 +02:00
|
|
|
import uuid
|
|
|
|
import yaml
|
|
|
|
|
|
|
|
from app import app, db
|
|
|
|
from ki.models import User, Token
|
|
|
|
|
|
|
|
|
2021-06-21 16:01:29 +02:00
|
|
|
class UserWrongCredentialsException(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class UserAllreadyLoggedInException(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2021-06-12 13:24:26 +02:00
|
|
|
def auth(username, password):
|
|
|
|
auth_file_path = app.config["KI_DATA_DIR"] + "/auth.yml"
|
|
|
|
|
|
|
|
with open(auth_file_path, "r") as auth_file_stream:
|
|
|
|
|
2021-06-21 16:01:29 +02:00
|
|
|
try:
|
|
|
|
users = yaml.safe_load(auth_file_stream)
|
|
|
|
|
|
|
|
except yaml.YAMLError:
|
|
|
|
print('Could not parse auth.yml.')
|
|
|
|
|
|
|
|
try:
|
|
|
|
auth_user = users[username]
|
2021-06-12 13:24:26 +02:00
|
|
|
|
2021-06-21 16:01:29 +02:00
|
|
|
if auth_user["password"] != password:
|
|
|
|
raise UserWrongCredentialsException
|
2021-06-12 13:24:26 +02:00
|
|
|
|
2021-06-21 16:01:29 +02:00
|
|
|
except (UserWrongCredentialsException, KeyError):
|
|
|
|
print('Wrong username/password combination')
|
2021-06-12 13:24:26 +02:00
|
|
|
return None
|
|
|
|
|
2021-06-21 16:01:29 +02:00
|
|
|
else:
|
|
|
|
user = User.query.filter(User.auth_id.__eq__(username)).first()
|
2021-06-12 13:24:26 +02:00
|
|
|
|
2021-06-21 16:01:29 +02:00
|
|
|
token = Token(token=str(uuid.uuid4()), user=user)
|
2021-06-12 13:24:26 +02:00
|
|
|
|
2021-06-21 16:01:29 +02:00
|
|
|
db.session.add(token)
|
|
|
|
db.session.commit()
|
2021-06-12 13:24:26 +02:00
|
|
|
|
2021-06-21 16:01:29 +02:00
|
|
|
return token
|