|
1 |
| -from datetime import timedelta |
2 |
| -import random |
3 |
| - |
4 |
| -from argon2 import PasswordHasher |
5 |
| -from argon2.exceptions import VerificationError |
6 |
| -from email_validator import validate_email, EmailNotValidError |
7 |
| - |
8 |
| -from common.database import get_connection |
9 |
| -from common.exceptions import AuthError, InvalidError, RequestError |
10 |
| -from common.redis import cache |
11 |
| - |
12 |
| -hasher = PasswordHasher( |
13 |
| - time_cost=2, |
14 |
| - memory_cost=2**15, |
15 |
| - parallelism=1 |
16 |
| -) |
17 |
| - |
18 |
| -class User: |
19 |
| - # TODO: change all these functions once database functions are merged |
20 |
| - |
21 |
| - # Private helper methods |
22 |
| - @staticmethod |
23 |
| - def _email_exists(cursor, email): |
24 |
| - """Checks if an email exists in the database.""" |
25 |
| - cursor.execute("SELECT * FROM Users WHERE email = %s", |
26 |
| - (email,)) |
27 |
| - |
28 |
| - results = cursor.fetchall() |
29 |
| - return results != [] |
30 |
| - |
31 |
| - @staticmethod |
32 |
| - def _username_exists(cursor, username): |
33 |
| - """Checks if a username is already used.""" |
34 |
| - cursor.execute("SELECT * FROM Users WHERE username = %s", (username,)) |
35 |
| - |
36 |
| - results = cursor.fetchall() |
37 |
| - return results != [] |
38 |
| - |
39 |
| - @staticmethod |
40 |
| - def _add_user(conn, cursor, email, username, password): |
41 |
| - """Given the details of a user, adds them to the database.""" |
42 |
| - cursor.execute("INSERT INTO Users (email, username, password, numStars, score) VALUES (%s, %s, %s, 0, 0)", |
43 |
| - (email, username, password)) |
44 |
| - conn.commit() |
45 |
| - |
46 |
| - cursor.execute("SELECT uid FROM Users WHERE email = %s", (email,)) |
47 |
| - id = cursor.fetchone()[0] |
48 |
| - |
49 |
| - return id |
50 |
| - |
51 |
| - # Constructor methods |
52 |
| - def __init__(self, email, password, id): |
53 |
| - self.email = email |
54 |
| - self.password = password |
55 |
| - self.id = id |
56 |
| - |
57 |
| - # API-facing methods |
58 |
| - @staticmethod |
59 |
| - def register(email, username, password): |
60 |
| - """Given an email, username and password, creates a verification code |
61 |
| - for that user in Redis such that we can verify that user's email.""" |
62 |
| - # Error handling |
63 |
| - conn = get_connection() |
64 |
| - cursor = conn.cursor() |
65 |
| - |
66 |
| - try: |
67 |
| - normalised = validate_email(email).email |
68 |
| - except EmailNotValidError as e: |
69 |
| - raise RequestError(description="Invalid email") from e |
70 |
| - |
71 |
| - if User._email_exists(cursor, normalised): |
72 |
| - raise RequestError(description="Email already registered") |
73 |
| - |
74 |
| - if User._username_exists(cursor, username): |
75 |
| - raise RequestError(description="Username already used") |
76 |
| - |
77 |
| - hashed = hasher.hash(password) |
78 |
| - # TODO: remove addition of user to database |
79 |
| - new_id = User._add_user(conn, cursor, normalised, username, hashed) |
80 |
| - |
81 |
| - cursor.close() |
82 |
| - conn.close() |
83 |
| - |
84 |
| - # Add verification code to Redis cache, with expiry date of 1 hour |
85 |
| - code = random.randint(0, 999_999) |
86 |
| - data = { |
87 |
| - "code": f"{code:06}", |
88 |
| - "username": username, |
89 |
| - "password": hashed |
90 |
| - } |
91 |
| - |
92 |
| - pipeline = cache.pipeline() |
93 |
| - |
94 |
| - # We use a pipeline here to ensure these instructions are atomic |
95 |
| - pipeline.hset(f"register:{new_id}", mapping=data) |
96 |
| - pipeline.expire(f"register:{new_id}", timedelta(hours=1)) |
97 |
| - |
98 |
| - pipeline.execute() |
99 |
| - |
100 |
| - return code |
101 |
| - |
102 |
| - @staticmethod |
103 |
| - def login(email, password): |
104 |
| - """Logs user in with their credentials (currently email and password).""" |
105 |
| - conn = get_connection() |
106 |
| - cursor = conn.cursor() |
107 |
| - |
108 |
| - try: |
109 |
| - normalised = validate_email(email).email |
110 |
| - except EmailNotValidError as e: |
111 |
| - raise AuthError(description="Invalid email or password") from e |
112 |
| - |
113 |
| - cursor.execute("SELECT * FROM Users WHERE email = %s", (normalised,)) |
114 |
| - result = cursor.fetchone() |
115 |
| - |
116 |
| - try: |
117 |
| - id, _, hashed = result |
118 |
| - hasher.verify(hashed, password) |
119 |
| - except (TypeError, VerificationError) as e: |
120 |
| - raise AuthError(description="Invalid email or password") from e |
121 |
| - |
122 |
| - cursor.close() |
123 |
| - conn.close() |
124 |
| - |
125 |
| - return User(normalised, hashed, id) |
126 |
| - |
127 |
| - @staticmethod |
128 |
| - def get(id): |
129 |
| - """Given a user's ID, fetches all of their information from the database.""" |
130 |
| - conn = get_connection() |
131 |
| - cursor = conn.cursor() |
132 |
| - |
133 |
| - cursor.execute("SELECT * FROM Users WHERE uid = %s", (id,)) |
134 |
| - fetched = cursor.fetchall() |
135 |
| - |
136 |
| - if fetched == []: |
137 |
| - raise InvalidError(description=f"Requested user ID {id} doesn't exist") |
138 |
| - |
139 |
| - email, _, password, _, _ = fetched[0] |
140 |
| - |
141 |
| - cursor.close() |
142 |
| - conn.close() |
143 |
| - |
144 |
| - return User(email, password, id) |
| 1 | +from datetime import timedelta |
| 2 | +import random |
| 3 | + |
| 4 | +from argon2 import PasswordHasher |
| 5 | +from argon2.exceptions import VerificationError |
| 6 | +from email_validator import validate_email, EmailNotValidError |
| 7 | + |
| 8 | +from common.database import get_connection |
| 9 | +from common.exceptions import AuthError, InvalidError, RequestError |
| 10 | +from common.redis import cache |
| 11 | + |
| 12 | +hasher = PasswordHasher( |
| 13 | + time_cost=2, |
| 14 | + memory_cost=2**15, |
| 15 | + parallelism=1 |
| 16 | +) |
| 17 | + |
| 18 | +class User: |
| 19 | + # TODO: change all these functions once database functions are merged |
| 20 | + |
| 21 | + # Private helper methods |
| 22 | + @staticmethod |
| 23 | + def _email_exists(cursor, email): |
| 24 | + """Checks if an email exists in the database.""" |
| 25 | + cursor.execute("SELECT * FROM Users WHERE email = %s", |
| 26 | + (email,)) |
| 27 | + |
| 28 | + results = cursor.fetchall() |
| 29 | + return results != [] |
| 30 | + |
| 31 | + @staticmethod |
| 32 | + def _username_exists(cursor, username): |
| 33 | + """Checks if a username is already used.""" |
| 34 | + cursor.execute("SELECT * FROM Users WHERE username = %s", (username,)) |
| 35 | + |
| 36 | + results = cursor.fetchall() |
| 37 | + return results != [] |
| 38 | + |
| 39 | + @staticmethod |
| 40 | + def _add_user(conn, cursor, email, username, password): |
| 41 | + """Given the details of a user, adds them to the database.""" |
| 42 | + cursor.execute("INSERT INTO Users (email, username, password, numStars, score) VALUES (%s, %s, %s, 0, 0)", |
| 43 | + (email, username, password)) |
| 44 | + conn.commit() |
| 45 | + |
| 46 | + cursor.execute("SELECT uid FROM Users WHERE email = %s", (email,)) |
| 47 | + id = cursor.fetchone()[0] |
| 48 | + |
| 49 | + return id |
| 50 | + |
| 51 | + # Constructor methods |
| 52 | + def __init__(self, email, password, id): |
| 53 | + self.email = email |
| 54 | + self.password = password |
| 55 | + self.id = id |
| 56 | + |
| 57 | + # API-facing methods |
| 58 | + @staticmethod |
| 59 | + def register(email, username, password): |
| 60 | + """Given an email, username and password, creates a verification code |
| 61 | + for that user in Redis such that we can verify that user's email.""" |
| 62 | + # Error handling |
| 63 | + conn = get_connection() |
| 64 | + cursor = conn.cursor() |
| 65 | + |
| 66 | + try: |
| 67 | + normalised = validate_email(email).email |
| 68 | + except EmailNotValidError as e: |
| 69 | + raise RequestError(description="Invalid email") from e |
| 70 | + |
| 71 | + if User._email_exists(cursor, normalised): |
| 72 | + raise RequestError(description="Email already registered") |
| 73 | + |
| 74 | + if User._username_exists(cursor, username): |
| 75 | + raise RequestError(description="Username already used") |
| 76 | + |
| 77 | + hashed = hasher.hash(password) |
| 78 | + # TODO: remove addition of user to database |
| 79 | + new_id = User._add_user(conn, cursor, normalised, username, hashed) |
| 80 | + |
| 81 | + cursor.close() |
| 82 | + conn.close() |
| 83 | + |
| 84 | + # Add verification code to Redis cache, with expiry date of 1 hour |
| 85 | + code = random.randint(0, 999_999) |
| 86 | + data = { |
| 87 | + "code": f"{code:06}", |
| 88 | + "username": username, |
| 89 | + "password": hashed |
| 90 | + } |
| 91 | + |
| 92 | + pipeline = cache.pipeline() |
| 93 | + |
| 94 | + # We use a pipeline here to ensure these instructions are atomic |
| 95 | + pipeline.hset(f"register:{new_id}", mapping=data) |
| 96 | + pipeline.expire(f"register:{new_id}", timedelta(hours=1)) |
| 97 | + |
| 98 | + pipeline.execute() |
| 99 | + |
| 100 | + return code |
| 101 | + |
| 102 | + @staticmethod |
| 103 | + def login(email, password): |
| 104 | + """Logs user in with their credentials (currently email and password).""" |
| 105 | + conn = get_connection() |
| 106 | + cursor = conn.cursor() |
| 107 | + |
| 108 | + try: |
| 109 | + normalised = validate_email(email).email |
| 110 | + except EmailNotValidError as e: |
| 111 | + raise AuthError(description="Invalid email or password") from e |
| 112 | + |
| 113 | + cursor.execute("SELECT * FROM Users WHERE email = %s", (normalised,)) |
| 114 | + result = cursor.fetchone() |
| 115 | + |
| 116 | + try: |
| 117 | + id, _, hashed = result |
| 118 | + hasher.verify(hashed, password) |
| 119 | + except (TypeError, VerificationError) as e: |
| 120 | + raise AuthError(description="Invalid email or password") from e |
| 121 | + |
| 122 | + cursor.close() |
| 123 | + conn.close() |
| 124 | + |
| 125 | + return User(normalised, hashed, id) |
| 126 | + |
| 127 | + @staticmethod |
| 128 | + def get(id): |
| 129 | + """Given a user's ID, fetches all of their information from the database.""" |
| 130 | + conn = get_connection() |
| 131 | + cursor = conn.cursor() |
| 132 | + |
| 133 | + cursor.execute("SELECT * FROM Users WHERE uid = %s", (id,)) |
| 134 | + fetched = cursor.fetchall() |
| 135 | + |
| 136 | + if fetched == []: |
| 137 | + raise InvalidError(description=f"Requested user ID {id} doesn't exist") |
| 138 | + |
| 139 | + email, _, password, _, _ = fetched[0] |
| 140 | + |
| 141 | + cursor.close() |
| 142 | + conn.close() |
| 143 | + |
| 144 | + return User(email, password, id) |
0 commit comments