59 lines
1.7 KiB
Python
59 lines
1.7 KiB
Python
from typing import Generator, Optional
|
|
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.db.session import get_db
|
|
from app.models.user import User
|
|
from app.services.auth import verify_token, get_user_by_username
|
|
|
|
# Security scheme
|
|
security = HTTPBearer()
|
|
|
|
|
|
def get_current_user(
|
|
db: Session = Depends(get_db),
|
|
credentials: HTTPAuthorizationCredentials = Depends(security),
|
|
) -> User:
|
|
"""Get current authenticated user."""
|
|
credentials_exception = HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
# Verify token
|
|
username = verify_token(credentials.credentials)
|
|
if username is None:
|
|
raise credentials_exception
|
|
|
|
# Get user from database
|
|
user = get_user_by_username(db, username=username)
|
|
if user is None:
|
|
raise credentials_exception
|
|
|
|
if not user.is_active:
|
|
raise HTTPException(status_code=400, detail="Inactive user")
|
|
|
|
return user
|
|
|
|
|
|
def get_current_active_user(
|
|
current_user: User = Depends(get_current_user),
|
|
) -> User:
|
|
"""Get current active user."""
|
|
if not current_user.is_active:
|
|
raise HTTPException(status_code=400, detail="Inactive user")
|
|
return current_user
|
|
|
|
|
|
def get_current_active_superuser(
|
|
current_user: User = Depends(get_current_user),
|
|
) -> User:
|
|
"""Get current active superuser."""
|
|
if not current_user.is_superuser:
|
|
raise HTTPException(
|
|
status_code=400, detail="The user doesn't have enough privileges"
|
|
)
|
|
return current_user |