Initial commit: Role-based data visualisation platform for DMH hospital admissions (Phases 1-3)
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
|
||||
class AuthException(HTTPException):
|
||||
def __init__(self, detail: str = "Could not validate credentials"):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=detail,
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
|
||||
class ForbiddenException(HTTPException):
|
||||
def __init__(self, detail: str = "Access forbidden: insufficient permissions"):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=detail
|
||||
)
|
||||
|
||||
|
||||
class NotFoundException(HTTPException):
|
||||
def __init__(self, detail: str = "Resource not found"):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=detail
|
||||
)
|
||||
|
||||
|
||||
class ConflictException(HTTPException):
|
||||
def __init__(self, detail: str = "Resource already exists"):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=detail
|
||||
)
|
||||
|
||||
|
||||
class ValidationException(HTTPException):
|
||||
def __init__(self, detail: str = "Invalid query or parameters"):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=detail
|
||||
)
|
||||
@@ -0,0 +1,43 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Dict, Optional
|
||||
import jwt
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError, InvalidHashError
|
||||
from app.config import settings
|
||||
|
||||
ph = PasswordHasher()
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""Hashes a plain password using argon2-cffi."""
|
||||
return ph.hash(password)
|
||||
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
"""Verifies a plain password against an argon2 hash."""
|
||||
try:
|
||||
return ph.verify(hashed_password, plain_password)
|
||||
except (VerifyMismatchError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
def create_access_token(data: Dict[str, Any], expires_delta: Optional[timedelta] = None) -> str:
|
||||
"""Creates a signed JWT token with PyJWT."""
|
||||
to_encode = data.copy()
|
||||
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.update({"exp": expire, "iat": datetime.now(timezone.utc)})
|
||||
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
return encoded_jwt
|
||||
|
||||
|
||||
def decode_access_token(token: str) -> Optional[Dict[str, Any]]:
|
||||
"""Decodes and validates a JWT token using PyJWT."""
|
||||
try:
|
||||
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
||||
return payload
|
||||
except (jwt.PyJWTError, Exception):
|
||||
return None
|
||||
Reference in New Issue
Block a user