all repos — myprecious @ d7583eb4604a185c188647b4cc192555e1579119

A lightweight web service to backup precious game saves.

myprecious/auth.py (view raw)

 1import myprecious.constants as c
 2from myprecious.db import add_user_to_queue, get_user_from_username, get_user_from_id, verify_user
 3from flask_login import UserMixin
 4
 5class User(UserMixin):
 6    def __init__(self, user_id, username, password, salt, email):
 7        self.id = user_id
 8        self.username = username
 9        self.password = password
10        self.salt = salt
11        self.email = email
12
13def construct_user(row):
14    try:
15        return User(int(row[0]), row[1], row[2], row[3], row[4])
16    except TypeError:
17        return None
18
19def handle_register(form):
20    username = form["username"].lower()
21    email = form["email"].lower()
22    password = form["password"]
23
24    if len(password) < c.MIN_PW_LENGTH or len(username) < c.MIN_USERNAME_LENGTH:
25        return "Your username or password is too short."
26    
27    if len(password) > c.MAX_LENGTH or len(username) > c.MAX_LENGTH:
28        return "Your username or password is too long."
29    
30    res = add_user_to_queue(username, password, email)
31    match res:
32        case "registered":
33            return "This user is already registered."
34        case "queued":
35            return "This user is waiting for approval."
36        case "done":
37            return "Done! Your request was submitted and will hopefully be approved shortly."
38        case _:
39            return "An error as occurred."
40        
41    return None
42
43def handle_login(form):
44    username = form["username"].lower()
45    password = form["password"]
46    
47    r = get_user_from_username(username)
48    if r is None:
49        return "This account either does not exist or it's still awaiting approval.", { "username": username }
50    user = construct_user(r)
51
52    last_user = { "username": username }
53    if user is None:
54        return "Parsing error.", last_user
55    if verify_user(username, user.password, password, user.salt):
56        return None, user
57    return "Wrong password.", last_user
58
59def get_logged_user(user_id):
60    lu = get_user_from_id(user_id)
61    if lu is None:
62        return None
63    return construct_user(lu)