Last active
September 16, 2016 12:41
-
-
Save janis-kra/82795b30cd74b58ad50d8c13dbf52bca to your computer and use it in GitHub Desktop.
Extending Oracle JET with Google Sign-In — how to do it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<button id="google-signin-button" | |
data-bind="ojComponent: { | |
component:'ojButton', label: 'Sign In', | |
icons: {start:'oj-fwk-icon oj-fwk-icon-signin'}, | |
chroming: 'full' | |
}"> | |
</button> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// in one of your ViewModels | |
require(['https://apis.google.com/js/platform.js'], function () { | |
self.googleapi = window.gapi; // just in case the api is needed anywhere else in our code, e.g. for a logout function | |
self.googleapi.load('auth2', function (auth2) { | |
// Retrieve the singleton for the GoogleAuth library and set up the client. | |
auth2 = self.googleapi.auth2.init({ | |
client_id: 'YOUR_TOKEN_HERE.apps.' + | |
'googleusercontent.com', | |
cookiepolicy: 'single_host_origin' | |
}); | |
auth2.attachClickHandler( | |
$('#google-signin-button')[0], // attach the handler to this button | |
{}, | |
function (googleUser) { | |
var profile = googleUser.getBasicProfile(); | |
var token = googleUser.getAuthResponse().id_token; | |
var name = profile.getName(); | |
// safe the user data to your ViewModel's variables: | |
self.username(name); | |
self.token(token); | |
// log into your backend webservice: | |
login(token).then(updateUiOnLogin); | |
alert('Welcome, ' + self.username() + '!'); | |
}, | |
function () { | |
console.error('Error, try again'); | |
} | |
); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This attaches the correct click handler to the button programmatically, so no references are leaked to the window object. As the button is defined as an
ojButton
component, it is styled as all the other buttons in your application. And more importantly, Requirejs is used for loading the script.Note: The correct way to load the Google signin API would be to add an entry to your bower.json, copy it into your libs directory via Grunt and then finally load it in the define call of the corresponding ViewModel. This was left out here, to make the example as concise as possible.