Skip to content

Instantly share code, notes, and snippets.

@Spencer-Easton
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Spencer-Easton/76632ea8658030530187 to your computer and use it in GitHub Desktop.
Save Spencer-Easton/76632ea8658030530187 to your computer and use it in GitHub Desktop.
Duel Auth for a script
var localAuth = false;
var sProps = PropertiesService.getScriptProperties();
function doGet() {
var driveService = getDriveService();
if (!driveService.hasAccess()) {
return showAuth();
}
return HtmlService.createHtmlOutput(makeRequest());
}
function getDriveService() {
return OAuth2.createService('drive')
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setClientId(sProps.getProperty("clientId"))
.setClientSecret(sProps.getProperty("clientSecret"))
.setProjectKey('...')
.setCallbackFunction('authCallback')
.setPropertyStore(sProps)
.setScope('https://www.googleapis.com/auth/drive')
.setParam('access_type', 'offline')
.setParam('approval_prompt', 'force');
}
function showAuth() {
var driveService = getDriveService();
if (!driveService.hasAccess()) {
var authorizationUrl = driveService.getAuthorizationUrl();
var template = HtmlService.createTemplate(
'<a href="<?= authorizationUrl ?>" target="_blank">Authorize</a>. ' +
'Reopen the sidebar when the authorization is complete.');
template.authorizationUrl = authorizationUrl;
var page = template.evaluate();
return page;
} else {
HtmlService.createHtmlOutput("Already have auth");
}
}
function authCallback(request) {
var driveService = getDriveService();
var isAuthorized = driveService.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this tab.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this tab');
}
}
function makeRequest() {
var driveService = getDriveService();
var response = UrlFetchApp.fetch('https://www.googleapis.com/drive/v2/files?maxResults=10', {
headers: {
Authorization: 'Bearer ' + driveService.getAccessToken()
}
});
return response.getContentText();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment