forked from Jxt-Eli/neobank_backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.py
More file actions
52 lines (41 loc) · 1.63 KB
/
auth.py
File metadata and controls
52 lines (41 loc) · 1.63 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
from passlib.context import CryptContext
import hashlib
from jose import jwt, JWTError
from datetime import datetime, timedelta
from dotenv import load_dotenv
import os
load_dotenv()
# ------password context-------
pwd_context = CryptContext(
schemes=["bcrypt"],
deprecated="auto",
)
# ---sha256 + bcrypt password hashing---
def hash_password(password: str) -> str:
pre_hashed = hashlib.sha256(password.encode()).hexdigest()
return pwd_context.hash(pre_hashed)
# ---verify password by hashing and comparing to stored hash---
def verify_password(plain_password: str, hashed_password: str)-> bool:
pre_hashed = hashlib.sha256(plain_password.encode()).hexdigest()
return pwd_context.verify(pre_hashed, hashed_password)
# ---JWT configuration---
SECRET_KEY = os.getenv("SECRET_KEY") # HACK: TEMPORARY FIX, WILL USE ENVIRONMENT VARIABLES LATER
ALGORITHM = os.getenv("ALGORITHM")
ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES"))
def create_access_token(data: dict):
"""creates a JWT token with expiration time"""
to_encode = data.copy()
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
def verify_access_token(token: str):
"""decodes and verifies a jwt token and returns the user_id"""
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user_id: str = payload.get("sub")
if user_id is None:
return None
return int(user_id)
except JWTError:
return None