/
google.js
69 lines (57 loc) · 2 KB
/
google.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
'use strict';
var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
module.exports = function (app, db) {
var User = db.model('user');
var googleConfig = app.getValue('env').GOOGLE;
var googleCredentials = {
clientID: googleConfig.clientID,
clientSecret: googleConfig.clientSecret,
callbackURL: googleConfig.callbackURL
};
var verifyCallback = function (accessToken, refreshToken, profile, done) {
//get user's first name via google oauth
let name = profile.displayName
let info = {
firstName: name.split(' ')[0],
lastName: name.split(' ').slice(1).join(' '),
email: profile.emails[0].value
};
User.findOne({
where: {
google_id: profile.id
}
})
.then(function (user) {
if (user) {
return user;
} else {
return User.create({
google_id: profile.id,
firstName: info.firstName,
lastName: info.lastName,
email: info.email
});
}
})
.then(function (userToLogin) {
done(null, userToLogin);
})
.catch(function (err) {
console.error('Error creating user from Google authentication', err);
done(err);
});
};
passport.use(new GoogleStrategy(googleCredentials, verifyCallback));
app.get('/auth/google', passport.authenticate('google', {
scope: [
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email'
]
}));
app.get('/auth/google/callback',
passport.authenticate('google', {failureRedirect: '/login'}),
function (req, res) {
res.redirect('/');
});
};