generated from CodeYourFuture/Module-Template
-
-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathusers.py
More file actions
108 lines (86 loc) · 3.03 KB
/
users.py
File metadata and controls
108 lines (86 loc) · 3.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
from dataclasses import dataclass
# from hashlib import scrypt
import hashlib
import random
import string
from typing import List, Optional
from data.connection import db_cursor
from psycopg2.errors import UniqueViolation
@dataclass
class User:
id: int
username: str
password_salt: bytes
password_scrypt: bytes
def check_password(self, password_plaintext: str) -> bool:
return self.password_scrypt == scrypt(
password_plaintext.encode("utf-8"), self.password_salt
)
class UserRegistrationError(Exception):
reason: str
def __init__(self, reason: str):
self.reason = reason
def get_user(username: str) -> Optional[User]:
with db_cursor() as cur:
cur.execute(
"SELECT id, password_salt, password_scrypt FROM users WHERE username = %s",
(username,),
)
row = cur.fetchone()
if row is None:
return None
user_id, password_salt, password_scrypt = row
return User(
id=user_id,
username=username,
password_salt=bytes(password_salt),
password_scrypt=bytes(password_scrypt),
)
def get_suggested_follows(following_user: User, limit: int) -> List[str]:
with db_cursor() as cur:
cur.execute(
"""
SELECT
users.username
FROM
users
WHERE
users.id <> %(following_user_id)s AND
users.id NOT IN (
SELECT followee FROM follows WHERE follower = %(following_user_id)s
)
ORDER BY RANDOM()
LIMIT %(limit)s
""",
dict(
following_user_id=following_user.id,
limit=limit,
),
)
rows = cur.fetchall()
return [row[0] for row in rows]
def register_user(username: str, password_plaintext: str) -> User:
salt = generate_salt()
password_scrypt = scrypt(password_plaintext.encode("utf-8"), salt)
with db_cursor() as cur:
try:
cur.execute(
"INSERT INTO users (username, password_salt, password_scrypt) VALUES (%(username)s, %(password_salt)s, %(password_scrypt)s)",
dict(
username=username,
password_salt=salt,
password_scrypt=password_scrypt,
),
)
except UniqueViolation as err:
raise UserRegistrationError("user already exists")
def scrypt(password_plaintext: bytes, password_salt: bytes) -> bytes:
return hashlib.scrypt(password_plaintext, salt=password_salt, n=8, r=8, p=1)
SALT_CHARACTERS = string.ascii_uppercase + string.ascii_lowercase + string.digits
def generate_salt() -> bytes:
return (
"".join(random.SystemRandom().choice(SALT_CHARACTERS) for _ in range(10))
).encode("utf-8")
def lookup_user(header_info, payload_info):
"""lookup_user is a hook for the jwt middleware to look-up authenticated users."""
return get_user(payload_info["sub"])