Files
picpeak/backend/AUTH_SECURITY_INTEGRATION.md
T
paul e35ac6a41c
Test Gitea Actions / test (push) Successful in 20s
continuous-integration/drone/push Build is passing
feat: implement critical security fixes for SQL injection and authentication vulnerabilities
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>
2025-07-13 00:40:05 +02:00

4.8 KiB

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):

{
  "id": 1,
  "type": "admin",
  "exp": 1234567890
}

After (Enhanced JWT):

{
  "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

// 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:

// 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:
// 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();
}
  1. Implement Logout:
async function logout() {
  await api.post('/auth/logout');
  clearToken();
  redirectToLogin();
}
  1. Check Session Status:
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:

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

-- 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

-- 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

-- 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

// 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