const express = require('express'); const bcrypt = require('bcryptjs'); const jwt = require('jwt-simple'); const User = require('../models/User'); require('dotenv').config(); const router = express.Router(); const secret = process.env.JWT_SECRET; // Register new user router.post('/register', async (req, res) => { const { email, password } = req.body; try { const user = await User.findOne({ email }); if (user) return res.status(400).json({ msg: 'User already exists' }); const newUser = new User({ email, password }); const salt = await bcrypt.genSalt(10); newUser.password = await bcrypt.hash(password, salt); await newUser.save(); const payload = { id: newUser.id }; const token = jwt.encode(payload, secret); res.json({ token }); } catch (err) { console.error(err.message); res.status(500).send('Server error'); } }); // Login user router.post('/login', async (req, res) => { const { email, password } = req.body; try { const user = await User.findOne({ email }); if (!user) return res.status(400).json({ msg: 'Invalid credentials' }); const isMatch = await bcrypt.compare(password, user.password); if (!isMatch) return res.status(400).json({ msg: 'Invalid credentials' }); const payload = { id: user.id }; const token = jwt.encode(payload, secret); res.json({ token }); } catch (err) { console.error(err.message); res.status(500).send('Server error'); } }); module.exports = router;