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
3from flask_login import UserMixin
4
5class User(UserMixin):
6 def __init__(self, user_id, username, password, email):
7 self.id = user_id
8 self.username = username
9 self.password = password
10 self.email = email
11
12def construct_user(id, username, password, email):
13 try:
14 return User(int(id), username, password, email)
15 except TypeError:
16 return None
17
18def handle_register(form):
19 username = form["username"].lower()
20 email = form["email"].lower()
21 password = form["password"]
22
23 if len(password) < c.MIN_PW_LENGTH or len(username) < c.MIN_USERNAME_LENGTH:
24 return "Your username or password is too short."
25
26 if len(password) > c.MAX_LENGTH or len(username) > c.MAX_LENGTH:
27 return "Your username or password is too long."
28
29 res = add_user_to_queue(username, password, email)
30 if res == None:
31 return "This username is already registered."
32 return None
33
34def handle_login(form):
35 username = form["username"].lower()
36 password = form["password"]
37
38 r = get_user_from_username(username)
39 if r is None:
40 return "That account does not exist.", { "username": username }
41 user = construct_user(r[0], r[1], r[2], r[3])
42
43 last_user = { "username": username }
44 if user is None:
45 return "Parsing error.", last_user
46
47 if user.password == password:
48 return None, user
49 return "Wrong password.", last_user
50
51def get_logged_user(user_id):
52 lu = get_user_from_id(user_id)
53 if lu is None:
54 return None
55 return construct_user(lu[0], lu[1], lu[2], lu[3])