e35ac6a41c
Security Enhancements: - Fix SQL injection vulnerabilities by replacing whereRaw queries with parameterized queries - Add LIKE pattern escaping to prevent SQL injection in search functionality - Implement account lockout protection (5 failed attempts = 30 min lockout) - Add comprehensive login attempt tracking and audit trail - Enhance JWT tokens with issuer validation, IP tracking, and password change detection - Add logout endpoint and session management - Prevent user enumeration with generic error messages Database Changes: - Add login_attempts table for authentication tracking - Add security columns to admin_users (password_changed_at, last_login_ip, two_factor_enabled) New Security Features: - Brute force protection with configurable lockout duration - Automatic cleanup of old login attempts - Enhanced authentication middleware with stricter validation - Monitoring scripts for security health checks All fixes are backward compatible and production-ready with rollback plans included. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
216 lines
4.8 KiB
Markdown
216 lines
4.8 KiB
Markdown
# Authentication Security Integration Guide
|
|
|
|
## How The Enhanced Security Works
|
|
|
|
### 1. Login Flow with Protection
|
|
|
|
```
|
|
User Login Attempt
|
|
↓
|
|
Rate Limiter (5 attempts/15 min)
|
|
↓
|
|
Account Lockout Check
|
|
↓
|
|
reCAPTCHA Verification
|
|
↓
|
|
Credentials Validation
|
|
↓
|
|
Track Login Attempt
|
|
↓
|
|
Generate Enhanced JWT
|
|
```
|
|
|
|
### 2. Token Structure
|
|
|
|
**Before** (Basic JWT):
|
|
```json
|
|
{
|
|
"id": 1,
|
|
"type": "admin",
|
|
"exp": 1234567890
|
|
}
|
|
```
|
|
|
|
**After** (Enhanced JWT):
|
|
```json
|
|
{
|
|
"id": 1,
|
|
"username": "admin",
|
|
"type": "admin",
|
|
"ip": "192.168.1.100",
|
|
"loginTime": 1234567890,
|
|
"exp": 1234567890,
|
|
"iss": "picpeak-auth"
|
|
}
|
|
```
|
|
|
|
### 3. Security Layers
|
|
|
|
1. **Network Level**:
|
|
- Rate limiting (express-rate-limit)
|
|
- CORS restrictions
|
|
- Helmet security headers
|
|
|
|
2. **Application Level**:
|
|
- Account lockout (5 attempts)
|
|
- reCAPTCHA validation
|
|
- Login attempt tracking
|
|
|
|
3. **Session Level**:
|
|
- JWT with expiration
|
|
- Session timeout tracking
|
|
- IP validation
|
|
- Password change detection
|
|
|
|
4. **Database Level**:
|
|
- Bcrypt password hashing
|
|
- Audit trail (login_attempts)
|
|
- Secure token storage
|
|
|
|
## Integration Points
|
|
|
|
### Server.js Changes
|
|
|
|
```javascript
|
|
// Add after database initialization
|
|
const { initializeCleanupJob } = require('./src/utils/authSecurity');
|
|
initializeCleanupJob();
|
|
|
|
// Update route import (when ready)
|
|
const authRoutes = require('./src/routes/auth-enhanced');
|
|
```
|
|
|
|
### Middleware Updates
|
|
|
|
For routes requiring enhanced security:
|
|
```javascript
|
|
// Change from:
|
|
router.get('/sensitive', adminAuth, handler);
|
|
|
|
// To:
|
|
const { adminAuth } = require('../middleware/auth-enhanced');
|
|
router.get('/sensitive', adminAuth, handler);
|
|
```
|
|
|
|
### Frontend Integration
|
|
|
|
1. **Handle New Error Codes**:
|
|
```javascript
|
|
// Lockout error
|
|
if (error.response?.status === 423) {
|
|
const retryAfter = error.response.data.retryAfter;
|
|
showError(`Account locked. Try again in ${retryAfter} seconds`);
|
|
}
|
|
|
|
// Session expired
|
|
if (error.response?.data?.code === 'SESSION_TIMEOUT') {
|
|
redirectToLogin();
|
|
}
|
|
```
|
|
|
|
2. **Implement Logout**:
|
|
```javascript
|
|
async function logout() {
|
|
await api.post('/auth/logout');
|
|
clearToken();
|
|
redirectToLogin();
|
|
}
|
|
```
|
|
|
|
3. **Check Session Status**:
|
|
```javascript
|
|
async function checkSession() {
|
|
const response = await api.get('/auth/session');
|
|
if (!response.data.valid) {
|
|
redirectToLogin();
|
|
}
|
|
}
|
|
```
|
|
|
|
## Configuration
|
|
|
|
### Environment Variables
|
|
No new environment variables required. Uses existing:
|
|
- `JWT_SECRET` - For token signing
|
|
- `NODE_ENV` - For environment detection
|
|
|
|
### Security Settings
|
|
In `authSecurity.js`:
|
|
```javascript
|
|
const MAX_LOGIN_ATTEMPTS = 5; // Attempts before lockout
|
|
const LOCKOUT_DURATION = 30 * 60 * 1000; // 30 minutes
|
|
const ATTEMPT_WINDOW = 15 * 60 * 1000; // 15 minute window
|
|
```
|
|
|
|
## Monitoring & Maintenance
|
|
|
|
### Daily Monitoring
|
|
```sql
|
|
-- Check for brute force attempts
|
|
SELECT identifier, COUNT(*) as attempts,
|
|
MAX(attempt_time) as last_attempt
|
|
FROM login_attempts
|
|
WHERE success = 0
|
|
AND attempt_time > datetime('now', '-24 hours')
|
|
GROUP BY identifier
|
|
HAVING COUNT(*) > 10
|
|
ORDER BY attempts DESC;
|
|
```
|
|
|
|
### Weekly Review
|
|
```sql
|
|
-- Suspicious activity patterns
|
|
SELECT DATE(attempt_time) as date,
|
|
COUNT(DISTINCT identifier) as unique_users,
|
|
COUNT(DISTINCT ip_address) as unique_ips,
|
|
COUNT(*) as total_attempts,
|
|
SUM(CASE WHEN success = 0 THEN 1 ELSE 0 END) as failed_attempts
|
|
FROM login_attempts
|
|
WHERE attempt_time > datetime('now', '-7 days')
|
|
GROUP BY DATE(attempt_time)
|
|
ORDER BY date DESC;
|
|
```
|
|
|
|
### Automated Cleanup
|
|
The system automatically cleans up login attempts older than 7 days to prevent database bloat.
|
|
|
|
## Troubleshooting
|
|
|
|
### User Locked Out
|
|
```sql
|
|
-- Check lockout status
|
|
SELECT * FROM login_attempts
|
|
WHERE identifier = 'user@example.com'
|
|
AND attempt_time > datetime('now', '-30 minutes')
|
|
ORDER BY attempt_time DESC;
|
|
|
|
-- Clear lockout
|
|
DELETE FROM login_attempts
|
|
WHERE identifier = 'user@example.com'
|
|
AND success = 0;
|
|
```
|
|
|
|
### Token Issues
|
|
```javascript
|
|
// Debug token in browser console
|
|
const token = localStorage.getItem('token');
|
|
const decoded = JSON.parse(atob(token.split('.')[1]));
|
|
console.log('Token expires:', new Date(decoded.exp * 1000));
|
|
console.log('Token IP:', decoded.ip);
|
|
```
|
|
|
|
## Security Best Practices
|
|
|
|
1. **Monitor Failed Attempts**: Set up alerts for excessive failures
|
|
2. **Review IP Patterns**: Look for geographic anomalies
|
|
3. **Rotate JWT Secret**: Periodically update in production
|
|
4. **Update Dependencies**: Keep auth libraries current
|
|
5. **Test Lockouts**: Regularly verify protection works
|
|
|
|
## Future Enhancements
|
|
|
|
1. **Two-Factor Authentication**: Database columns already added
|
|
2. **IP Whitelist**: For admin accounts
|
|
3. **Device Fingerprinting**: Enhanced session security
|
|
4. **OAuth Integration**: Social login options
|
|
5. **WebAuthn/Passkeys**: Passwordless authentication |