from __future__ import annotations import logging from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.exc import IntegrityError, SQLAlchemyError from .deps import get_auth_service, get_bearer_token from .errors import ( AuthError, CurrentPasswordIncorrectError, InvalidCredentialsError, InvalidEmailError, InvalidOrExpiredOtpError, InvalidPhoneNumberError, InvalidTokenError, UnauthorizedError, UserAlreadyExistsError, UserInactiveError, UserNotFoundError, WeakPasswordError, ) from .schema import ( AuthTokenResponse, ChangePasswordRequest, ChangePasswordResponse, ForgotPasswordRequest, ForgotPasswordResponse, ProfileUpdateRequest, ProfileUpdateResponse, ResetPasswordRequest, ResetPasswordResponse, UserIdentityResponse, UserLoginRequest, UserRegisterRequest, ) from .security import normalize_email from .service import AuthService logger = logging.getLogger(__name__) router = APIRouter( prefix="/auth", tags=["Authentication"], ) def _translate_auth_error(exc: Exception) -> HTTPException: if isinstance(exc, (UnauthorizedError, InvalidTokenError)): return HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail=str(exc), ) if isinstance(exc, UserInactiveError): return HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=str(exc), ) if isinstance(exc, UserNotFoundError): return HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc), ) if isinstance( exc, ( InvalidCredentialsError, InvalidEmailError, InvalidOrExpiredOtpError, InvalidPhoneNumberError, WeakPasswordError, UserAlreadyExistsError, CurrentPasswordIncorrectError, ), ): return HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc), ) return HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Authentication operation failed.", ) @router.post("/register", response_model=AuthTokenResponse) async def register( payload: UserRegisterRequest, service: AuthService = Depends(get_auth_service), ) -> AuthTokenResponse: try: response = await service.register(payload) await service.session.commit() return response except AuthError as exc: await service.session.rollback() raise _translate_auth_error(exc) from exc except IntegrityError as exc: await service.session.rollback() raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="An account with the supplied identity already exists.", ) from exc @router.post("/login", response_model=AuthTokenResponse) async def login( payload: UserLoginRequest, service: AuthService = Depends(get_auth_service), ) -> AuthTokenResponse: try: response = await service.login(payload) await service.session.commit() return response except AuthError as exc: await service.session.rollback() raise _translate_auth_error(exc) from exc @router.get("/me", response_model=UserIdentityResponse) @router.get("/profile", response_model=UserIdentityResponse) async def get_identity( access_token: str = Depends(get_bearer_token), service: AuthService = Depends(get_auth_service), ) -> UserIdentityResponse: try: return await service.get_identity( access_token=access_token ) except UserNotFoundError as exc: raise HTTPException(status_code=404, detail=str(exc)) from exc except AuthError as exc: raise _translate_auth_error(exc) from exc @router.put("/profile", response_model=ProfileUpdateResponse) async def update_profile( payload: ProfileUpdateRequest, access_token: str = Depends(get_bearer_token), service: AuthService = Depends(get_auth_service), ) -> ProfileUpdateResponse: try: response = await service.update_profile( access_token=access_token, request=payload, ) await service.session.commit() return response except UserNotFoundError as exc: await service.session.rollback() raise HTTPException(status_code=404, detail=str(exc)) from exc except AuthError as exc: await service.session.rollback() raise _translate_auth_error(exc) from exc @router.post("/change-password", response_model=ChangePasswordResponse) async def change_password( payload: ChangePasswordRequest, access_token: str = Depends(get_bearer_token), service: AuthService = Depends(get_auth_service), ) -> ChangePasswordResponse: try: response = await service.change_password( access_token=access_token, request=payload, ) await service.session.commit() return response except UserNotFoundError as exc: await service.session.rollback() raise HTTPException(status_code=404, detail=str(exc)) from exc except AuthError as exc: await service.session.rollback() raise _translate_auth_error(exc) from exc @router.post("/forgot-password", response_model=ForgotPasswordResponse) async def forgot_password( payload: ForgotPasswordRequest, service: AuthService = Depends(get_auth_service), ) -> ForgotPasswordResponse: try: normalized_email = normalize_email(payload.email) response, otp_code = await service.forgot_password(payload) # Durably persist OTP before attempting SMTP delivery. await service.session.commit() if otp_code is not None: await service.send_password_reset_email( email=normalized_email, otp_code=otp_code, ) return response except AuthError as exc: await service.session.rollback() raise _translate_auth_error(exc) from exc except SQLAlchemyError as exc: await service.session.rollback() logger.exception("Unable to create password reset OTP") raise HTTPException( status_code=500, detail="Unable to process password reset request.", ) from exc @router.post("/reset-password", response_model=ResetPasswordResponse) async def reset_password( payload: ResetPasswordRequest, service: AuthService = Depends(get_auth_service), ) -> ResetPasswordResponse: try: response = await service.reset_password(payload) await service.session.commit() return response except AuthError as exc: await service.session.rollback() raise _translate_auth_error(exc) from exc except SQLAlchemyError as exc: await service.session.rollback() logger.exception("Unable to reset password") raise HTTPException( status_code=500, detail="Unable to reset password.", ) from exc