2016-02-04 14:03:39 -05:00
|
|
|
// Helper functions for accessing the google API.
|
|
|
|
|
var https = require('https');
|
|
|
|
|
var Parse = require('parse/node').Parse;
|
|
|
|
|
|
2016-10-17 12:44:24 -04:00
|
|
|
function validateIdToken(id, token) {
|
|
|
|
|
return request("tokeninfo?id_token="+token)
|
|
|
|
|
.then((response) => {
|
2016-10-26 11:44:56 -04:00
|
|
|
if (response && (response.sub == id || response.user_id == id)) {
|
2016-10-17 12:44:24 -04:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
throw new Parse.Error(
|
|
|
|
|
Parse.Error.OBJECT_NOT_FOUND,
|
|
|
|
|
'Google auth is invalid for this user.');
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function validateAuthToken(id, token) {
|
|
|
|
|
return request("tokeninfo?access_token="+token)
|
2016-02-04 14:03:39 -05:00
|
|
|
.then((response) => {
|
2016-10-26 11:44:56 -04:00
|
|
|
if (response && (response.sub == id || response.user_id == id)) {
|
2016-02-04 14:03:39 -05:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
throw new Parse.Error(
|
|
|
|
|
Parse.Error.OBJECT_NOT_FOUND,
|
|
|
|
|
'Google auth is invalid for this user.');
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2016-10-17 12:44:24 -04:00
|
|
|
// Returns a promise that fulfills if this user id is valid.
|
|
|
|
|
function validateAuthData(authData) {
|
|
|
|
|
if (authData.id_token) {
|
|
|
|
|
return validateIdToken(authData.id, authData.id_token);
|
|
|
|
|
} else {
|
|
|
|
|
return validateAuthToken(authData.id, authData.access_token).then(() => {
|
|
|
|
|
// Validation with auth token worked
|
|
|
|
|
return;
|
|
|
|
|
}, () => {
|
|
|
|
|
// Try with the id_token param
|
|
|
|
|
return validateIdToken(authData.id, authData.access_token);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Returns a promise that fulfills if this app id is valid.
|
2016-02-04 14:03:39 -05:00
|
|
|
function validateAppId() {
|
|
|
|
|
return Promise.resolve();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// A promisey wrapper for api requests
|
|
|
|
|
function request(path) {
|
|
|
|
|
return new Promise(function(resolve, reject) {
|
2016-06-11 07:25:25 +08:00
|
|
|
https.get("https://www.googleapis.com/oauth2/v3/" + path, function(res) {
|
2016-02-04 14:03:39 -05:00
|
|
|
var data = '';
|
|
|
|
|
res.on('data', function(chunk) {
|
|
|
|
|
data += chunk;
|
|
|
|
|
});
|
|
|
|
|
res.on('end', function() {
|
|
|
|
|
data = JSON.parse(data);
|
|
|
|
|
resolve(data);
|
|
|
|
|
});
|
2016-11-24 15:47:41 -05:00
|
|
|
}).on('error', function() {
|
2016-02-04 14:03:39 -05:00
|
|
|
reject('Failed to validate this access token with Google.');
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
|
validateAppId: validateAppId,
|
|
|
|
|
validateAuthData: validateAuthData
|
|
|
|
|
};
|