-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.js
586 lines (540 loc) · 19.8 KB
/
user.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
var async = require('async');
var crypto = require('crypto');
var nodemailer = require('nodemailer');
var jwt = require('jsonwebtoken');
var moment = require('moment');
var request = require('request');
var qs = require('querystring');
var User = require('../models/User');
function generateToken(user) {
var payload = {
iss: 'my.domain.com',
sub: user.id,
iat: moment().unix(),
exp: moment().add(7, 'days').unix()
};
return jwt.sign(payload, "875916b9aa8591781khiladi287df573c07ed56ecc697ebb88b744329af117468be5953");
}
/**
* Login required middleware
*/
exports.ensureAuthenticated = function(req, res, next) {
if (req.isAuthenticated()) {
next();
} else {
res.status(401).send({ msg: 'Unauthorized' });
}
};
/**
* POST /login
* Sign in with email and password
*/
exports.loginPost = function(req, res, next) {
req.assert('email', 'Email is not valid').isEmail();
req.assert('email', 'Email cannot be blank').notEmpty();
req.assert('password', 'Password cannot be blank').notEmpty();
req.sanitize('email').normalizeEmail({ remove_dots: false });
var errors = req.validationErrors();
if (errors) {
return res.status(400).send(errors);
}
User.findOne({ email: req.body.email }, function(err, user) {
if (!user) {
return res.status(401).send({ msg: 'The email address ' + req.body.email + ' is not associated with any account. ' +
'Double-check your email address and try again.'
});
}
user.comparePassword(req.body.password, function(err, isMatch) {
if (!isMatch) {
return res.status(401).send({ msg: 'Invalid email or password' });
}
res.send({ token: generateToken(user), user: user.toJSON() });
});
});
};
/**
* POST /signup
*/
exports.signupPost = function(req, res, next) {
req.assert('name', 'Name cannot be blank').notEmpty();
req.assert('email', 'Email is not valid').isEmail();
req.assert('email', 'Email cannot be blank').notEmpty();
req.assert('password', 'Password must be at least 4 characters long').len(4);
req.sanitize('email').normalizeEmail({ remove_dots: false });
var errors = req.validationErrors();
if (errors) {
return res.status(400).send(errors);
}
User.findOne({ email: req.body.email }, function(err, user) {
if (user) {
return res.status(400).send({ msg: 'The email address you have entered is already associated with another account.' });
}
user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password
});
user.save(function(err) {
res.send({ token: generateToken(user), user: user });
});
});
};
/**
* PUT /account
* Update profile information OR change password.
*/
exports.accountPut = function(req, res, next) {
if ('password' in req.body) {
req.assert('password', 'Password must be at least 4 characters long').len(4);
req.assert('confirm', 'Passwords must match').equals(req.body.password);
} else {
req.assert('email', 'Email is not valid').isEmail();
req.assert('email', 'Email cannot be blank').notEmpty();
req.sanitize('email').normalizeEmail({ remove_dots: false });
}
var errors = req.validationErrors();
if (errors) {
return res.status(400).send(errors);
}
User.findById(req.user.id, function(err, user) {
if ('password' in req.body) {
user.password = req.body.password;
} else {
user.email = req.body.email;
user.name = req.body.name;
user.gender = req.body.gender;
user.location = req.body.location;
user.website = req.body.website;
}
user.save(function(err) {
if ('password' in req.body) {
res.send({ msg: 'Your password has been changed.' });
} else if (err && err.code === 11000) {
res.status(409).send({ msg: 'The email address you have entered is already associated with another account.' });
} else {
res.send({ user: user, msg: 'Your profile information has been updated.' });
}
});
});
};
/**
* DELETE /account
*/
exports.accountDelete = function(req, res, next) {
User.remove({ _id: req.user.id }, function(err) {
res.send({ msg: 'Your account has been permanently deleted.' });
});
};
/**
* GET /unlink/:provider
*/
exports.unlink = function(req, res, next) {
User.findById(req.user.id, function(err, user) {
switch (req.params.provider) {
case 'facebook':
user.facebook = undefined;
break;
case 'google':
user.google = undefined;
break;
case 'twitter':
user.twitter = undefined;
break;
case 'vk':
user.vk = undefined;
break;
case 'github':
user.github = undefined;
break;
default:
return res.status(400).send({ msg: 'Invalid OAuth Provider' });
}
user.save(function(err) {
res.send({ msg: 'Your account has been unlinked.' });
});
});
};
/**
* POST /forgot
*/
exports.forgotPost = function(req, res, next) {
req.assert('email', 'Email is not valid').isEmail();
req.assert('email', 'Email cannot be blank').notEmpty();
req.sanitize('email').normalizeEmail({ remove_dots: false });
var errors = req.validationErrors();
if (errors) {
return res.status(400).send(errors);
}
async.waterfall([
function(done) {
crypto.randomBytes(16, function(err, buf) {
var token = buf.toString('hex');
done(err, token);
});
},
function(token, done) {
User.findOne({ email: req.body.email }, function(err, user) {
if (!user) {
return res.status(400).send({ msg: 'The email address ' + req.body.email + ' is not associated with any account.' });
}
user.passwordResetToken = token;
user.passwordResetExpires = Date.now() + 3600000; // expire in 1 hour
user.save(function(err) {
done(err, token, user);
});
});
},
function(token, user, done) {
var transporter = nodemailer.createTransport({
service: 'Mailgun',
auth: {
user: "postmaster@sandbox67c118365e564798a8864434e4b2a3cb.mailgun.org",
pass: "ed49d942fd9e6c11208ee3aacb29df9d"
}
});
var mailOptions = {
to: user.email,
from: 'support@vmrworld.com',
subject: '✔ Reset your password on skillsMeterified',
text: 'You are receiving this email because you (or someone else) have requested the reset of the password for your account.\n\n' +
'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
'http://' + req.headers.host + '/reset/' + token + '\n\n' +
'If you did not request this, please ignore this email and your password will remain unchanged.\n'
};
transporter.sendMail(mailOptions, function(err) {
res.send({ msg: 'An email has been sent to ' + user.email + ' with further instructions.' });
done(err);
});
}
]);
};
/**
* POST /reset
*/
exports.resetPost = function(req, res, next) {
req.assert('password', 'Password must be at least 4 characters long').len(4);
req.assert('confirm', 'Passwords must match').equals(req.body.password);
var errors = req.validationErrors();
if (errors) {
return res.status(400).send(errors);
}
async.waterfall([
function(done) {
User.findOne({ passwordResetToken: req.params.token })
.where('passwordResetExpires').gt(Date.now())
.exec(function(err, user) {
if (!user) {
return res.status(400).send({ msg: 'Password reset token is invalid or has expired.' });
}
user.password = req.body.password;
user.passwordResetToken = undefined;
user.passwordResetExpires = undefined;
user.save(function(err) {
done(err, user);
});
});
},
function(user, done) {
var transporter = nodemailer.createTransport({
service: 'Mailgun',
auth: {
user: "postmaster@sandbox67c118365e564798a8864434e4b2a3cb.mailgun.org",
pass: "ed49d942fd9e6c11208ee3aacb29df9d"
}
});
var mailOptions = {
from: 'support@vmrworld.com',
to: user.email,
subject: 'Your skillsMeterified password has been changed',
text: 'Hello,\n\n' +
'This is a confirmation that the password for your account ' + user.email + ' has just been changed.\n'
};
transporter.sendMail(mailOptions, function(err) {
res.send({ msg: 'Your password has been changed successfully.' });
});
}
]);
};
/**
* POST /auth/facebook
* Sign in with Facebook
*/
exports.authFacebook = function(req, res) {
var profileFields = ['id', 'name', 'email', 'gender', 'location'];
var accessTokenUrl = 'https://graph.facebook.com/v2.5/oauth/access_token';
var graphApiUrl = 'https://graph.facebook.com/v2.5/me?fields=' + profileFields.join(',');
var params = {
code: req.body.code,
client_id: req.body.clientId,
client_secret: "79be066f46a83c27e54491a67478ec85",
redirect_uri: req.body.redirectUri
};
// Step 1. Exchange authorization code for access token.
request.get({ url: accessTokenUrl, qs: params, json: true }, function(err, response, accessToken) {
if (accessToken.error) {
return res.status(500).send({ msg: accessToken.error.message });
}
// Step 2. Retrieve user's profile information.
request.get({ url: graphApiUrl, qs: accessToken, json: true }, function(err, response, profile) {
if (profile.error) {
return res.status(500).send({ msg: profile.error.message });
}
// Step 3a. Link accounts if user is authenticated.
if (req.isAuthenticated()) {
User.findOne({ facebook: profile.id }, function(err, user) {
if (user) {
return res.status(409).send({ msg: 'There is already an existing account linked with Facebook that belongs to you.' });
}
user = req.user;
user.name = user.name || profile.name;
user.gender = user.gender || profile.gender;
user.picture = user.picture || 'https://graph.facebook.com/' + profile.id + '/picture?type=large';
user.facebook = profile.id;
user.save(function() {
res.send({ token: generateToken(user), user: user });
});
});
} else {
// Step 3b. Create a new user account or return an existing one.
User.findOne({ facebook: profile.id }, function(err, user) {
if (user) {
return res.send({ token: generateToken(user), user: user });
}
User.findOne({ email: profile.email }, function(err, user) {
if (user) {
return res.status(400).send({ msg: user.email + ' is already associated with another account.' })
}
user = new User({
name: profile.name,
email: profile.email,
gender: profile.gender,
location: profile.location && profile.location.name,
picture: 'https://graph.facebook.com/' + profile.id + '/picture?type=large',
facebook: profile.id
});
user.save(function(err) {
return res.send({ token: generateToken(user), user: user });
});
});
});
}
});
});
};
exports.authFacebookCallback = function(req, res) {
res.send('Loading...');
};
/**
* POST /auth/google
* Sign in with Google
*/
exports.authGoogle = function(req, res) {
var accessTokenUrl = 'https://accounts.google.com/o/oauth2/token';
var peopleApiUrl = 'https://www.googleapis.com/plus/v1/people/me/openIdConnect';
var params = {
code: req.body.code,
client_id: req.body.clientId,
client_secret: "WebcjZnXZDcjqu-CZxWORUWZ",
redirect_uri: req.body.redirectUri,
grant_type: 'authorization_code'
};
// Step 1. Exchange authorization code for access token.
request.post(accessTokenUrl, { json: true, form: params }, function(err, response, token) {
var accessToken = token.access_token;
var headers = { Authorization: 'Bearer ' + accessToken };
// Step 2. Retrieve user's profile information.
request.get({ url: peopleApiUrl, headers: headers, json: true }, function(err, response, profile) {
if (profile.error) {
return res.status(500).send({ message: profile.error.message });
}
// Step 3a. Link accounts if user is authenticated.
if (req.isAuthenticated()) {
User.findOne({ google: profile.sub }, function(err, user) {
if (user) {
return res.status(409).send({ msg: 'There is already an existing account linked with Google that belongs to you.' });
}
user = req.user;
user.name = user.name || profile.name;
user.gender = profile.gender;
user.picture = user.picture || profile.picture.replace('sz=50', 'sz=200');
user.location = user.location || profile.location;
user.google = profile.sub;
user.save(function() {
res.send({ token: generateToken(user), user: user });
});
});
} else {
// Step 3b. Create a new user account or return an existing one.
User.findOne({ google: profile.sub }, function(err, user) {
if (user) {
return res.send({ token: generateToken(user), user: user });
}
user = new User({
name: profile.name,
email: profile.email,
gender: profile.gender,
picture: profile.picture.replace('sz=50', 'sz=200'),
location: profile.location,
google: profile.sub
});
user.save(function(err) {
res.send({ token: generateToken(user), user: user });
});
});
}
});
});
};
exports.authGoogleCallback = function(req, res) {
res.send('Loading...');
};
/**
* POST /auth/twitter
* Sign in with Twitter
*/
exports.authTwitter = function(req, res) {
var requestTokenUrl = 'https://api.twitter.com/oauth/request_token';
var accessTokenUrl = 'https://api.twitter.com/oauth/access_token';
var profileUrl = 'https://api.twitter.com/1.1/users/show.json?screen_name=';
// Part 1 of 2: Initial POST request to obtain OAuth request token.
if (!req.body.oauth_token || !req.body.oauth_verifier) {
var requestTokenOauthSignature = {
consumer_key: process.env.TWITTER_KEY,
consumer_secret: process.env.TWITTER_SECRET,
callback: req.body.redirectUri
};
// Step 1. Obtain request token to initiate app authorization.
// At this point nothing is happening inside a popup yet.
request.post({ url: requestTokenUrl, oauth: requestTokenOauthSignature }, function(err, response, body) {
var oauthToken = qs.parse(body);
// Step 2. Send OAuth token back.
// After request token is sent back, a popup will redirect to the Twitter app authorization screen.
// Unlike Facebook and Google (OAuth 2.0), we have to do this extra step for Twitter (OAuth 1.0).
res.send(oauthToken);
});
} else {
// Part 2 of 2: Second POST request after "Authorize app" button is clicked.
// OAuth 2.0 basically starts from Part 2, but with OAuth 1.0 we need to do that extra step in Part 1.
var accessTokenOauth = {
consumer_key: process.env.TWITTER_KEY,
consumer_secret: process.env.TWITTER_SECRET,
token: req.body.oauth_token,
verifier: req.body.oauth_verifier
};
// Step 3. Exchange "oauth token" and "oauth verifier" for access token.
request.post({ url: accessTokenUrl, oauth: accessTokenOauth }, function(err, response, accessToken) {
accessToken = qs.parse(accessToken);
var profileOauth = {
consumer_key: process.env.TWITTER_KEY,
consumer_secret: process.env.TWITTER_SECRET,
oauth_token: accessToken.oauth_token
};
// Step 4. Retrieve user's profile information.
request.get({ url: profileUrl + accessToken.screen_name, oauth: profileOauth, json: true }, function(err, response, profile) {
// Step 5a. Link accounts if user is authenticated.
if (req.isAuthenticated()) {
User.findOne({ twitter: profile.id }, function(err, user) {
if (user) {
return res.status(409).send({ msg: 'There is already an existing account linked with Twitter that belongs to you.' });
}
user = req.user;
user.name = user.name || profile.name;
user.picture = user.picture || profile.profile_image_url_https;
user.location = user.location || profile.location;
user.twitter = profile.id;
user.save(function(err) {
res.send({ token: generateToken(user), user: user });
});
});
} else {
// Step 5b. Create a new user account or return an existing one.
User.findOne({ twitter: profile.id }, function(err, user) {
if (user) {
return res.send({ token: generateToken(user), user: user });
}
// Twitter does not provide an email address, but email is a required field in our User schema.
// We can "fake" a Twitter email address as follows: username@twitter.com.
user = new User({
name: profile.name,
email: profile.screen_name + '@twitter.com',
location: profile.location,
picture: profile.profile_image_url_https,
twitter: profile.id
});
user.save(function() {
res.send({ token: generateToken(user), user: user });
});
});
}
});
});
}
};
exports.authTwitterCallback = function(req, res) {
res.send('Loading...');
};
/**
* POST /auth/google
* Sign in with Github
*/
exports.authGithub = function(req, res) {
var accessTokenUrl = 'https://github.com/login/oauth/access_token';
var userUrl = 'https://api.github.com/user';
var params = {
code: req.body.code,
client_id: req.body.clientId,
client_secret: process.env.GITHUB_SECRET,
redirect_uri: req.body.redirectUri,
grant_type: 'authorization_code'
};
// Step 1. Exchange authorization code for access token.
request.post(accessTokenUrl, { json: true, form: params }, function(err, response, token) {
var accessToken = token.access_token;
var headers = {
Authorization: 'Bearer ' + accessToken,
'User-Agent': 'MegaBoilerplate'
};
// Step 2. Retrieve user's profile information.
request.get({ url: userUrl, headers: headers, json: true }, function(err, response, profile) {
if (profile.error) {
return res.status(500).send({ message: profile.error.message });
}
// Step 3a. Link accounts if user is authenticated.
if (req.isAuthenticated()) {
User.findOne({ github: profile.id }, function(err, user) {
if (user) {
return res.status(409).send({ msg: 'There is already an existing account linked with Github that belongs to you.' });
}
user = req.user;
user.name = user.name || profile.name;
user.picture = user.picture || profile.avatar_url;
user.location = user.location || profile.location;
user.github = profile.id;
user.save(function() {
res.send({ token: generateToken(user), user: user });
});
});
} else {
// Step 3b. Create a new user account or return an existing one.
User.findOne({ github: profile.id }, function(err, user) {
if (user) {
return res.send({ token: generateToken(user), user: user });
}
user = new User({
name: profile.name,
email: profile.email,
picture: profile.avatar_url,
location: profile.location,
github: profile.id
});
user.save(function(err) {
res.send({ token: generateToken(user), user: user });
});
});
}
});
});
};
exports.authGithubCallback = function(req, res) {
res.send('Loading...');
};