
- 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
54 lines
1.7 KiB
Python
54 lines
1.7 KiB
Python
from fastapi import APIRouter, HTTPException, status, Depends
|
|
|
|
from app.schemas.user import UserUpdate, PasswordChange, UserResponse, Message
|
|
from app.services.user_service import user_service
|
|
from app.utils.dependencies import get_current_active_user
|
|
from app.models.user import UserInDB
|
|
|
|
router = APIRouter()
|
|
|
|
@router.put("/username", response_model=UserResponse)
|
|
async def update_username(
|
|
user_update: UserUpdate,
|
|
current_user: UserInDB = Depends(get_current_active_user)
|
|
):
|
|
if not user_update.username:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Username is required"
|
|
)
|
|
|
|
updated_user = await user_service.update_username(str(current_user.id), user_update.username)
|
|
if not updated_user:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Username already taken"
|
|
)
|
|
|
|
return UserResponse(
|
|
id=str(updated_user.id),
|
|
email=updated_user.email,
|
|
username=updated_user.username,
|
|
is_active=updated_user.is_active,
|
|
created_at=updated_user.created_at,
|
|
updated_at=updated_user.updated_at
|
|
)
|
|
|
|
@router.put("/password", response_model=Message)
|
|
async def change_password(
|
|
password_change: PasswordChange,
|
|
current_user: UserInDB = Depends(get_current_active_user)
|
|
):
|
|
success = await user_service.change_password(
|
|
str(current_user.id),
|
|
password_change.current_password,
|
|
password_change.new_password
|
|
)
|
|
|
|
if not success:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Current password is incorrect"
|
|
)
|
|
|
|
return {"message": "Password updated successfully"} |