5.8 KiB
5.8 KiB
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:
{
"email": "user@example.com"
}
Response:
{
"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:
{
"token": "abc123def456ghi789",
"newPassword": "newSecurePassword123!"
}
Response:
{
"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
-
Token Security:
- Tokens are hashed before storage
- 1-hour expiration time
- Single-use tokens (cleared after use)
-
Password Validation:
- Minimum 6 characters
- Maximum 100 characters
- Password strength validation via PasswordService
-
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 Requestwith 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:
curl -X POST http://localhost:3000/api/users/forgot-password \
-H "Content-Type: application/json" \
-d '{"email": "test@example.com"}'
Test Reset Password:
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:
- Invalid email format:
curl -X POST http://localhost:3000/api/users/forgot-password \
-H "Content-Type: application/json" \
-d '{"email": "invalid-email"}'
- Missing token:
curl -X POST http://localhost:3000/api/users/reset-password \
-H "Content-Type: application/json" \
-d '{"newPassword": "newPassword123!"}'
- Weak password:
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:
- User clicks "Forgot Password" on login page
- User enters email address
- Frontend calls
/api/users/forgot-password - User receives email with reset link
- User clicks link or uses token
- Frontend presents password reset form
- Frontend calls
/api/users/reset-password - User can login with new password
Sample Frontend Code:
// 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:
# 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
- Rate Limiting: Consider implementing rate limiting on password reset requests
- IP Tracking: Log IP addresses for security monitoring
- Account Lockout: Consider temporary lockout after multiple failed attempts
- Token Entropy: Tokens use cryptographically secure random generation
- 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.