docusort-api / backend /auth.py
Mohib
Clean backend API push
8ddf321
Raw
History Blame Contribute Delete
1.45 kB
# File: backend/auth.py
from passlib.context import CryptContext
from datetime import datetime, timedelta
from typing import Optional
from jose import JWTError, jwt
# SECRET CONFIG
SECRET_KEY = "super_secret_key_for_docusort_project_22"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
class Hash:
@staticmethod
def bcrypt(password: str):
return pwd_context.hash(password)
@staticmethod
def verify(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
# Add Expiry and Token Version to payload
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
def verify_token(token: str, credentials_exception):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
email: str = payload.get("sub")
# We need to return the whole payload to check version later
if email is None:
raise credentials_exception
return payload
except JWTError:
raise credentials_exception