This repository has been archived by the owner on Dec 1, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
google.js
98 lines (79 loc) · 2.64 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
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const config = require('../lib/config');
const canonicalized = require('../lib/email').canonicalized;
const CLIENT_ID = config.get('google.clientId');
const CLIENT_SECRET = config.get('google.clientSecret');
const REDIRECT_URI = config.get('server.publicUrl') + '/authenticate/verify';
const OPENID_REALM = config.get('server.openidRealm');
const SCOPE = 'openid email';
// declared a var so that it can be overridden for testing.
var googleapis = require('googleapis');
function setClientCredentialsFromCode (oauthClient, code, callback) {
oauthClient.getToken(code, function (error, credentials) {
if (error) {
return callback(error);
}
oauthClient.setCredentials(credentials);
callback(null);
});
}
function getUserInfo (oauthClient, callback) {
if (!oauthClient.credentials) {
return callback(new Error('missing Google OAuth client credentials'));
}
var userInfo = googleapis.oauth2('v2').userinfo;
userInfo.get({ auth: oauthClient }, callback);
}
function getVerifiedEmail (oauthClient, callback) {
getUserInfo(oauthClient, function (error, userInfo) {
if (error) {
return callback(error);
}
/*jshint camelcase: false*/
callback(null, userInfo.verified_email && userInfo.email);
});
}
function createClient() {
return new googleapis.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);
}
module.exports = {
getAuthUrl: function (email, state, callback) {
/*jshint camelcase: false*/
var options = {
login_hint: canonicalized(email),
access_type: 'online',
scope: SCOPE,
state: state,
'openid.realm': OPENID_REALM
};
var authUrl = createClient().generateAuthUrl(options);
callback(null, authUrl);
},
tradeCodeForEmail: function (code, callback) {
// `credentials` is modified for each transaction, meaning
// every verification needs its own client.
var oauthClient = createClient();
setClientCredentialsFromCode(oauthClient, code, function (error) {
if (error) {
return callback(error);
}
getVerifiedEmail(oauthClient, function (error, verifiedEmail) {
if (error) {
return callback(error);
}
if (!verifiedEmail) {
return callback(new Error('Could not get email'));
}
callback(null, {
email: verifiedEmail
});
});
});
},
// used for testing
setGoogleApis: function (_googleapis) {
googleapis = _googleapis;
}
};