|
|
@@ -0,0 +1,41 @@
|
|
|
+const express = require('express');
|
|
|
+const bcrypt = require('bcryptjs');
|
|
|
+const jwt = require('jsonwebtoken');
|
|
|
+const User = require('../models/User');
|
|
|
+const { body, validationResult } = require('express-validator');
|
|
|
+const router = express.Router();
|
|
|
+
|
|
|
+router.post('/register', [
|
|
|
+ body('username').notEmpty(),
|
|
|
+ body('email').isEmail(),
|
|
|
+ body('password').isLength({ min: 6 }),
|
|
|
+], async (req, res) => {
|
|
|
+ const errors = validationResult(req);
|
|
|
+ if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });
|
|
|
+
|
|
|
+ const { username, email, password } = req.body;
|
|
|
+ try {
|
|
|
+ const hashedPassword = await bcrypt.hash(password, 10);
|
|
|
+ const newUser = new User({ username, email, password: hashedPassword });
|
|
|
+ await newUser.save();
|
|
|
+ res.status(201).json({ message: 'User registered successfully' });
|
|
|
+ } catch (error) {
|
|
|
+ res.status(500).json({ error: 'Server error' });
|
|
|
+ }
|
|
|
+});
|
|
|
+
|
|
|
+router.post('/login', async (req, res) => {
|
|
|
+ const { email, password } = req.body;
|
|
|
+ try {
|
|
|
+ const user = await User.findOne({ email });
|
|
|
+ if (!user || !(await bcrypt.compare(password, user.password))) {
|
|
|
+ return res.status(400).json({ error: 'Invalid credentials' });
|
|
|
+ }
|
|
|
+ const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' });
|
|
|
+ res.json({ token });
|
|
|
+ } catch (error) {
|
|
|
+ res.status(500).json({ error: 'Server error' });
|
|
|
+ }
|
|
|
+});
|
|
|
+
|
|
|
+module.exports = router;
|