Automated Action e01f6aaf16 Fix linting issues and finalize User Authentication Service
- Removed unused imports in deps.py, routes/auth.py, and models/user.py
- Code is now lint-free and follows best practices
- Complete FastAPI user authentication service with JWT token support

generated with BackendIM... (backend.im)
2025-05-14 09:46:58 +00:00

79 lines
2.3 KiB
Python

from datetime import timedelta
from typing import Any
from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from app import schemas
from app.api import deps
from app.core import security
from app.core.config import settings
from app.db import crud
router = APIRouter(prefix=f"{settings.API_V1_STR}/auth", tags=["auth"])
@router.post("/register", response_model=schemas.User)
def register_user(
*,
db: Session = Depends(deps.get_db),
user_in: schemas.UserCreate,
) -> Any:
"""
Register a new user.
"""
# Check if user with this email already exists
user = crud.get_user_by_email(db, email=user_in.email)
if user:
raise HTTPException(
status_code=400,
detail="A user with this email already exists in the system.",
)
# Check if user with this username already exists
user = crud.get_user_by_username(db, username=user_in.username)
if user:
raise HTTPException(
status_code=400,
detail="A user with this username already exists in the system.",
)
# Create new user
user = crud.create_user(db, user_in=user_in)
return user
@router.post("/login", response_model=schemas.Token)
def login_access_token(
db: Session = Depends(deps.get_db),
form_data: OAuth2PasswordRequestForm = Depends(),
) -> Any:
"""
OAuth2 compatible token login, get an access token for future requests.
"""
user = crud.authenticate_user(
db, username=form_data.username, password=form_data.password
)
if not user:
raise HTTPException(status_code=400, detail="Incorrect username or password")
elif not crud.is_active_user(user):
raise HTTPException(status_code=400, detail="Inactive user")
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
return {
"access_token": security.create_access_token(
user.id, expires_delta=access_token_expires
),
"token_type": "bearer",
}
@router.get("/me", response_model=schemas.User)
def read_users_me(
current_user: schemas.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Get current user.
"""
return current_user