-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
google_server.js
214 lines (193 loc) · 5.53 KB
/
google_server.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
import Google from './namespace.js';
import { Accounts } from 'meteor/accounts-base';
import { fetch } from 'meteor/fetch';
const hasOwn = Object.prototype.hasOwnProperty;
// https://developers.google.com/accounts/docs/OAuth2Login#userinfocall
Google.whitelistedFields = [
'id',
'email',
'verified_email',
'name',
'given_name',
'family_name',
'picture',
'locale',
'timezone',
'gender',
];
const getServiceDataFromTokens = async (tokens, callback) => {
const { accessToken, idToken } = tokens;
const scopes = await getScopes(accessToken).catch((err) => {
const error = Object.assign(
new Error(`Failed to fetch tokeninfo from Google. ${err.message}`),
{ response: err.response }
);
callback && callback(error);
throw error;
});
let identity = await getIdentity(accessToken).catch((err) => {
const error = Object.assign(
new Error(`Failed to fetch identity from Google. ${err.message}`),
{ response: err.response }
);
callback && callback(error);
throw error;
});
const serviceData = {
accessToken,
idToken,
scope: scopes,
};
if (hasOwn.call(tokens, 'expiresIn')) {
serviceData.expiresAt = Date.now() + 1000 * parseInt(tokens.expiresIn, 10);
}
const fields = Object.create(null);
Google.whitelistedFields.forEach(function (name) {
if (hasOwn.call(identity, name)) {
fields[name] = identity[name];
}
});
Object.assign(serviceData, fields);
// only set the token in serviceData if it's there. this ensures
// that we don't lose old ones (since we only get this on the first
// log in attempt)
if (tokens.refreshToken) {
serviceData.refreshToken = tokens.refreshToken;
}
const returnValue = {
serviceData,
options: {
profile: {
name: identity.name,
},
},
};
callback && callback(undefined, returnValue);
return returnValue;
};
Accounts.registerLoginHandler(async (request) => {
if (request.googleSignIn !== true) {
return;
}
const tokens = {
accessToken: request.accessToken,
refreshToken: request.refreshToken,
idToken: request.idToken,
};
if (request.serverAuthCode) {
Object.assign(
tokens,
await getTokens({
code: request.serverAuthCode,
})
);
}
let result;
try {
result = await getServiceDataFromTokens(tokens);
} catch (err) {
throw Object.assign(
new Error(
`Failed to complete OAuth handshake with Google. ${err.message}`
),
{ response: err.response }
);
}
return Accounts.updateOrCreateUserFromExternalService(
'google',
{
id: request.userId,
idToken: request.idToken,
accessToken: request.accessToken,
email: request.email,
picture: request.imageUrl,
...result.serviceData,
},
result.options
);
});
// returns an object containing:
// - accessToken
// - expiresIn: lifetime of token in seconds
// - refreshToken, if this is the first authorization request
const getTokens = async (query, callback) => {
const config = ServiceConfiguration.configurations.findOne({
service: 'google',
});
if (!config) throw new ServiceConfiguration.ConfigError();
const content = new URLSearchParams({
code: query.code,
client_id: config.clientId,
client_secret: OAuth.openSecret(config.secret),
redirect_uri: OAuth._redirectUri('google', config),
grant_type: 'authorization_code',
});
const request = await fetch('https://accounts.google.com/o/oauth2/token', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: content,
});
const response = await request.json();
if (response.error) {
// if the http response was a json object with an error attribute
callback && callback(response.error);
throw new Meteor.Error(
`Failed to complete OAuth handshake with Google. ${response.error}`
);
} else {
const data = {
accessToken: response.access_token,
refreshToken: response.refresh_token,
expiresIn: response.expires_in,
idToken: response.id_token,
};
callback && callback(undefined, data);
return data;
}
};
const getServiceData = async (query) =>
getServiceDataFromTokens(await getTokens(query));
OAuth.registerService('google', 2, null, getServiceData);
const getIdentity = async (accessToken, callback) => {
const content = new URLSearchParams({ access_token: accessToken });
let response;
try {
const request = await fetch(
`https://www.googleapis.com/oauth2/v1/userinfo?${content.toString()}`,
{
method: 'GET',
headers: { Accept: 'application/json' },
}
);
response = await request.json();
} catch (e) {
callback && callback(e);
throw new Meteor.Error(e.reason);
}
callback && callback(undefined, response);
return response;
};
const getScopes = async (accessToken, callback) => {
const content = new URLSearchParams({ access_token: accessToken });
let response;
try {
const request = await fetch(
`https://www.googleapis.com/oauth2/v1/tokeninfo?${content.toString()}`,
{
method: 'GET',
headers: { Accept: 'application/json' },
}
);
response = await request.json();
} catch (e) {
callback && callback(e);
throw new Meteor.Error(e.reason);
}
callback && callback(undefined, response.scope.split(' '));
return response.scope.split(' ');
};
Google.retrieveCredential = (credentialToken, credentialSecret) =>
OAuth.retrieveCredential(credentialToken, credentialSecret);