|
| 1 | +// The client ID is obtained from the {{ Google Cloud Console }} |
| 2 | +// at {{ https://cloud.google.com/console }}. |
| 3 | +// If you run this code from a server other than http://localhost, |
| 4 | +// you need to register your own client ID. |
| 5 | +var OAUTH2_CLIENT_ID = '__YOUR_CLIENT_ID__'; |
| 6 | +var OAUTH2_SCOPES = [ |
| 7 | + 'https://www.googleapis.com/auth/youtube' |
| 8 | +]; |
| 9 | + |
| 10 | +// Upon loading, the Google APIs JS client automatically invokes this callback. |
| 11 | +googleApiClientReady = function() { |
| 12 | + gapi.auth.init(function() { |
| 13 | + window.setTimeout(checkAuth, 1); |
| 14 | + }); |
| 15 | +} |
| 16 | + |
| 17 | +// Attempt the immediate OAuth 2.0 client flow as soon as the page loads. |
| 18 | +// If the currently logged-in Google Account has previously authorized |
| 19 | +// the client specified as the OAUTH2_CLIENT_ID, then the authorization |
| 20 | +// succeeds with no user intervention. Otherwise, it fails and the |
| 21 | +// user interface that prompts for authorization needs to display. |
| 22 | +function checkAuth() { |
| 23 | + gapi.auth.authorize({ |
| 24 | + client_id: OAUTH2_CLIENT_ID, |
| 25 | + scope: OAUTH2_SCOPES, |
| 26 | + immediate: true |
| 27 | + }, handleAuthResult); |
| 28 | +} |
| 29 | + |
| 30 | +// Handle the result of a gapi.auth.authorize() call. |
| 31 | +function handleAuthResult(authResult) { |
| 32 | + if (authResult) { |
| 33 | + // Authorization was successful. Hide authorization prompts and show |
| 34 | + // content that should be visible after authorization succeeds. |
| 35 | + $('.pre-auth').hide(); |
| 36 | + $('.post-auth').show(); |
| 37 | + loadAPIClientInterfaces(); |
| 38 | + } else { |
| 39 | + // Make the #login-link clickable. Attempt a non-immediate OAuth 2.0 |
| 40 | + // client flow. The current function is called when that flow completes. |
| 41 | + $('#login-link').click(function() { |
| 42 | + gapi.auth.authorize({ |
| 43 | + client_id: OAUTH2_CLIENT_ID, |
| 44 | + scope: OAUTH2_SCOPES, |
| 45 | + immediate: false |
| 46 | + }, handleAuthResult); |
| 47 | + }); |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +// Load the client interfaces for the YouTube Analytics and Data APIs, which |
| 52 | +// are required to use the Google APIs JS client. More info is available at |
| 53 | +// http://code.google.com/p/google-api-javascript-client/wiki/GettingStarted#Loading_the_Client |
| 54 | +function loadAPIClientInterfaces() { |
| 55 | + gapi.client.load('youtube', 'v3', function() { |
| 56 | + handleAPILoaded(); |
| 57 | + }); |
| 58 | +} |
0 commit comments