-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.js
60 lines (49 loc) · 2.02 KB
/
user.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const express = require("express");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const User = require("../models/users");
const { body, validationResult } = require('express-validator');
const router = express.Router();
// Register a new user
router.post("/register", [
body('email').isEmail().withMessage('Please provide a valid email'),
body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters long'),
], async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
try {
const { name, email, password } = req.body;
// Check if the user already exists
const existingUser = await User.findOne({ email });
if (existingUser) return res.status(400).json({ message: "User already exists" });
// Hash the password
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);
// Create a new user
const newUser = new User({ name, email, password: hashedPassword });
await newUser.save();
res.status(201).json({ message: "User registered successfully" });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Login a user
router.post("/login", async (req, res) => {
try {
const { email, password } = req.body;
// Find the user
const user = await User.findOne({ email });
if (!user) return res.status(404).json({ message: "User not found" });
// Compare passwords
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return res.status(400).json({ message: "Invalid credentials" });
// Generate a token
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: "1h" });
res.json({ token, user: { id: user._id, name: user.name, email: user.email } });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
module.exports = router;