Automated Action 8575427c43 Implement user authentication flow
- Setup project structure with FastAPI
- Create user models with SQLAlchemy
- Implement JWT authentication
- Create auth endpoints (register, login, me)
- Add health endpoint
- Generate Alembic migrations
- Update documentation

Generated with BackendIM... (backend.im)
2025-05-12 17:00:50 +00:00

105 lines
2.8 KiB
Python

from typing import Generator, Optional
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import jwt, JWTError
from pydantic import ValidationError
from sqlalchemy.orm import Session
from app.core.config import settings
from app.core.security import (
create_access_token,
get_password_hash,
verify_password,
)
from app.db.session import get_db
from app.models.user import User
from app.schemas.token import TokenPayload
from app.services import user as user_service
reusable_oauth2 = OAuth2PasswordBearer(
tokenUrl=f"{settings.API_V1_STR}/auth/login"
)
def get_current_user(
db: Session = Depends(get_db), token: str = Depends(reusable_oauth2)
) -> User:
"""
Get the current user based on JWT token.
Args:
db: Database session
token: JWT token from OAuth2 dependency
Returns:
User: Current user model
Raises:
HTTPException: If token is invalid or user doesn't exist
"""
try:
payload = jwt.decode(
token, settings.SECRET_KEY, algorithms=["HS256"]
)
token_data = TokenPayload(**payload)
except (JWTError, ValidationError):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
user = user_service.get_by_id(db, id=token_data.sub)
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
return user
def get_current_active_user(
current_user: User = Depends(get_current_user),
) -> User:
"""
Get current active user (inactive users cannot use the system).
Args:
current_user: Current user from get_current_user dependency
Returns:
User: Current active user
Raises:
HTTPException: If user is inactive
"""
if not user_service.is_active(current_user):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Inactive user"
)
return current_user
def get_current_active_superuser(
current_user: User = Depends(get_current_active_user),
) -> User:
"""
Get current active superuser.
Args:
current_user: Current active user from get_current_active_user dependency
Returns:
User: Current active superuser
Raises:
HTTPException: If user is not a superuser
"""
if not user_service.is_superuser(current_user):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not enough permissions"
)
return current_user