Skip to content

Instantly share code, notes, and snippets.

@tientp-floware
Created December 22, 2022 10:30
Show Gist options
  • Save tientp-floware/58f129f0f0731044b8ae184f3f34d70c to your computer and use it in GitHub Desktop.
Save tientp-floware/58f129f0f0731044b8ae184f3f34d70c to your computer and use it in GitHub Desktop.
Title google document
<html><head></head><body>
<script>
var YOUR_CLIENT_ID = 'REPLACE_THIS_VALUE';
var YOUR_REDIRECT_URI = 'REPLACE_THIS_VALUE';
var fragmentString = location.hash.substring(1);
// Parse query string to see if page request is coming from OAuth 2.0 server.
var params = {};
var regex = /([^&=]+)=([^&]*)/g, m;
while (m = regex.exec(fragmentString)) {
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
if (Object.keys(params).length > 0) {
localStorage.setItem('oauth2-test-params', JSON.stringify(params) );
if (params['state'] && params['state'] == 'try_sample_request') {
trySampleRequest();
}
}
// If there's an access token, try an API request.
// Otherwise, start OAuth 2.0 flow.
function trySampleRequest() {
var params = JSON.parse(localStorage.getItem('oauth2-test-params'));
if (params && params['access_token']) {
var xhr = new XMLHttpRequest();
xhr.open('GET',
'https://www.googleapis.com/drive/v3/files/1-lPPef31mLaQJkFHXvbsd-PEWWKBtHFmGHznTBHfee0' +
'&access_token=' + params['access_token']);
xhr.onreadystatechange = function (e) {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.response);
} else if (xhr.readyState === 4 && xhr.status === 401) {
// Token invalid, so prompt for user permission.
oauth2SignIn();
}
};
xhr.send(null);
} else {
oauth2SignIn();
}
}
/*
* Create form to request access token from Google's OAuth 2.0 server.
*/
function oauth2SignIn() {
// Google's OAuth 2.0 endpoint for requesting an access token
var oauth2Endpoint = 'https://accounts.google.com/o/oauth2/v2/auth';
// Create element to open OAuth 2.0 endpoint in new window.
var form = document.createElement('form');
form.setAttribute('method', 'GET'); // Send as a GET request.
form.setAttribute('action', oauth2Endpoint);
// Parameters to pass to OAuth 2.0 endpoint.
var params = {'client_id': '1016512431780-3tv1uknfqhf3ukoue0bhuh69vbp1p2bg.apps.googleusercontent.com',
'redirect_uri': 'http://localhost:3003',
'scope': 'https://www.googleapis.com/auth/drive.metadata.readonly',
'state': 'try_sample_request',
'include_granted_scopes': 'true',
'response_type': 'token'}
// Add form parameters as hidden input values.
for (var p in params) {
var input = document.createElement('input');
input.setAttribute('type', 'hidden');
input.setAttribute('name', p);
input.setAttribute('value', params[p]);
form.appendChild(input);
}
// Add form to page and submit it to open the OAuth 2.0 endpoint.
document.body.appendChild(form);
form.submit();
}
</script>
<button onclick="trySampleRequest();">Try sample request</button>
</body></html>
@tientp-floware
Copy link
Author

// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

const {google} = require('googleapis');

/**
 * This example demonstrates authenticating to the Google APIs backend using
 * an access token only. Generally access tokens are obtained using the standard JWT
 * and 3-legged-OAuth methods, but from time to time only the access token
 * is available.
 */
async function runSample(accessToken) {
  const drive = google.drive({
    version: 'v2',
    // this header will be present for every request
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
  });

  // Make an authorized request to list Drive files.
  const res = await drive.files.list();
  console.log(res.data);

  return res;
}

if (module === require.main) {
  runSample().catch(console.error);
}

// Exports for unit testing purposes
module.exports = {runSample};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment