-
Notifications
You must be signed in to change notification settings - Fork 30
/
google-api-methods.js
60 lines (52 loc) · 1.83 KB
/
google-api-methods.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
Meteor.methods({
// Obtain a new access token using the refresh token
exchangeRefreshToken: function(userId) {
this.unblock();
if (this.connection) { //when called from client
if (this.userId) {
userId = this.userId;
} else {
throw new Meteor.Error(403, "Must be signed in to use Google API.");
}
}
var user;
if (userId && Meteor.isServer) {
user = Meteor.users.findOne({_id: userId});
} else {
user = Meteor.user();
}
var config = Accounts.loginServiceConfiguration.findOne({service: "google"});
if (! config)
throw new Meteor.Error(500, "Google service not configured.");
if (! user.services || ! user.services.google || ! user.services.google.refreshToken)
throw new Meteor.Error(500, "Refresh token not found.");
try {
var result = HTTP.call("POST",
"https://accounts.google.com/o/oauth2/token",
{
params: {
'client_id': config.clientId,
'client_secret': config.secret,
'refresh_token': user.services.google.refreshToken,
'grant_type': 'refresh_token'
}
});
} catch (e) {
var code = e.response ? e.response.statusCode : 500;
throw new Meteor.Error(code, 'Unable to exchange google refresh token.', e.response)
}
if (result.statusCode === 200) {
// console.log('success');
// console.log(EJSON.stringify(result.data));
Meteor.users.update(user._id, {
'$set': {
'services.google.accessToken': result.data.access_token,
'services.google.expiresAt': (+new Date) + (1000 * result.data.expires_in),
}
});
return result.data;
} else {
throw new Meteor.Error(result.statusCode, 'Unable to exchange google refresh token.', result);
}
}
});