-
Notifications
You must be signed in to change notification settings - Fork 150
/
auth.js
207 lines (187 loc) · 6.3 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
const User = require('../models/user');
const Blog = require('../models/blog');
const shortId = require('shortid');
const jwt = require('jsonwebtoken');
const expressJwt = require('express-jwt');
const { errorHandler } = require('../helpers/dbErrorHandler');
const _ = require('lodash');
// sendgrid
const sgMail = require('@sendgrid/mail'); // SENDGRID_API_KEY
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
exports.signup = (req, res) => {
// console.log(req.body);
User.findOne({ email: req.body.email }).exec((err, user) => {
if (user) {
return res.status(400).json({
error: 'Email is taken'
});
}
const { name, email, password } = req.body;
let username = shortId.generate();
let profile = `${process.env.CLIENT_URL}/profile/${username}`;
let newUser = new User({ name, email, password, profile, username });
newUser.save((err, success) => {
if (err) {
return res.status(400).json({
error: err
});
}
// res.json({
// user: success
// });
res.json({
message: 'Signup success! Please signin.'
});
});
});
};
exports.signin = (req, res) => {
const { email, password } = req.body;
// check if user exist
User.findOne({ email }).exec((err, user) => {
if (err || !user) {
return res.status(400).json({
error: 'User with that email does not exist. Please signup.'
});
}
// authenticate
if (!user.authenticate(password)) {
return res.status(400).json({
error: 'Email and password do not match.'
});
}
// generate a token and send to client
const token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET, { expiresIn: '1d' });
res.cookie('token', token, { expiresIn: '1d' });
const { _id, username, name, email, role } = user;
return res.json({
token,
user: { _id, username, name, email, role }
});
});
};
exports.signout = (req, res) => {
res.clearCookie('token');
res.json({
message: 'Signout success'
});
};
exports.requireSignin = expressJwt({
secret: process.env.JWT_SECRET // req.user
});
exports.authMiddleware = (req, res, next) => {
const authUserId = req.user._id;
User.findById({ _id: authUserId }).exec((err, user) => {
if (err || !user) {
return res.status(400).json({
error: 'User not found'
});
}
req.profile = user;
next();
});
};
exports.adminMiddleware = (req, res, next) => {
const adminUserId = req.user._id;
User.findById({ _id: adminUserId }).exec((err, user) => {
if (err || !user) {
return res.status(400).json({
error: 'User not found'
});
}
if (user.role !== 1) {
return res.status(400).json({
error: 'Admin resource. Access denied'
});
}
req.profile = user;
next();
});
};
exports.canUpdateDeleteBlog = (req, res, next) => {
const slug = req.params.slug.toLowerCase();
Blog.findOne({ slug }).exec((err, data) => {
if (err) {
return res.status(400).json({
error: errorHandler(err)
});
}
let authorizedUser = data.postedBy._id.toString() === req.profile._id.toString();
if (!authorizedUser) {
return res.status(400).json({
error: 'You are not authorized'
});
}
next();
});
};
exports.forgotPassword = (req, res) => {
const { email } = req.body;
User.findOne({ email }, (err, user) => {
if (err || !user) {
return res.status(401).json({
error: 'User with that email does not exist'
});
}
const token = jwt.sign({ _id: user._id }, process.env.JWT_RESET_PASSWORD, { expiresIn: '10m' });
// email
const emailData = {
from: process.env.EMAIL_FROM,
to: email,
subject: `Password reset link`,
html: `
<p>Please use the following link to reset your password:</p>
<p>${process.env.CLIENT_URL}/auth/password/reset/${token}</p>
<hr />
<p>This email may contain sensetive information</p>
<p>https://seoblog.com</p>
`
};
// populating the db > user > resetPasswordLink
return user.updateOne({ resetPasswordLink: token }, (err, success) => {
if (err) {
return res.json({ error: errorHandler(err) });
} else {
sgMail.send(emailData).then(sent => {
return res.json({
message: `Email has been sent to ${email}. Follow the instructions to reset your password. Link expires in 10min.`
});
});
}
});
});
};
exports.resetPassword = (req, res) => {
const { resetPasswordLink, newPassword } = req.body;
if (resetPasswordLink) {
jwt.verify(resetPasswordLink, process.env.JWT_RESET_PASSWORD, function(err, decoded) {
if (err) {
return res.status(401).json({
error: 'Expired link. Try again'
});
}
User.findOne({ resetPasswordLink }, (err, user) => {
if (err || !user) {
return res.status(401).json({
error: 'Something went wrong. Try later'
});
}
const updatedFields = {
password: newPassword,
resetPasswordLink: ''
};
user = _.extend(user, updatedFields);
user.save((err, result) => {
if (err) {
return res.status(400).json({
error: errorHandler(err)
});
}
res.json({
message: `Great! Now you can login with your new password`
});
});
});
});
}
};