-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusers.js
89 lines (84 loc) · 2.54 KB
/
users.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
87
88
const User = require('../models/User');
const validateRegisterInput = require('../validation/register');
const gravatar = require('gravatar');
const bcrypt = require('bcryptjs');
const validateLoginInput = require('../validation/login');
const jwt = require('jsonwebtoken');
const keys = require('../config/keys');
exports.current = function (req, res) {
res.json({
id: req.user.id,
name: req.user.name,
email: req.user.email
});
};
exports.register = function (req, res) {
const { errors, isValid } = validateRegisterInput(req.body);
if (!isValid) {
return res.status(400).json(errors);
}
User.findOne({ email: req.body.email })
.then(user => {
if (user) {
errors.email = 'Email already exists';
return res.status(400).json(errors);
} else {
const avatar = gravatar.url(req.body.email, {
s: '200', // size
r: 'pg', // rating
d: 'mm' // default
});
const newUser = new User({
name: req.body.name,
email: req.body.email,
avatar,
password: req.body.password
});
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser.save()
.then(user => res.json(user))
.catch(err => console.log(err));
});
});
}
})
.catch(err => res.status(404).json(err.message));
};
exports.login = function (req, res) {
const { errors, isValid } = validateLoginInput(req.body);
if (!isValid) {
return res.status(400).json(errors);
}
const { email, password } = req.body;
User.findOne({ email })
.then(user => {
if (!user) {
errors.email = 'User not found';
return res.status(404).json(errors);
}
bcrypt.compare(password, user.password)
.then(isMatch => {
if (isMatch) {
// user passed, generate token
const payload = { id: user.id, name: user.name, avatar: user.avatar };
jwt.sign(
payload,
keys.JWT_SECRET,
{ expiresIn: 3600 },
(err, token) => {
res.json({
success: 'true',
token: 'Bearer ' + token
});
});
} else {
errors.password = 'Password incorrect';
return res.status(400).json(errors);
}
});
})
.catch(err => res.status(404).json(err.message));
};