-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUtils.py
49 lines (36 loc) · 1.2 KB
/
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
import jwt
import bcrypt
from datetime import datetime, timedelta, timezone
PRIVATE_KEY_PATH = ".keys/private.pem"
PUBLIC_KEY_PATH = ".keys/public.pem"
EXPIRE_MINUTES = 30
with open(PRIVATE_KEY_PATH, "r") as file:
PRIVATE_KEY = file.read()
with open(PUBLIC_KEY_PATH, "r") as file:
PUBLIC_KEY = file.read()
def create_jwt(
data: dict, expires_delta: timedelta = timedelta(minutes=EXPIRE_MINUTES)
):
payload = data.copy()
payload["exp"] = datetime.now(timezone.utc) + expires_delta
payload["iat"] = datetime.now(timezone.utc)
payload["iss"] = "pi.daazed.dev"
return jwt.encode(payload, PRIVATE_KEY, algorithm="RS256")
def verify_jwt(token: str):
try:
payload = jwt.decode(token, PUBLIC_KEY, algorithms=["RS256"])
return payload
except jwt.ExpiredSignatureError:
raise ValueError("TOKEN EXPIRED")
except jwt.InvalidTokenError:
raise ValueError("INVALID TOKEN")
def verify_password(password, hashed_password):
return bcrypt.checkpw(
bytes(password, encoding="utf-8"),
hashed_password,
)
def hash_password(password):
return bcrypt.hashpw(
bytes(password, encoding="utf-8"),
bcrypt.gensalt(),
)