Spaces:
Sleeping
Sleeping
File size: 5,857 Bytes
dacae32 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 | # 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)
```python
@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:**
```python
# 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:**
```python
# 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:**
```python
# 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`:
```python
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):
3. β³ Audit log viewing API
4. β³ Audit log export
5. β³ Session management UI
6. β³ 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!
|