44 lines
1.3 KiB
Python
44 lines
1.3 KiB
Python
from datetime import datetime, timedelta, timezone
|
|
from typing import Optional
|
|
|
|
from jose import JWTError, jwt
|
|
from passlib.context import CryptContext
|
|
|
|
from app.config import settings
|
|
|
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
return pwd_context.hash(password)
|
|
|
|
|
|
def verify_password(plain: str, hashed: str) -> bool:
|
|
return pwd_context.verify(plain, hashed)
|
|
|
|
|
|
def create_token(user_id: int, admin_id: Optional[int] = None) -> str:
|
|
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
|
|
payload: dict = {"sub": str(user_id), "exp": expire}
|
|
if admin_id is not None:
|
|
payload["admin_id"] = admin_id
|
|
return jwt.encode(payload, settings.secret_key, algorithm=settings.algorithm)
|
|
|
|
|
|
def decode_token(token: str) -> Optional[int]:
|
|
try:
|
|
payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
|
|
user_id = payload.get("sub")
|
|
if user_id is None:
|
|
return None
|
|
return int(user_id)
|
|
except JWTError:
|
|
return None
|
|
|
|
|
|
def decode_token_full(token: str) -> Optional[dict]:
|
|
try:
|
|
return jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
|
|
except JWTError:
|
|
return None
|