-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
80 lines (74 loc) · 1.93 KB
/
auth.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const express = require("express");
const router = express.Router();
const auth = require("../../middleware/auth");
const User = require("../../models/User");
const jwt = require("jsonwebtoken");
const config = require("config");
const bcrypt = require("bcryptjs");
const { check, validationResult } = require("express-validator/check");
//@route GET api/auth
//@desc Get user by token
//@access Private
router.get("/", auth, async (req, res) => {
try{
const user = await User.findById(req.user.id).select('-password');
res.json(user);
}
catch(err){
console.error(err);
res.status(500).send("server error");
}
});
// @route POST api/auth
// @desc Auth user and get token (login)
// @access Public
router.post(
"/",
[
check("email", "Please include a valid email").isEmail(),
check(
"password",
"Password is required"
).exists()
],
async (req, res) => {
console.log(req.body);
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { email, password } = req.body;
try {
let user = await User.findOne({ email });
if (!user) {
return res
.status(400)
.json({ errors: [{ msg: "Invalid credentials" }] });
}
const isMatch = await bcrypt.compare(password, user.password);
if(!isMatch){
return res
.status(400)
.json({ errors: [{ msg: "Invalid credentials" }] });
}
const paylod = {
user: {
id: user.id, //mongoose changes _id on mongoDb to id
},
};
jwt.sign(
paylod,
config.get("jwtSecret"),
{ expiresIn: 360000 },
(err, token) => {
if (err) throw err;
res.json({ token });
}
);
} catch (err) {
console.error(err.message);
res.status(500).send("Server error");
}
}
);
module.exports = router;