-
Notifications
You must be signed in to change notification settings - Fork 0
/
CreateUser.js
77 lines (63 loc) · 2.35 KB
/
CreateUser.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
const express = require('express')
const router = express.Router()
const User = require("../models/User")
const { body, validationResult } = require('express-validator');
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const jwtSecret = "jhiudbfkjdpj820280983097kangt@#%"
router.post("/createuser", [
body('email').isEmail(),
// password must be at least 5 chars long
body('password', 'Incorrect Password').isLength({ min: 5 })]
, async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const salt = await bcrypt.genSalt(10);
let secPassword = await bcrypt.hash(req.body.password, salt)
try {
await User.create({
name: req.body.name,
password: secPassword,
email: req.body.email,
location: req.body.location
})
res.json({ success: true });
} catch (error) {
console.log(error);
res.json({ success: false });
}
})
router.post("/loginuser", [
body('email').isEmail(),
// password must be at least 5 chars long
body('password', 'Incorrect Password').isLength({ min: 5 })],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
let email = req.body.email;
try {
let userData = await User.findOne({ email });
if (!userData) {
return res.status(400).json({ errors: "Try logging with correct credentials" })
}
const pwd = await bcrypt.compare(req.body.password,userData.password) //comparing the body password and the user password
if (!pwd) {
return res.status(400).json({ errors: "Try logging with correct credentials" })
}
const data = {
user:{
id:userData.id
}
}
const authToken = jwt.sign(data,jwtSecret);
return res.json({ success: true,authToken:authToken });
} catch (error) {
console.log(error);
res.json({ success: false });
}
})
module.exports = router;