28 lines
1.2 KiB
Python
28 lines
1.2 KiB
Python
from datetime import datetime, timedelta, timezone
|
|
from typing import Any, Union, Optional
|
|
from jose import jwt
|
|
import bcrypt
|
|
from app.config.config import settings
|
|
|
|
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
|
"""Compare a plain text password with its bcrypt hash to verify identity."""
|
|
return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8'))
|
|
|
|
def get_password_hash(password: str) -> str:
|
|
"""Generate a bcrypt hash from a plain text password."""
|
|
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
|
|
|
|
def create_access_token(subject: Union[str, Any], expires_delta: Optional[timedelta] = None) -> str:
|
|
"""
|
|
Generate a JSON Web Token (JWT) containing the subject (e.g. username/id).
|
|
Accepts an optional expiration delta, defaulting to the config setting.
|
|
"""
|
|
if expires_delta:
|
|
expire = datetime.now(timezone.utc) + expires_delta
|
|
else:
|
|
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
|
|
to_encode = {"exp": expire, "sub": str(subject)}
|
|
encoded_jwt = jwt.encode(to_encode, settings.JWT_SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
|
|
return encoded_jwt
|