swiftops-backend / docs /agent /implementation-notes /PASSWORD_RESET_AND_AUDIT_IMPLEMENTATION.md
kamau1's picture
feat(project): add complete project setup workflow with service methods and API endpoints for regions, roles, subcontractors, and finalization including validation and authorization
4835b24

Password Reset & Audit Logging Implementation

Summary

I've analyzed your session management and created the foundation for password reset and audit logging. Here's what's been done and what remains:


βœ… Session Management Analysis

Verdict: Your current approach is EXCELLENT and industry-standard!

  • Using Supabase Auth with JWT tokens (stateless)
  • Scales to millions of users
  • No session storage overhead
  • Battle-tested approach (used by Auth0, Firebase, AWS Cognito)

Recommendation: Keep as is. No changes needed.

See docs/agent/SESSION_MANAGEMENT_ANALYSIS.md for full analysis.


βœ… Completed

1. Audit Log Model

  • Created src/app/models/audit_log.py
  • Maps to existing audit_logs table in schema
  • Tracks: user_id, action, entity_type, changes, IP, user_agent, location

2. Audit Service

  • Created src/app/services/audit_service.py
  • log_action() - Generic action logging
  • log_auth_event() - Specialized for auth events (login, logout, failures)
  • Extracts IP address and user agent from requests
  • Graceful failure (doesn't break main operations)

3. Password Reset Schemas

  • Added to src/app/schemas/auth.py:
    • ForgotPasswordRequest - Email input
    • ResetPasswordRequest - Token + new password
    • MessageResponse - Generic message response

πŸ”„ Remaining Implementation

1. Password Reset Endpoints (auth.py)

@router.post("/forgot-password", response_model=MessageResponse)
async def forgot_password(
    request_data: ForgotPasswordRequest,
    db: Session = Depends(get_db),
    request: Request = None
):
    """
    Request password reset email
    
    - Generates secure reset token
    - Sends email with reset link
    - Logs audit event
    """
    # Implementation needed

@router.post("/reset-password", response_model=MessageResponse)
async def reset_password(
    reset_data: ResetPasswordRequest,
    db: Session = Depends(get_db),
    request: Request = None
):
    """
    Reset password with token
    
    - Validates reset token
    - Updates password in Supabase
    - Logs audit event
    """
    # Implementation needed

2. Update Existing Auth Endpoints with Audit Logging

Login endpoint:

# Add after successful login
AuditService.log_auth_event(
    db=db,
    action='login',
    user_email=credentials.email,
    success=True,
    request=request
)

# Add after failed login
AuditService.log_auth_event(
    db=db,
    action='login',
    user_email=credentials.email,
    success=False,
    request=request,
    reason="Invalid credentials"
)

Register endpoint:

# Add after successful registration
AuditService.log_action(
    db=db,
    action='create',
    entity_type='user',
    entity_id=str(new_user.id),
    description=f"User registered: {user_data.email}",
    user=new_user,
    request=request
)

Password change endpoint:

# Add after successful password change
AuditService.log_action(
    db=db,
    action='update',
    entity_type='user',
    entity_id=str(current_user.id),
    description=f"Password changed for user: {current_user.email}",
    user=current_user,
    request=request
)

3. Password Reset Service

Create src/app/services/password_reset_service.py:

class PasswordResetService:
    @staticmethod
    async def request_reset(email: str, db: Session):
        """
        Generate reset token and send email
        
        1. Check if user exists
        2. Generate secure token (32 chars)
        3. Store token in user_invitations table (reuse) or create new table
        4. Send email with reset link
        5. Log audit event
        """
        pass
    
    @staticmethod
    async def reset_password(token: str, new_password: str, db: Session):
        """
        Reset password with token
        
        1. Validate token (not expired, exists)
        2. Get user from token
        3. Update password in Supabase
        4. Invalidate token
        5. Log audit event
        """
        pass

4. Email Templates

Create src/app/templates/emails/password_reset.html:

  • Professional HTML template
  • Reset link with token
  • Expiry notice (1 hour)
  • Security notice

5. Token Storage Options

Option A: Reuse user_invitations table

  • Add invitation_type field ('invitation' | 'password_reset')
  • Reuse existing token infrastructure
  • Simpler, no new table

Option B: Create password_reset_tokens table

  • Dedicated table for reset tokens
  • Cleaner separation of concerns
  • More explicit

Recommendation: Option A (reuse invitations table)


πŸ“‹ Implementation Steps

Step 1: Update Auth Endpoints with Audit Logging (15 min)

  • Add audit logging to login
  • Add audit logging to register
  • Add audit logging to password change
  • Add audit logging to profile updates

Step 2: Create Password Reset Service (20 min)

  • Token generation
  • Email sending
  • Token validation
  • Password update

Step 3: Add Password Reset Endpoints (15 min)

  • POST /auth/forgot-password
  • POST /auth/reset-password

Step 4: Create Email Template (10 min)

  • HTML template for password reset
  • Include reset link
  • Security notices

Step 5: Testing (10 min)

  • Test forgot password flow
  • Test reset password flow
  • Test audit logging
  • Test token expiry

Total Time: ~70 minutes


🎯 Priority

Must Have (Implement Now):

  1. βœ… Audit logging for auth events
  2. βœ… Password reset flow

Nice to Have (Later):

  1. ⏳ Audit log viewing API
  2. ⏳ Audit log export
  3. ⏳ Session management UI
  4. ⏳ Refresh tokens

Next Steps

Would you like me to:

  1. Complete the implementation (all remaining code)
  2. Review the plan first and adjust
  3. Implement in phases (audit logging first, then password reset)

Let me know and I'll proceed!