Reputation: 73
I am trying to delete some files from google drive folder using this script it keep saying my while i run this code
"Access denied: DriveApp. (line 20, file "Code")Dismiss"
I have read so much about it on internet and already tried every solution that i saw! i enabled the permission in the script editor and in the google APIs console developer. any idea? thank you very much guys
function DeleteOldFiles() {
var Folders = new Array(
'1RnA55YH_AyPzEVmkAXkaia2iuH17Kkdl'
);
var Files;
Logger.clear();
for each (var FolderID in Folders) {
Folder = DriveApp.getFolderById(FolderID)
Files = Folder.getFiles();
while (Files.hasNext()) {
var File = Files.next();
if (new Date() - File.getLastUpdated() > 1 * 1 * 10 * 10 * 1000) {
File.setTrashed(true); // Places the file int the Trash folder
//Drive.Files.remove(File.getId()); // Permanently deletes the file
Logger.log('File ' + File.getName() + ' was deleted.');
}
"Access denied: DriveApp. (line 20, file "Code")Dismiss"
but i enabled the access in the api console and through the script editor
Upvotes: 1
Views: 467
Reputation: 170
If the file which you are trying to delete is owned by someone who is in your domain, than you can delete it. You need to use a service account behind the user.
OAuth Service:
var JSON_user = {
"private_key": "your private key",
"client_email": "your client email"
};
function getOAuthService(userId) {
return OAuth2.createService("Service Account")
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(JSON_user.private_key)
.setIssuer(JSON_user.client_email)
.setSubject(userId)
.setPropertyStore(PropertiesService.getScriptProperties())
.setParam('access_type', 'offline')
.setScope('https://www.googleapis.com/auth/drive')
.setParam('approval_prompt', 'auto');
}
Now you can impersonate a user like this:
var service = getOAuthService("user email to impersonate");
Hope it helps.
Upvotes: 1
Reputation: 116938
What you need to remember is that this is private user data. If you want to access private user data you need permission of the owner of the data to access it. Enabling the api in the script only means that your script will be using that API it does not mean that a user has granted you access to their data.
Access denied
either means that the user you have authenticated with does not have permission to do what it is you are trying to do. or your application has not been granted any permissions.
Apps Script determines the authorization scopes (like access your Google Sheets files or Gmail) automatically, based on a scan of the code. Code that is commented out can still generate an authorization request. If a script needs authorization, you'll see one of the authorization dialogs shown here when it is run. Read more here Authorization
Upvotes: 1