Files / app /core /security.py
lea97338's picture
Upload 100 files (#1)
680fa2b
Raw
History Blame Contribute Delete
1.32 kB
import bcrypt
from datetime import datetime, timedelta
from typing import Any, Union
from jose import jwt
from backend.app.core.config import settings
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""Verify if a plain text password matches its hashed bcrypt value."""
if not hashed_password:
return False
try:
return bcrypt.checkpw(
plain_password.encode("utf-8"),
hashed_password.encode("utf-8")
)
except Exception:
return False
def get_password_hash(password: str) -> str:
"""Generate a secure bcrypt hash of a plain text password."""
# Generate salt and hash the password
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(password.encode("utf-8"), salt)
return hashed.decode("utf-8")
def create_access_token(subject: Union[str, Any], expires_delta: timedelta = None) -> str:
"""Generate a JWT access token for a subject (usually user phone)."""
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode = {"exp": expire, "sub": str(subject)}
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
return encoded_jwt