Authorizing Google Apps Script to access Drive files - google-apps-script

The code below works fine for getting my own Google+ user attributes:
// Google oAuth
function getAuth(service, scopes) {
var oAuthConfig = UrlFetchApp.addOAuthService(service);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken? scope="+scopes);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey("anonymous");
oAuthConfig.setConsumerSecret("anonymous");
return {oAuthServiceName:service, oAuthUseToken:"always"};
}
function test_API_Key() {
var gPlusAuth = getAuth("plus", "https://www.googleapis.com/auth/plus.me");
var url = "https://www.googleapis.com/plus/v1/people/me?key=" + API_KEY;
var httpResponse = UrlFetchApp.fetch(url, gPlusAuth);
Logger.log(httpResponse);
}
When I use the same approach for accessing metadata about files on my Google Drive, I run into the HTTP error, 403, and "access not configured." Below is the code. What am I doing wrong?
function getFileMetaData(fileId) {
var driveAuth = getAuth("drive", "https://www.googleapis.com/auth/drive");
var url = "https://www.googleapis.com/drive/v2/files/" +
documentID + "?key=" + API_KEY;
var response = UrlFetchApp.fetch(url, driveAuth);
Logger.log(response);
}

Taken from google developer site[1]
At a high-level, all apps follow the same basic authorization pattern:
Register the application in the Google Developers Console.
Request that the user grant access to data in their Google account.
If the user consents, your application requests and receives credentials to access the Drive API.
Refresh the credentials (if necessary).
<script type="text/javascript">
var CLIENT_ID = '<YOUR_CLIENT_ID>';
var SCOPES = [
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
// Add other scopes needed by your application.
];
[1] https://developers.google.com/drive/web/about-auth

Related

Error: Access not granted or expired. when accessing Google Admin Directory API via service account and domain wide delegation

I am developing a google Apps script which lists all google groups. The App is published with Execute the app ass user accessing the web app and Who has access to the app -> Anyone in specific Domain. I am using a service account and Domain Wide Delegation to impersonate a Gsuite admin account in order to access the API.
function getDomWideDelegationService(serviceName) {
const scope = "https://www.googleapis.com/auth/admin.directory.group";
const email = 'gsuiteAdmin#mydomain.com';
var props = PropertiesService.getScriptProperties();
const keyfromstore = props.getProperty("SERVICE_ACCOUNT_KEY");
const serviceaccount = props.getProperty("SERVICEACCOUNT");
return OAuth2.createService(serviceName + email)
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(keyfromstore)
.setIssuer(serviceaccount)
.setSubject(email)
.setPropertyStore(PropertiesService.getScriptProperties())
.setScope(scope);
}
and this is the part where I access the google api:
function listUsersGroups(user){
const adminMail =
PropertiesService.getScriptProperties().getProperty("ADMIN_EMAIL");
var service = getDomWideDelegationService('listGroup:',
'https://www.googleapis.com/auth/admin.directory.group',adminMail);
const token = service.getAccessToken();
var requestBody = {};
requestBody.headers = {'Authorization': 'Bearer ' +
service.getAccessToken()};
requestBody.method = "GET";
requestBody.muteHttpExceptions = false;
var url = 'https://www.googleapis.com/admin/directory/v1/groups/?
userKey='+user;
var listGroupResponse = UrlFetchApp.fetch(url, requestBody);
var statusCode = listGroupResponse.getResponseCode();
var contentText = listGroupResponse.getContentText();
var contentObj = JSON.parse(contentText);
if(statusCode == 200)
console.log(`listing groups was successful`);
else
console.error(`listing group was NOT successful with error:
${contentText}`);
if(contentObj.hasOwnProperty("groups"))
return contentObj.groups;
else
return [];
}
However I always get:
Error: Access not granted or expired.
I double checked following:
Are the credentials of the service account correct?
Is the gsuiteAdmin#mydomain.com a Gsuite Admin?
Is the scope https://www.googleapis.com/auth/admin.directory.group added in the GSuite for the service account? (Security->API Controls->Domain Wide Delegation)
Is the scope added to the Google Appscript Porject?
Is the Google Admin Directory API added to the Advanced Google Services of the Apps Script Project?
Is the Google Admin Directory API added to the GCP Project?
I have no idea what else I could check...

Is it possible to access a deployed Protected Google Web App via URL without logging in from browser each time?

I've deployed a protected web app, and I'd like to trigger it without logging in each time:
I'd like to access the web app URL without logging in:
Based on this document, it's not possible without logging in from browser:
https://github.com/tanaikech/taking-advantage-of-Web-Apps-with-google-apps-script/blob/master/README.md
If the script of Web Apps uses some scopes, client users have to
authorize the scopes by own browser.
I'm assuming scopes means the web app is protected.
I've tried this: https://github.com/gsuitedevs/apps-script-oauth2/blob/master/samples/GoogleServiceAccount.gs but it asks for "request access"
If I click on request access, then it shows me this:
At this point, I'm thinking it's not possible to setup a service account with scope to trigger a protected deployed web app without authenticating through a browser each time. Can anyone confirm this?
My assumption is that the web app scope is https://www.googleapis.com/auth/drive since it has access to all drive's files.
Update: (What I tried but didn't work)
I matched the scope from the script:
To the service account:
The blurred area above is the client id i got from:
I've generated the access token using this script:
function accessTokens(){
var private_key = "-----BEGIN PRIVATE KEY-----*****\n-----END PRIVATE KEY-----\n"; // private_key of JSON file retrieved by creating Service Account
var client_email = "****#****.iam.gserviceaccount.com"; // client_email of JSON file retrieved by creating Service Account
var scopes = ["https://www.googleapis.com/auth/documents","https://www.googleapis.com/auth/forms","https://www.googleapis.com/auth/script.external_request","https://www.googleapis.com/auth/spreadsheets","https://www.googleapis.com/auth/userinfo.email"]; // Scopes
var url = "https://www.googleapis.com/oauth2/v3/token";
var header = {
alg: "RS256",
typ: "JWT",
};
var now = Math.floor(Date.now() / 1000);
var claim = {
iss: client_email,
scope: scopes.join(" "),
aud: url,
exp: (now + 3600).toString(),
iat: now.toString(),
};
var signature = Utilities.base64Encode(JSON.stringify(header)) + "." + Utilities.base64Encode(JSON.stringify(claim));
var jwt = signature + "." + Utilities.base64Encode(Utilities.computeRsaSha256Signature(signature, private_key));
var params = {
method: "post",
payload: {
assertion: jwt,
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
},
};
var res = UrlFetchApp.fetch(url, params).getContentText();
Logger.log(res);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
sheet.getRange(1, 3).setValue(JSON.parse(res)['access_token']);
}
And still has the same error, it asks for request access.
After a couple days into this, I've figured it out (with help of course).
Get the scope from your deployed web app script: File > Project Properties > Scopes
Add the scope along with https://www.googleapis.com/auth/drive in page Manage API client access https://admin.google.com/AdminHome?chromeless=1#OGX:ManageOauthClients (use comma delimited to add multiple scopes: http...,http..., etc.)
For the client name, get the client id from the service account page in your admin console: https://console.developers.google.com
Deploy your script Publish > Deploy as Web App
After generating access token(instruction below), append the access token with your deployed web app url &access_token=YOURTOKENHERE
Use this script with a google sheet, it will generate the access_token in cell A1 of Sheet1 (Replace the 4 variables with the info relevant to you):
function accessTokens(){
var private_key = "-----BEGIN PRIVATE KEY-----n-----END PRIVATE KEY-----\n"; // private_key of JSON file retrieved by creating Service Account
var client_email = "*****#****.iam.gserviceaccount.com"; // client_email of JSON file retrieved by creating Service Account
var scopes = ["https://www.googleapis.com/auth/documents","https://www.googleapis.com/auth/forms","https://www.googleapis.com/auth/script.external_request","https://www.googleapis.com/auth/spreadsheets","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/drive"]; // Scopes
var impersonate_email = "" //impersonate email
var url = "https://www.googleapis.com/oauth2/v4/token";
var header = {
alg: "RS256",
typ: "JWT",
};
var now = Math.floor(Date.now() / 1000);
var claim = {
iss: client_email,
sub: impersonate_email,
scope: scopes.join(" "),
aud: url,
exp: (now + 3600).toString(),
iat: now.toString(),
};
var signature = Utilities.base64Encode(JSON.stringify(header)) + "." + Utilities.base64Encode(JSON.stringify(claim));
var jwt = signature + "." + Utilities.base64Encode(Utilities.computeRsaSha256Signature(signature, private_key));
var params = {
method: "post",
payload: {
assertion: jwt,
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
},
};
var res = UrlFetchApp.fetch(url, params).getContentText();
Logger.log(res);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
sheet.getRange(1, 1).setValue(JSON.parse(res)['access_token']);
}

Google Apps Script Wants Unrestricted Scope

Simple function here in Google Apps Script:
function driveSearch() {
// Log the name of every file in the user's Drive whose visibility is anyonewithLink or anyonecanfind
var files = DriveApp.searchFiles(
'visibility = "anyoneWithLink" or visibility = "anyoneCanFind"');
while (files.hasNext()) {
var file = files.next();
var owner = file.getOwner().getName();
var sa = file.getSharingAccess();
Logger.log(file.getName());
Logger.log('Owner:'+owner);
Logger.log("SharingAccess:"+sa);
}
}
It want to find shared files in my gsuite drive.
However, it says I don't have permissions to run DriveApp
My permissions are set and requested correctly, like so:
{
"timeZone": "America/New_York",
"dependencies": {
},
"exceptionLogging": "STACKDRIVER",
"oauthScopes": [
"https://www.googleapis.com/auth/drive.readonly",
"https://www.googleapis.com/auth/drive.metadata.readonly"
]
}
The error is
You do not have permission to call DriveApp.searchFiles. Required permissions: https://www.googleapis.com/auth/drive (line 3, file "Code")
Why does searchFiles require delete permissions? I am very worried about inadvertent deletion, I don't want the full scope. Is there something else I'm doing wrong?
Lastly, yes my Gsuite allows Google Apps Script.
How about this workaround? In this workaround, the endpoint of Drive API is directly requested by UrlFetchApp, and the following 2 scopes are used.
https://www.googleapis.com/auth/drive.metadata.readonly
This is used to the access token which is used for using Drive API.
https://www.googleapis.com/auth/script.external_request
This is used for using UrlFetchApp.
Enable Drive API at API console
Before you use this script, please enable Drive API as follows.
On script editor
Resources -> Cloud Platform project
View API console
At Getting started, click "Explore and enable APIs".
At left side, click Library.
At "Search for APIs & services", input "Drive". And click Drive API.
Click Enable button.
If API has already been enabled, please don't turn off.
Sample script:
function myFunction() {
var baseUrl = "https://www.googleapis.com/drive/v3/files";
var q = 'visibility = "anyoneWithLink" or visibility = "anyoneCanFind"';
var fields = "files(id,name,owners,permissions),nextPageToken";
var pageToken = "";
var results = [];
var params = {headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}};
do {
var endpoint = baseUrl + "?pageSize=1000&q=" + encodeURIComponent(q) + "&fields=" + encodeURIComponent(fields) + "&pageToken=" + pageToken;
var res = UrlFetchApp.fetch(endpoint, params);
res = JSON.parse(res.getContentText());
Array.prototype.push.apply(results, res.files);
pageToken = res.nextPageToken || "";
} while (pageToken);
results.forEach(function(e) {
Logger.log(e.name);
Logger.log('Owner: ' + e.owners.map(function(f) {return f.displayName}).join(","));
Logger.log("SharingAccess: " + e.permissions.map(function(f) {return f.id}).join(","));
});
}
Note:
In this sample script, the log is the same with your script.
References:
Drive API
list
UrlFetchApp
If this was not the result you want, I apologize.

Retrieve photo from Google Apps Profile API

I am trying to retrieve Google Apps Profile API photo using Google Apps Profile API but It keeps on prompting to authorize the request even after authorizing it.
Here is the code which I have tried so far.
function getPhoto(userName){
userName = 'user#myDomain.com'; //will be replaced by actual username
var scope = 'https://www.google.com/m8/feeds/profiles';
var fetchArgs = googleOAuth_('Profile', scope);
fetchArgs.method = 'GET';
var domain = UserManager.getDomain();
var url = 'https://www.google.com/m8/feeds/photos/profile/'+domain+'/'+userName+'?v=3';
var rawData = UrlFetchApp.fetch(url, fetchArgs).getContentText();
Logger.log(rawData);
}
//google oAuth
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey("anonymous");
oAuthConfig.setConsumerSecret("anonymous");
return {oAuthServiceName:name, oAuthUseToken:"always"};
}
Refernces :
https://developers.google.com/google-apps/profiles/#photo_management
https://developers.google.com/google-apps/profiles/auth
Note : I have super administrator access to the domain I am trying
You could try with
var scope = 'https://www.google.com/m8/feeds/';
to authorize.
You can take a look at this Library. It lets you get the profile picture as a blob without any issue:
https://sites.google.com/site/scriptsexamples/new-connectors-to-google-services/profiles-services

Transfer ownership of a file to another user in Google Apps Script

I have created a little upload UI which I include in a Google Sites page. It let's a user upload a document. Since the script is published it runs under my account and the uploaded file is uploaded to my google drive. I can from apps script add the person that uploaded the file as an editor, but what I would like to do is make them the owner of a file. (from apps script you can do a .getOwner() on a file... but not a .setOwner() ..... does anyone know a workaround?
Unfortunately changing the owner of a file isn't supported in Apps Script. Issue 74 is a feature request to add this ability, and if you star the issue you'll show your support for the feature and get notified of updates.
------EDITED------
Now there is a handy method called setOwner, which can be found here: https://developers.google.com/apps-script/reference/drive/file#setOwner(User)
There's also the possibility to pass the new owner's email address instead of the User object, which is even more handy in some cases:
https://developers.google.com/apps-script/reference/drive/file#setOwner(String)
Updated 12 Sep 2016:
This code uses a service account that's been granted Google Apps Domain-Wide Delegation of Authority. This lets you change the owner of any file owned by any user on the domain. This code uses the Google apps-script-oauth2 library by Eric Koleda.
var PRIVATE_KEY = PropertiesService.getScriptProperties().getProperty('PRIVATE_KEY');
var CLIENT_EMAIL = PropertiesService.getScriptProperties().getProperty('CLIENT_EMAIL');
/**
* Transfers ownership of a file or folder to another account on the domain.
*
* #param {String} fileId The id of the file or folder
* #param {String} ownerEmail The email address of the new owner.
*/
function transferOwnership(fileId, ownerEmail) {
var file = DriveApp.getFileById(fileId);
var currentOwnerEmail = file.getOwner().getEmail(); //the user that we need to impersonate
var service = getService(currentOwnerEmail);
if (service.hasAccess()) {
var url = 'https://www.googleapis.com/drive/v2/files/' + fileId + '/permissions';
var payload = {value: ownerEmail,
type: 'user',
role: 'owner'};
var options = {method: "post",
contentType: "application/json",
headers : {
Authorization: 'Bearer ' + service.getAccessToken()
},
payload: JSON.stringify(payload)//,
,muteHttpExceptions: true
};
//debugger;
//throw 'test my errors';
var response = UrlFetchApp.fetch(url, options);
if (response.getResponseCode() === 200 ||
(response.getResponseCode() === 400 && response.getContentText().indexOf('were successfully shared'))
) {
return response.getContentText();
}
if (response.getResponseCode() === 401 && response.getContentText().indexOf('Invalid Credentials')) {
throw 'Unable to transfer ownership from owner ' + currentOwnerEmail + ' ... ' +
'Please make sure the file\'s owner has a Google Apps license (and not a Google Apps Vault - Former Employee license) and try again.';
}
throw response.getContentText();
} else {
throw service.getLastError();
}
}
/**
* Reset the authorization state, so that it can be re-tested.
*/
function reset() {
var service = getService();
service.reset();
}
/**
* Configures the service.
*/
function getService(userEmail) {
return OAuth2.createService('GoogleDrive:' + userEmail)
// Set the endpoint URL.
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
// Set the private key and issuer.
.setPrivateKey(PRIVATE_KEY)
.setIssuer(CLIENT_EMAIL)
// Set the name of the user to impersonate. This will only work for
// Google Apps for Work/EDU accounts whose admin has setup domain-wide
// delegation:
// https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
.setSubject(userEmail)
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getScriptProperties())
// Set the scope. This must match one of the scopes configured during the
// setup of domain-wide delegation.
.setScope('https://www.googleapis.com/auth/drive');
}
Old answer (obsolete now as the Document List API is deprecated):
You can achieve this in Google Apps Script by accessing the Document List API using the raw atom xml protocol. You need to be a super admin of the domain. Here's an example that works for me:
/**
* Change Owner of a file or folder
* Run this as admin and authorise first in the script editor.
*/
function changeOwner(newOwnerEmail, fileOrFolderId){
var file = DocsList.getFileById(fileOrFolderId);
var oldOwnerEmail = file.getOwner().getEmail();
if (oldOwnerEmail === newOwnerEmail) {
return;
}
file.removeEditor(newOwnerEmail);
var base = 'https://docs.google.com/feeds/';
var fetchArgs = googleOAuth_('docs', base);
fetchArgs.method = 'POST';
var rawXml = "<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gAcl='http://schemas.google.com/acl/2007'>"
+"<category scheme='http://schemas.google.com/g/2005#kind' "
+"term='http://schemas.google.com/acl/2007#accessRule'/>"
+"<gAcl:role value='owner'/>"
+"<gAcl:scope type='user' value='"+newOwnerEmail+"'/>"
+"</entry>";
fetchArgs.payload = rawXml;
fetchArgs.contentType = 'application/atom+xml';
var url = base + encodeURIComponent(oldOwnerEmail) + '/private/full/'+fileOrFolderId+'/acl?v=3&alt=json';
var content = UrlFetchApp.fetch(url, fetchArgs).getContentText();
}
//Google oAuth
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey("anonymous");
oAuthConfig.setConsumerSecret("anonymous");
return {oAuthServiceName:name, oAuthUseToken:"always"};
}
Try this out! (at least it worked for me)
var newFolder = DriveApp.createFolder(folderName).addEditor(ownerEmail).setOwner(ownerEmail).addEditor(group.getEmail()).removeEditor(Session.getActiveUser().getEmail());
The above creates a folder and adds a new editor, sets the new editor to be the owner, adds another group to the editors and finally removes the user who has just created the folder from the editors.
I figured out a work-around -- not sure if it's exactly what you all are looking for. Simply give access to the account you'd like to switch ownership to. Access the document/form/etc. from that account and then make a copy of the said document. You are now the owner. You'll have to re-invite others.