226 lines
5.8 KiB
Markdown
226 lines
5.8 KiB
Markdown
# Password Reset Implementation Guide
|
|
|
|
## Overview
|
|
The SerpentRace application includes a complete password reset system with email verification and secure token handling.
|
|
|
|
## API Endpoints
|
|
|
|
### 1. Forgot Password (Request Reset)
|
|
**Endpoint:** `POST /api/users/forgot-password`
|
|
|
|
**Request Body:**
|
|
```json
|
|
{
|
|
"email": "user@example.com"
|
|
}
|
|
```
|
|
|
|
**Response:**
|
|
```json
|
|
{
|
|
"message": "If the email exists, a reset link has been sent to your email address."
|
|
}
|
|
```
|
|
|
|
**Features:**
|
|
- Validates email format
|
|
- Security: Always returns success message (doesn't reveal if email exists)
|
|
- Generates secure reset token with 1-hour expiration
|
|
- Sends multilingual email with reset link and token
|
|
- Logs all password reset attempts
|
|
|
|
### 2. Reset Password (Complete Reset)
|
|
**Endpoint:** `POST /api/users/reset-password`
|
|
|
|
**Request Body:**
|
|
```json
|
|
{
|
|
"token": "abc123def456ghi789",
|
|
"newPassword": "newSecurePassword123!"
|
|
}
|
|
```
|
|
|
|
**Response:**
|
|
```json
|
|
{
|
|
"message": "Password has been reset successfully. You can now login with your new password."
|
|
}
|
|
```
|
|
|
|
**Features:**
|
|
- Validates token existence and expiration
|
|
- Enforces password strength requirements
|
|
- Hashes new password securely
|
|
- Clears reset token after successful reset
|
|
- Comprehensive error handling
|
|
|
|
## Implementation Details
|
|
|
|
### Security Features
|
|
1. **Token Security:**
|
|
- Tokens are hashed before storage
|
|
- 1-hour expiration time
|
|
- Single-use tokens (cleared after use)
|
|
|
|
2. **Password Validation:**
|
|
- Minimum 6 characters
|
|
- Maximum 100 characters
|
|
- Password strength validation via PasswordService
|
|
|
|
3. **Email Privacy:**
|
|
- Non-existent emails don't reveal account existence
|
|
- Consistent response messages
|
|
|
|
### Error Handling
|
|
- Invalid/expired tokens: `400 Bad Request`
|
|
- Password validation failures: `400 Bad Request` with specific message
|
|
- Token expiration: Clear error message
|
|
- Server errors: `500 Internal Server Error`
|
|
|
|
### Email Templates
|
|
The system supports multilingual email templates:
|
|
- `password-reset.txt` (English)
|
|
- `password-reset-hu.txt` (Hungarian)
|
|
- `password-reset-de.txt` (German)
|
|
|
|
Templates include:
|
|
- Reset URL link
|
|
- Reset token (fallback)
|
|
- Security warnings
|
|
- Expiration information
|
|
|
|
## Testing the Implementation
|
|
|
|
### Test Forgot Password:
|
|
```bash
|
|
curl -X POST http://localhost:3000/api/users/forgot-password \
|
|
-H "Content-Type: application/json" \
|
|
-d '{"email": "test@example.com"}'
|
|
```
|
|
|
|
### Test Reset Password:
|
|
```bash
|
|
curl -X POST http://localhost:3000/api/users/reset-password \
|
|
-H "Content-Type: application/json" \
|
|
-d '{"token": "your-reset-token", "newPassword": "newPassword123!"}'
|
|
```
|
|
|
|
### Error Test Cases:
|
|
1. **Invalid email format:**
|
|
```bash
|
|
curl -X POST http://localhost:3000/api/users/forgot-password \
|
|
-H "Content-Type: application/json" \
|
|
-d '{"email": "invalid-email"}'
|
|
```
|
|
|
|
2. **Missing token:**
|
|
```bash
|
|
curl -X POST http://localhost:3000/api/users/reset-password \
|
|
-H "Content-Type: application/json" \
|
|
-d '{"newPassword": "newPassword123!"}'
|
|
```
|
|
|
|
3. **Weak password:**
|
|
```bash
|
|
curl -X POST http://localhost:3000/api/users/reset-password \
|
|
-H "Content-Type: application/json" \
|
|
-d '{"token": "valid-token", "newPassword": "123"}'
|
|
```
|
|
|
|
## Integration with Existing Services
|
|
|
|
### Used Services:
|
|
- **EmailService:** Sends multilingual reset emails
|
|
- **TokenService:** Generates and validates reset tokens
|
|
- **PasswordService:** Validates and hashes passwords
|
|
- **ValidationMiddleware:** Validates request data
|
|
- **Logger:** Logs all operations for audit
|
|
|
|
### Database Integration:
|
|
- **UserRepository:** Finds users by email/token, updates passwords
|
|
- Token storage in user table with expiration
|
|
|
|
## Frontend Integration
|
|
|
|
### Reset Flow:
|
|
1. User clicks "Forgot Password" on login page
|
|
2. User enters email address
|
|
3. Frontend calls `/api/users/forgot-password`
|
|
4. User receives email with reset link
|
|
5. User clicks link or uses token
|
|
6. Frontend presents password reset form
|
|
7. Frontend calls `/api/users/reset-password`
|
|
8. User can login with new password
|
|
|
|
### Sample Frontend Code:
|
|
```javascript
|
|
// Request password reset
|
|
async function requestPasswordReset(email) {
|
|
const response = await fetch('/api/users/forgot-password', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ email })
|
|
});
|
|
|
|
if (response.ok) {
|
|
alert('Reset link sent to your email!');
|
|
}
|
|
}
|
|
|
|
// Reset password
|
|
async function resetPassword(token, newPassword) {
|
|
const response = await fetch('/api/users/reset-password', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ token, newPassword })
|
|
});
|
|
|
|
if (response.ok) {
|
|
alert('Password reset successful!');
|
|
// Redirect to login
|
|
} else {
|
|
const error = await response.json();
|
|
alert('Error: ' + error.error);
|
|
}
|
|
}
|
|
```
|
|
|
|
## Environment Configuration
|
|
|
|
Required environment variables:
|
|
```env
|
|
# Email Configuration
|
|
EMAIL_HOST=smtp.gmail.com
|
|
EMAIL_PORT=587
|
|
EMAIL_SECURE=false
|
|
EMAIL_USER=your-email@gmail.com
|
|
EMAIL_PASS=your-app-password
|
|
EMAIL_FROM=noreply@serpentrace.com
|
|
|
|
# Application URL for reset links
|
|
APP_BASE_URL=http://localhost:3000
|
|
```
|
|
|
|
## Monitoring and Logging
|
|
|
|
All password reset operations are logged with:
|
|
- Request details (sanitized)
|
|
- Success/failure status
|
|
- Error messages
|
|
- User identification (when available)
|
|
- Timestamps
|
|
|
|
Log entries help with:
|
|
- Security monitoring
|
|
- Troubleshooting issues
|
|
- Audit trail compliance
|
|
|
|
## Security Considerations
|
|
|
|
1. **Rate Limiting:** Consider implementing rate limiting on password reset requests
|
|
2. **IP Tracking:** Log IP addresses for security monitoring
|
|
3. **Account Lockout:** Consider temporary lockout after multiple failed attempts
|
|
4. **Token Entropy:** Tokens use cryptographically secure random generation
|
|
5. **Email Security:** Ensure SMTP connection is encrypted
|
|
|
|
This implementation provides a secure, user-friendly password reset system that integrates seamlessly with the existing SerpentRace authentication infrastructure. |