When integrating Google Drive functionality, make sure the OAuth scope provided during authentication includes the required permissions.
Initially, the scope I provided during user authentication was:
// @/lib/auth.config.ts
import { NextAuthConfig } from "next-auth";
import Google from "next-auth/providers/google";
export const authConfig: NextAuthConfig = {
providers: [
Google({
authorization: {
params: {
scope: "https://www.googleapis.com/auth/drive.file",
access_type: "offline",
prompt: "consent",
},
},
}),
],
};
This scope (https://www.googleapis.com/auth/drive.file
) only allows access to files created or opened by the app. To gain broader access, I updated the scope to:
// @/lib/auth.config.ts
import { NextAuthConfig } from "next-auth";
import Google from "next-auth/providers/google";
export const authConfig: NextAuthConfig = {
providers: [
Google({
authorization: {
params: {
scope: "https://www.googleapis.com/auth/drive",
access_type: "offline",
prompt: "consent",
},
},
}),
],
};
With this change, the refresh and access tokens issued will include the https://www.googleapis.com/auth/drive
scope, granting full access to the user's Google Drive.
In Node.js, the code is:
import { google } from 'googleapis';
async function getOAuthClient(accessToken,refreshToken) {
const oauth2Client = new google.auth.OAuth2(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET
);
oauth2Client.setCredentials({
access_token: accessToken,
refresh_token: refreshToken,
});
return oauth2Client;
}
// Set up the query string for the search
let query = "mimeType='application/vnd.google-apps.document'"; // Only Google Docs
// If a search query is provided, add it to the query
if (searchQuery) {
query += ` and name contains '${searchQuery}'`;
}
const oauthClient = await getOAuthClient(tenant);
const drive = google.drive({ version: 'v3', auth: oauthClient });
const response = await drive.files.list({
q: query,
fields: 'files(id, name, createdTime, modifiedTime, webViewLink)',
pageSize: 5,
orderBy: 'modifiedTime desc',
corpora: 'allDrives',
includeItemsFromAllDrives: true,
supportsAllDrives: true,
});
This resolved the issue for me. I hope it helps others facing similar problems!