| 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);
|
|
|
|
|
| const io = socketIo(server, {
|
| cors: {
|
| origin: "http://localhost:3000",
|
| methods: ["GET", "POST", "PUT", "DELETE"],
|
| credentials: false
|
| }
|
| });
|
|
|
|
|
| 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')));
|
|
|
|
|
| const users = [];
|
|
|
|
|
| app.post('/api/auth/register', async (req, res) => {
|
| try {
|
| const { username, email, password, displayName } = req.body;
|
|
|
| console.log('Registration attempt:', { username, email, displayName });
|
|
|
|
|
| if (!username || !email || !password || !displayName) {
|
| return res.status(400).json({ error: 'All fields are required' });
|
| }
|
|
|
|
|
| const existingUser = users.find(u => u.email === email || u.username === username);
|
| if (existingUser) {
|
| return res.status(400).json({ error: 'User already exists' });
|
| }
|
|
|
|
|
| const hashedPassword = await bcrypt.hash(password, 12);
|
|
|
|
|
| const user = {
|
| id: Date.now().toString(),
|
| username,
|
| email,
|
| displayName,
|
| password: hashedPassword,
|
| avatar: null,
|
| status: 'online',
|
| lastSeen: new Date(),
|
| createdAt: new Date()
|
| };
|
|
|
| users.push(user);
|
|
|
|
|
| const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET || 'fallback-secret', { expiresIn: '30d' });
|
|
|
|
|
| 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' });
|
| }
|
|
|
|
|
| const user = users.find(u => u.email === email);
|
| if (!user) {
|
| return res.status(401).json({ error: 'Invalid credentials' });
|
| }
|
|
|
|
|
| const isPasswordValid = await bcrypt.compare(password, user.password);
|
| if (!isPasswordValid) {
|
| return res.status(401).json({ error: 'Invalid credentials' });
|
| }
|
|
|
|
|
| user.status = 'online';
|
| user.lastSeen = new Date();
|
|
|
|
|
| const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET || 'fallback-secret', { expiresIn: '30d' });
|
|
|
|
|
| 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' });
|
| }
|
| });
|
|
|
|
|
| app.get('/api/health', (req, res) => {
|
| res.json({
|
| status: 'OK',
|
| message: 'YSNRFD Messenger Backend is running!',
|
| usersCount: users.length,
|
| timestamp: new Date().toISOString()
|
| });
|
| });
|
|
|
|
|
| app.get('/api/test-cors', (req, res) => {
|
| res.json({
|
| message: 'CORS is working!',
|
| corsConfig: {
|
| origin: 'http://localhost:3000',
|
| credentials: false
|
| }
|
| });
|
| });
|
|
|
|
|
| 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}`);
|
| }); |