Files
spotlightcam/backend/src/app.js

56 lines
1.4 KiB
JavaScript
Raw Normal View History

const express = require('express');
const cors = require('cors');
const app = express();
// Middleware
app.use(cors({
origin: process.env.CORS_ORIGIN || 'http://localhost:8080',
credentials: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Request logging middleware
app.use((req, res, next) => {
console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
next();
});
// Health check endpoint
app.get('/api/health', (req, res) => {
res.status(200).json({
status: 'ok',
message: 'Backend is running',
timestamp: new Date().toISOString(),
environment: process.env.NODE_ENV || 'development'
});
});
// API routes
feat: add JWT authentication with complete test coverage Phase 1 - Step 3: Authentication API **Backend Authentication:** - bcryptjs for password hashing (salt rounds: 10) - JWT tokens with 24h expiration - Secure password storage (never expose passwordHash) **API Endpoints:** - POST /api/auth/register - User registration - Username validation (3-50 chars, alphanumeric + underscore) - Email validation and normalization - Password validation (min 6 chars) - Duplicate email/username detection - Auto-generated avatar (ui-avatars.com) - POST /api/auth/login - User authentication - Email + password credentials - Returns JWT token + user data - Invalid credentials protection - GET /api/users/me - Get current user (protected) - Requires valid JWT token - Returns user data + stats (matches, ratings) - Token validation via middleware **Security Features:** - express-validator for input sanitization - Auth middleware for protected routes - Token verification (Bearer token) - Password never returned in responses - Proper error messages (no information leakage) **Frontend Integration:** - API service layer (frontend/src/services/api.js) - Updated AuthContext to use real API - Token storage in localStorage - Automatic token inclusion in requests - Error handling for expired/invalid tokens **Unit Tests (30 tests, 78.26% coverage):** Auth Endpoints (14 tests): - ✅ Register: success, duplicate email, duplicate username - ✅ Register validation: invalid email, short password, short username - ✅ Login: success, wrong password, non-existent user, invalid format - ✅ Protected route: valid token, no token, invalid token, malformed header Auth Utils (9 tests): - ✅ Password hashing and comparison - ✅ Different hashes for same password - ✅ JWT generation and verification - ✅ Token expiration validation - ✅ Invalid token handling All tests passing ✅ Coverage: 78.26% ✅
2025-11-12 22:16:14 +01:00
app.use('/api/auth', require('./routes/auth'));
app.use('/api/users', require('./routes/users'));
app.use('/api/events', require('./routes/events'));
app.use('/api/wsdc', require('./routes/wsdc'));
// app.use('/api/matches', require('./routes/matches'));
// app.use('/api/ratings', require('./routes/ratings'));
// 404 handler
app.use((req, res) => {
res.status(404).json({
error: 'Not Found',
message: `Cannot ${req.method} ${req.path}`
});
});
// Error handler
app.use((err, req, res, next) => {
console.error('Error:', err);
res.status(err.status || 500).json({
error: err.message || 'Internal Server Error',
...(process.env.NODE_ENV === 'development' && { stack: err.stack })
});
});
module.exports = app;