-
Notifications
You must be signed in to change notification settings - Fork 2
/
auth_utils.py
53 lines (43 loc) · 1.41 KB
/
auth_utils.py
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
import hashlib
from db_utils import engine, Users
from sqlalchemy import (
select,
update,
)
from fastapi.responses import JSONResponse
SALT = "WITHPEPPER"
def login_user(username, password):
hashed_password = hashlib.sha256((username + SALT + password).encode()).hexdigest()
with engine.begin() as conn:
user = conn.execute(
select(Users).where(Users.hashed_password == hashed_password)
).fetchone()
if user:
return {"status": "success", "user_type": user[0], "token": hashed_password}
else:
return JSONResponse(
status_code=401,
content={
"error": "unauthorized",
"message": "Invalid username or password",
},
)
def reset_password(username, new_password):
hashed_password = hashlib.sha256(
(username + SALT + new_password).encode()
).hexdigest()
with engine.begin() as conn:
conn.execute(
update(Users)
.where(Users.username == username)
.values(hashed_password=hashed_password)
)
def get_hashed_password(username, password):
return hashlib.sha256((username + SALT + password).encode()).hexdigest()
def validate_user_email(email):
with engine.begin() as conn:
user = conn.execute(select(Users).where(Users.username == email)).fetchone()
if user:
return True
else:
return False