const express = require('express'); const http = require('http'); const socketIo = require('socket.io'); const mongoose = require('mongoose'); const cors = require('cors'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const path = require('path'); require('dotenv').config(); const app = express(); const server = http.createServer(app); // Fix CORS configuration const io = socketIo(server, { cors: { origin: "http://localhost:3000", methods: ["GET", "POST", "PUT", "DELETE"], credentials: false } }); // CORS middleware - fix this part app.use(cors({ origin: "http://localhost:3000", credentials: false, methods: ["GET", "POST", "PUT", "DELETE"], allowedHeaders: ["Content-Type", "Authorization"] })); app.use(express.json()); app.use('/uploads', express.static(path.join(__dirname, 'uploads'))); // Simple User Model (in-memory for now) const users = []; // Auth Routes app.post('/api/auth/register', async (req, res) => { try { const { username, email, password, displayName } = req.body; console.log('Registration attempt:', { username, email, displayName }); // Validation if (!username || !email || !password || !displayName) { return res.status(400).json({ error: 'All fields are required' }); } // Check if user exists const existingUser = users.find(u => u.email === email || u.username === username); if (existingUser) { return res.status(400).json({ error: 'User already exists' }); } // Hash password const hashedPassword = await bcrypt.hash(password, 12); // Create user const user = { id: Date.now().toString(), username, email, displayName, password: hashedPassword, avatar: null, status: 'online', lastSeen: new Date(), createdAt: new Date() }; users.push(user); // Generate token const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET || 'fallback-secret', { expiresIn: '30d' }); // Remove password from response const { password: _, ...userWithoutPassword } = user; console.log('User registered successfully:', userWithoutPassword.username); res.status(201).json({ message: 'User registered successfully', user: userWithoutPassword, token }); } catch (error) { console.error('Registration error:', error); res.status(500).json({ error: 'Server error during registration' }); } }); app.post('/api/auth/login', async (req, res) => { try { const { email, password } = req.body; console.log('Login attempt:', { email }); if (!email || !password) { return res.status(400).json({ error: 'Email and password are required' }); } // Find user const user = users.find(u => u.email === email); if (!user) { return res.status(401).json({ error: 'Invalid credentials' }); } // Check password const isPasswordValid = await bcrypt.compare(password, user.password); if (!isPasswordValid) { return res.status(401).json({ error: 'Invalid credentials' }); } // Update user status user.status = 'online'; user.lastSeen = new Date(); // Generate token const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET || 'fallback-secret', { expiresIn: '30d' }); // Remove password from response const { password: _, ...userWithoutPassword } = user; console.log('User logged in:', userWithoutPassword.username); res.json({ message: 'Login successful', user: userWithoutPassword, token }); } catch (error) { console.error('Login error:', error); res.status(500).json({ error: 'Server error during login' }); } }); app.get('/api/auth/me', (req, res) => { const token = req.headers.authorization?.split(' ')[1]; if (!token) { return res.status(401).json({ error: 'No token provided' }); } try { const decoded = jwt.verify(token, process.env.JWT_SECRET || 'fallback-secret'); const user = users.find(u => u.id === decoded.userId); if (!user) { return res.status(404).json({ error: 'User not found' }); } const { password: _, ...userWithoutPassword } = user; res.json({ user: userWithoutPassword }); } catch (error) { res.status(401).json({ error: 'Invalid token' }); } }); // Health check app.get('/api/health', (req, res) => { res.json({ status: 'OK', message: 'YSNRFD Messenger Backend is running!', usersCount: users.length, timestamp: new Date().toISOString() }); }); // Test route to verify CORS is working app.get('/api/test-cors', (req, res) => { res.json({ message: 'CORS is working!', corsConfig: { origin: 'http://localhost:3000', credentials: false } }); }); // Socket.io connection io.on('connection', (socket) => { console.log('User connected:', socket.id); socket.on('disconnect', () => { console.log('User disconnected:', socket.id); }); }); const PORT = process.env.PORT || 5000; server.listen(PORT, () => { console.log(`🚀 YSNRFD Messenger backend running on port ${PORT}`); console.log(`🔧 Environment: ${process.env.NODE_ENV || 'development'}`); console.log(`🌍 Frontend URL: http://localhost:3000`); console.log(`🔍 Health check: http://localhost:${PORT}/api/health`); console.log(`🔍 CORS test: http://localhost:${PORT}/api/test-cors`); console.log(`👥 Registered users: ${users.length}`); });