Working on API
This commit is contained in:
80
src/file-processor/app/api/routes/auth.py
Normal file
80
src/file-processor/app/api/routes/auth.py
Normal file
@@ -0,0 +1,80 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
|
||||
from app.api.dependencies import get_auth_service, get_current_user, get_user_service
|
||||
from app.models.auth import LoginResponse, UserResponse
|
||||
from app.models.user import UserInDB
|
||||
from app.services.auth_service import AuthService
|
||||
from app.services.user_service import UserService
|
||||
|
||||
router = APIRouter(tags=["authentication"])
|
||||
|
||||
|
||||
@router.post("/login", response_model=LoginResponse)
|
||||
def login(
|
||||
form_data: OAuth2PasswordRequestForm = Depends(),
|
||||
auth_service: AuthService = Depends(get_auth_service),
|
||||
user_service: UserService = Depends(get_user_service)
|
||||
):
|
||||
"""
|
||||
Authenticate user and return JWT token.
|
||||
|
||||
Args:
|
||||
form_data: OAuth2 password form data
|
||||
auth_service: Auth service instance
|
||||
user_service: User service instance
|
||||
|
||||
Returns:
|
||||
LoginResponse: JWT token and user info
|
||||
|
||||
Raises:
|
||||
HTTPException: If authentication fails
|
||||
"""
|
||||
incorrect_username_or_pwd = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect username or password",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
user = user_service.get_user_by_username(form_data.username)
|
||||
if (not user or
|
||||
not user.is_active or
|
||||
not auth_service.verify_user_password(form_data.password, user.hashed_password)):
|
||||
raise incorrect_username_or_pwd
|
||||
|
||||
access_token = auth_service.create_access_token(data={"sub": user.username})
|
||||
|
||||
return LoginResponse(
|
||||
access_token=access_token,
|
||||
user=UserResponse(
|
||||
_id=user.id,
|
||||
username=user.username,
|
||||
email=user.email,
|
||||
role=user.role,
|
||||
is_active=user.is_active,
|
||||
created_at=user.created_at,
|
||||
updated_at=user.updated_at
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserResponse)
|
||||
def get_current_user_profile(current_user: UserInDB = Depends(get_current_user)):
|
||||
"""
|
||||
Get current user profile.
|
||||
|
||||
Args:
|
||||
current_user: Current authenticated user
|
||||
|
||||
Returns:
|
||||
UserResponse: Current user profile without sensitive data
|
||||
"""
|
||||
return UserResponse(
|
||||
_id=current_user.id,
|
||||
username=current_user.username,
|
||||
email=current_user.email,
|
||||
role=current_user.role,
|
||||
is_active=current_user.is_active,
|
||||
created_at=current_user.created_at,
|
||||
updated_at=current_user.updated_at
|
||||
)
|
||||
Reference in New Issue
Block a user