-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthController.js
More file actions
31 lines (26 loc) · 977 Bytes
/
Copy pathauthController.js
File metadata and controls
31 lines (26 loc) · 977 Bytes
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
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('./User');
const multer = require('multer');
const upload = multer();
router.post('/signup', upload.none(), async (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).send('Username and password are required');
}
const hashedPassword = await bcrypt.hash(password, 10);
const user = new User({ username, password: hashedPassword });
await user.save();
res.sendStatus(201);
});
router.post('/login', upload.none(), async (req, res) => {
const user = await User.findOne({ username: req.body.username });
if (!user || !await bcrypt.compare(req.body.password, user.password)) {
return res.sendStatus(401);
}
const token = jwt.sign({ _id: user._id }, process.env.SECRET_KEY);
res.send({ token });
});
module.exports = router;