mitlist/be/app/core/security.py
mohamad f49e15c05c
Some checks failed
Deploy to Production, build images and push to Gitea Registry / build_and_push (pull_request) Failing after 1m24s
feat: Introduce FastAPI and Vue.js guidelines, enhance API structure, and add caching support
This commit adds new guidelines for FastAPI and Vue.js development, emphasizing best practices for component structure, API performance, and data handling. It also introduces caching mechanisms using Redis for improved performance and updates the API structure to streamline authentication and user management. Additionally, new endpoints for categories and time entries are implemented, enhancing the overall functionality of the application.
2025-06-09 21:02:51 +02:00

74 lines
2.2 KiB
Python

from passlib.context import CryptContext
from datetime import datetime, timedelta
from jose import jwt
from typing import Optional
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""
Verifies a plain text password against a hashed password.
This is used by FastAPI-Users internally, but also exposed here for custom authentication flows
if needed.
Args:
plain_password: The password attempt.
hashed_password: The stored hash from the database.
Returns:
True if the password matches the hash, False otherwise.
"""
try:
return pwd_context.verify(plain_password, hashed_password)
except Exception:
return False
def hash_password(password: str) -> str:
"""
Hashes a plain text password using the configured context (bcrypt).
This is used by FastAPI-Users internally, but also exposed here for
custom user creation or password reset flows if needed.
Args:
password: The plain text password to hash.
Returns:
The resulting hash string.
"""
return pwd_context.hash(password)
# Alias for compatibility with guest.py
def get_password_hash(password: str) -> str:
"""
Alias for hash_password function for backward compatibility.
Args:
password: The plain text password to hash.
Returns:
The resulting hash string.
"""
return hash_password(password)
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
"""
Create a JWT access token.
Args:
data: The data to encode in the token (typically {"sub": email}).
expires_delta: Optional custom expiration time.
Returns:
The encoded JWT token.
"""
from app.config import settings
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm="HS256")
return encoded_jwt