-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCreateUser.js
86 lines (78 loc) · 2.13 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
78
79
80
81
82
83
84
85
86
const express = require("express");
const router = express.Router();
const User = require("../models/User");
const { body, validationResult } = require("express-validator");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const jwtSecret = "iammuqadas$#";
router.post(
"/createuser",
[
body("email").isEmail(),
body("name").isLength({ min: 5 }),
body("password", "Please put 5 character").isLength({ min: 4 }),
],
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(),
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 coreect email" });
}
const pwdCompare = await bcrypt.compare(
req.body.password,
userData.password
);
if (!pwdCompare) {
return res
.status(400)
.json({ errors: "try logging with coreect email" });
}
const data = {
user: {
id: userData.id,
},
};
const authToken = jwt.sign(data, jwtSecret);
return res.json({ success: true, authToken: authToken });
//return res.json({suceess:true})
} catch (error) {
console.log(error);
res.json({ success: false });
}
}
);
module.exports = router;