Skip to content

Instantly share code, notes, and snippets.

@cravindra
Last active November 7, 2017 11:59
Show Gist options
  • Save cravindra/eaecebc9672a5bbeb70048a8a3352096 to your computer and use it in GitHub Desktop.
Save cravindra/eaecebc9672a5bbeb70048a8a3352096 to your computer and use it in GitHub Desktop.
A wrapper which uses lasso-loader to enable google oauth flow asynchronously
const lassoLoader = require('lasso-loader');
/* globals gapi, _sdk */
/**
* Performs a one time OAuth 2.0 authorization.
* Depending on the parameters used, this will open a popup to the Google sign-in flow
* or try to load the requested response silently, without user interaction.
*/
function authenticate() {
return new Promise(function (resolve, reject) {
lassoLoader.load({
js: [
'https://apis.google.com/js/platform.js'
]
}, function () {
if (!gapi) {
let err = new Error('Google client is not instantiated');
err.message = 'session.googleAuthFailed';
return reject(err);
}
if (!(_sdk && _sdk.config && _sdk.config.oauth && _sdk.config.oauth.google)) {
let err = new Error('Global namespace _sdk is not instantiated');
_sdk.slError(err, 'warn');
err.message = 'error.general';
return reject(err);
}
gapi.load('auth2', function () {
/**
* This is an alternate way of logging the user in without using the usual Google Button Flow
* Reference:
* https://developers.google.com/identity/sign-in/web/reference#gapiauth2authorizeparams-callback
*/
gapi.auth2.authorize(_sdk.config.oauth.google,
function (response) {
if (response.error) {
// An error happened!
/*
* Handle error codes as given by google auth flow
* https://developers.google.com/identity/sign-in/web/reference#gapiauth2authorize-errorcodes
*/
let errorMap = {
/**
* Failed to initialize a required iframe from Google, for instance, due to an
* unsupported environment. A details property will give more information on the error
* raised.
*/
'idpiframe_initialization_failed': 'session.googleAuthFailed',
/**
* The user closed the popup before finishing the sign in flow.
*/
'popup_closed_by_user': 'session.popupClosed',
/**
* The user denied the permission to the scopes required.
*/
'access_denied': 'session.accessDenied',
/**
* No user could be automatically selected without prompting the consent flow. Error
* raised when using signIn with prompt: 'none' option.
* raised when using signIn with prompt: 'none' option.
*/
'immediate_failed': 'session.googleAuthFailed'
};
return reject(new Error(errorMap[response.error] || 'session.loginFailure'));
}
resolve({
//The provider name is google in this case
provider: 'google',
// The user authorized the application for the scopes requested.
token: response.id_token
});
});
});
});
});
}
module.exports = {
authenticate
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment