Exception handling enhancement
This commit is contained in:
@@ -1,18 +1,24 @@
|
||||
# app/services/auth_service.py
|
||||
"""Summary description ....
|
||||
"""
|
||||
Authentication service for user registration and login.
|
||||
|
||||
This module provides classes and functions for:
|
||||
- ....
|
||||
- ....
|
||||
- ....
|
||||
- User registration with validation
|
||||
- User authentication and JWT token generation
|
||||
- Password management and security
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.exceptions import (
|
||||
UserAlreadyExistsException,
|
||||
InvalidCredentialsException,
|
||||
UserNotActiveException,
|
||||
ValidationException,
|
||||
)
|
||||
from middleware.auth import AuthManager
|
||||
from models.schemas.auth import UserLogin, UserRegister
|
||||
from models.database.user import User
|
||||
@@ -39,36 +45,41 @@ class AuthService:
|
||||
Created user object
|
||||
|
||||
Raises:
|
||||
HTTPException: If email or username already exists
|
||||
UserAlreadyExistsException: If email or username already exists
|
||||
ValidationException: If user data is invalid
|
||||
"""
|
||||
# Check if email already exists
|
||||
existing_email = db.query(User).filter(User.email == user_data.email).first()
|
||||
if existing_email:
|
||||
raise HTTPException(status_code=400, detail="Email already registered")
|
||||
try:
|
||||
# Check if email already exists
|
||||
if self._email_exists(db, user_data.email):
|
||||
raise UserAlreadyExistsException("Email already registered", field="email")
|
||||
|
||||
# Check if username already exists
|
||||
existing_username = (
|
||||
db.query(User).filter(User.username == user_data.username).first()
|
||||
)
|
||||
if existing_username:
|
||||
raise HTTPException(status_code=400, detail="Username already taken")
|
||||
# Check if username already exists
|
||||
if self._username_exists(db, user_data.username):
|
||||
raise UserAlreadyExistsException("Username already taken", field="username")
|
||||
|
||||
# Hash password and create user
|
||||
hashed_password = self.auth_manager.hash_password(user_data.password)
|
||||
new_user = User(
|
||||
email=user_data.email,
|
||||
username=user_data.username,
|
||||
hashed_password=hashed_password,
|
||||
role="user",
|
||||
is_active=True,
|
||||
)
|
||||
# Hash password and create user
|
||||
hashed_password = self.auth_manager.hash_password(user_data.password)
|
||||
new_user = User(
|
||||
email=user_data.email,
|
||||
username=user_data.username,
|
||||
hashed_password=hashed_password,
|
||||
role="user",
|
||||
is_active=True,
|
||||
)
|
||||
|
||||
db.add(new_user)
|
||||
db.commit()
|
||||
db.refresh(new_user)
|
||||
db.add(new_user)
|
||||
db.commit()
|
||||
db.refresh(new_user)
|
||||
|
||||
logger.info(f"New user registered: {new_user.username}")
|
||||
return new_user
|
||||
logger.info(f"New user registered: {new_user.username}")
|
||||
return new_user
|
||||
|
||||
except UserAlreadyExistsException:
|
||||
raise # Re-raise custom exceptions
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
logger.error(f"Error registering user: {str(e)}")
|
||||
raise ValidationException("Registration failed")
|
||||
|
||||
def login_user(self, db: Session, user_credentials: UserLogin) -> Dict[str, Any]:
|
||||
"""
|
||||
@@ -82,53 +93,94 @@ class AuthService:
|
||||
Dictionary containing access token data and user object
|
||||
|
||||
Raises:
|
||||
HTTPException: If authentication fails
|
||||
InvalidCredentialsException: If authentication fails
|
||||
UserNotActiveException: If user account is not active
|
||||
"""
|
||||
user = self.auth_manager.authenticate_user(
|
||||
db, user_credentials.username, user_credentials.password
|
||||
)
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=401, detail="Incorrect username or password"
|
||||
try:
|
||||
user = self.auth_manager.authenticate_user(
|
||||
db, user_credentials.username, user_credentials.password
|
||||
)
|
||||
if not user:
|
||||
raise InvalidCredentialsException("Incorrect username or password")
|
||||
|
||||
# Create access token
|
||||
token_data = self.auth_manager.create_access_token(user)
|
||||
# Check if user is active
|
||||
if not user.is_active:
|
||||
raise UserNotActiveException("User account is not active")
|
||||
|
||||
logger.info(f"User logged in: {user.username}")
|
||||
# Create access token
|
||||
token_data = self.auth_manager.create_access_token(user)
|
||||
|
||||
return {"token_data": token_data, "user": user}
|
||||
logger.info(f"User logged in: {user.username}")
|
||||
return {"token_data": token_data, "user": user}
|
||||
|
||||
except (InvalidCredentialsException, UserNotActiveException):
|
||||
raise # Re-raise custom exceptions
|
||||
except Exception as e:
|
||||
logger.error(f"Error during login: {str(e)}")
|
||||
raise InvalidCredentialsException()
|
||||
|
||||
def get_user_by_email(self, db: Session, email: str) -> Optional[User]:
|
||||
"""Get user by email."""
|
||||
return db.query(User).filter(User.email == email).first()
|
||||
try:
|
||||
return db.query(User).filter(User.email == email).first()
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting user by email: {str(e)}")
|
||||
return None
|
||||
|
||||
def get_user_by_username(self, db: Session, username: str) -> Optional[User]:
|
||||
"""Get user by username."""
|
||||
return db.query(User).filter(User.username == username).first()
|
||||
|
||||
def email_exists(self, db: Session, email: str) -> bool:
|
||||
"""Check if email already exists."""
|
||||
return db.query(User).filter(User.email == email).first() is not None
|
||||
|
||||
def username_exists(self, db: Session, username: str) -> bool:
|
||||
"""Check if username already exists."""
|
||||
return db.query(User).filter(User.username == username).first() is not None
|
||||
try:
|
||||
return db.query(User).filter(User.username == username).first()
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting user by username: {str(e)}")
|
||||
return None
|
||||
|
||||
def authenticate_user(
|
||||
self, db: Session, username: str, password: str
|
||||
) -> Optional[User]:
|
||||
"""Authenticate user with username/password."""
|
||||
return self.auth_manager.authenticate_user(db, username, password)
|
||||
try:
|
||||
return self.auth_manager.authenticate_user(db, username, password)
|
||||
except Exception as e:
|
||||
logger.error(f"Error authenticating user: {str(e)}")
|
||||
return None
|
||||
|
||||
def create_access_token(self, user: User) -> Dict[str, Any]:
|
||||
"""Create access token for user."""
|
||||
return self.auth_manager.create_access_token(user)
|
||||
try:
|
||||
return self.auth_manager.create_access_token(user)
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating access token: {str(e)}")
|
||||
raise ValidationException("Failed to create access token")
|
||||
|
||||
def hash_password(self, password: str) -> str:
|
||||
"""Hash password."""
|
||||
return self.auth_manager.hash_password(password)
|
||||
try:
|
||||
return self.auth_manager.hash_password(password)
|
||||
except Exception as e:
|
||||
logger.error(f"Error hashing password: {str(e)}")
|
||||
raise ValidationException("Failed to hash password")
|
||||
|
||||
# Private helper methods
|
||||
def _email_exists(self, db: Session, email: str) -> bool:
|
||||
"""Check if email already exists."""
|
||||
return db.query(User).filter(User.email == email).first() is not None
|
||||
|
||||
def _username_exists(self, db: Session, username: str) -> bool:
|
||||
"""Check if username already exists."""
|
||||
return db.query(User).filter(User.username == username).first() is not None
|
||||
|
||||
# Legacy methods for backward compatibility (deprecated)
|
||||
def email_exists(self, db: Session, email: str) -> bool:
|
||||
"""Check if email already exists. DEPRECATED: Use proper exception handling."""
|
||||
logger.warning("email_exists is deprecated, use proper exception handling")
|
||||
return self._email_exists(db, email)
|
||||
|
||||
def username_exists(self, db: Session, username: str) -> bool:
|
||||
"""Check if username already exists. DEPRECATED: Use proper exception handling."""
|
||||
logger.warning("username_exists is deprecated, use proper exception handling")
|
||||
return self._username_exists(db, username)
|
||||
|
||||
|
||||
# Create service instance following the same pattern as admin_service
|
||||
# Create service instance following the same pattern as other services
|
||||
auth_service = AuthService()
|
||||
|
||||
Reference in New Issue
Block a user