itcloud/backend/src/app/infra/security.py

98 lines
2.4 KiB
Python
Raw Normal View History

2025-12-30 13:35:19 +01:00
"""Security utilities for authentication and authorization."""
from datetime import datetime, timedelta
from typing import Optional
from jose import JWTError, jwt
from passlib.context import CryptContext
from app.infra.config import get_settings
settings = get_settings()
# Password hashing context
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def hash_password(password: str) -> str:
"""
Hash a password using bcrypt.
Args:
password: Plain text password
Returns:
Hashed password
"""
return pwd_context.hash(password)
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""
Verify a password against its hash.
Args:
plain_password: Plain text password
hashed_password: Hashed password to verify against
Returns:
True if password matches, False otherwise
"""
return pwd_context.verify(plain_password, hashed_password)
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
"""
Create a JWT access token.
Args:
data: Data to encode in the token
expires_delta: Optional expiration time delta
Returns:
Encoded JWT token
"""
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(seconds=settings.jwt_access_ttl_seconds)
to_encode.update({"exp": expire, "type": "access"})
encoded_jwt = jwt.encode(to_encode, settings.jwt_secret, algorithm=settings.jwt_algorithm)
return encoded_jwt
def create_refresh_token(data: dict) -> str:
"""
Create a JWT refresh token.
Args:
data: Data to encode in the token
Returns:
Encoded JWT token
"""
to_encode = data.copy()
expire = datetime.utcnow() + timedelta(seconds=settings.jwt_refresh_ttl_seconds)
to_encode.update({"exp": expire, "type": "refresh"})
encoded_jwt = jwt.encode(to_encode, settings.jwt_secret, algorithm=settings.jwt_algorithm)
return encoded_jwt
def decode_token(token: str) -> Optional[dict]:
"""
Decode and verify a JWT token.
Args:
token: JWT token to decode
Returns:
Decoded token payload or None if invalid
"""
try:
payload = jwt.decode(token, settings.jwt_secret, algorithms=[settings.jwt_algorithm])
return payload
except JWTError:
return None