
- Set up FastAPI application with MongoDB Motor driver - Implemented user registration, login, and logout with HTTP-only cookies - Added JWT token authentication and password hashing - Created user management endpoints for username updates and password changes - Structured application with proper separation of concerns (models, schemas, services, routes) - Added CORS configuration and health endpoints - Documented API endpoints and environment variables in README
39 lines
1.2 KiB
Python
39 lines
1.2 KiB
Python
from fastapi import Depends, HTTPException, status, Request
|
|
from typing import Optional
|
|
|
|
from app.services.user_service import user_service
|
|
from app.utils.security import verify_token
|
|
from app.models.user import UserInDB
|
|
|
|
async def get_current_user(request: Request) -> UserInDB:
|
|
token = request.cookies.get("access_token")
|
|
|
|
if not token:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Not authenticated"
|
|
)
|
|
|
|
email = verify_token(token)
|
|
if email is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid token"
|
|
)
|
|
|
|
user = await user_service.get_user_by_email(email)
|
|
if user is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="User not found"
|
|
)
|
|
|
|
return user
|
|
|
|
async def get_current_active_user(current_user: UserInDB = Depends(get_current_user)) -> UserInDB:
|
|
if not current_user.is_active:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Inactive user"
|
|
)
|
|
return current_user |