Improve error handling, logging, and security in authentication services and utilities
- Refactored `create_user` and `change_password` methods to add transaction rollback on failures and enhanced logging for error contexts. - Updated security utilities to use constant-time comparison (`hmac.compare_digest`) to mitigate timing attacks. - Adjusted API responses in registration and password reset flows for better security and user experience. - Added session invalidation after password resets to enhance account security.
This commit is contained in:
@@ -61,10 +61,11 @@ async def register_user(
|
||||
user = await AuthService.create_user(db, user_data)
|
||||
return user
|
||||
except AuthenticationError as e:
|
||||
# SECURITY: Don't reveal if email exists - generic error message
|
||||
logger.warning(f"Registration failed: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=str(e)
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Registration failed. Please check your information and try again."
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Unexpected error during registration: {str(e)}")
|
||||
@@ -439,11 +440,22 @@ async def confirm_password_reset(
|
||||
db.add(user)
|
||||
await db.commit()
|
||||
|
||||
logger.info(f"Password reset successful for {user.email}")
|
||||
# SECURITY: Invalidate all existing sessions after password reset
|
||||
# This prevents stolen sessions from being used after password change
|
||||
from app.crud.session_async import session_async as session_crud
|
||||
try:
|
||||
deactivated_count = await session_crud.deactivate_all_user_sessions(
|
||||
db,
|
||||
user_id=str(user.id)
|
||||
)
|
||||
logger.info(f"Password reset successful for {user.email}, invalidated {deactivated_count} sessions")
|
||||
except Exception as session_error:
|
||||
# Log but don't fail password reset if session invalidation fails
|
||||
logger.error(f"Failed to invalidate sessions after password reset: {str(session_error)}")
|
||||
|
||||
return MessageResponse(
|
||||
success=True,
|
||||
message="Password has been reset successfully. You can now log in with your new password."
|
||||
message="Password has been reset successfully. All devices have been logged out for security. You can now log in with your new password."
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
|
||||
@@ -62,7 +62,7 @@ async def get_my_organizations(
|
||||
# Add member count and role to each organization
|
||||
orgs_with_data = []
|
||||
for org in orgs:
|
||||
role = organization_crud.get_user_role_in_org(
|
||||
role = await organization_crud.get_user_role_in_org(
|
||||
db,
|
||||
user_id=current_user.id,
|
||||
organization_id=org.id
|
||||
|
||||
Reference in New Issue
Block a user