fixes
This commit is contained in:
+50
-7
@@ -1,10 +1,56 @@
|
||||
import { google } from 'googleapis';
|
||||
import { Readable } from 'stream';
|
||||
import { prisma } from './prisma';
|
||||
|
||||
export async function uploadToDrive(accessToken: string, fileName: string, content: string, folderId?: string) {
|
||||
const auth = new google.auth.OAuth2();
|
||||
auth.setCredentials({ access_token: accessToken });
|
||||
export async function getGoogleAuth(userId: string) {
|
||||
const account = await prisma.account.findFirst({
|
||||
where: { userId, provider: 'google' },
|
||||
});
|
||||
|
||||
if (!account) {
|
||||
throw new Error('Google account not found');
|
||||
}
|
||||
|
||||
const auth = new google.auth.OAuth2(
|
||||
process.env.GOOGLE_CLIENT_ID,
|
||||
process.env.GOOGLE_CLIENT_SECRET
|
||||
);
|
||||
|
||||
auth.setCredentials({
|
||||
access_token: account.access_token,
|
||||
refresh_token: account.refresh_token,
|
||||
expiry_date: account.expires_at ? account.expires_at * 1000 : null,
|
||||
});
|
||||
|
||||
// Check if the token is expired or will expire in the next 1 minute
|
||||
// NextAuth stores expires_at in seconds
|
||||
const isExpired = account.expires_at ? (account.expires_at * 1000) < (Date.now() + 60000) : true;
|
||||
|
||||
if (isExpired && account.refresh_token) {
|
||||
try {
|
||||
const { credentials } = await auth.refreshAccessToken();
|
||||
auth.setCredentials(credentials);
|
||||
|
||||
// Update database with new tokens
|
||||
await prisma.account.update({
|
||||
where: { id: account.id },
|
||||
data: {
|
||||
access_token: credentials.access_token,
|
||||
refresh_token: credentials.refresh_token || account.refresh_token,
|
||||
expires_at: credentials.expiry_date ? Math.floor(credentials.expiry_date / 1000) : null,
|
||||
},
|
||||
});
|
||||
console.log('Successfully refreshed Google access token for user:', userId);
|
||||
} catch (error) {
|
||||
console.error('Error refreshing access token:', error);
|
||||
// If refresh fails, we still return the auth object, but requests will fail with 401
|
||||
}
|
||||
}
|
||||
|
||||
return auth;
|
||||
}
|
||||
|
||||
export async function uploadToDrive(auth: any, fileName: string, content: string, folderId?: string) {
|
||||
const drive = google.drive({ version: 'v3', auth });
|
||||
|
||||
const fileMetadata: any = {
|
||||
@@ -34,10 +80,7 @@ export async function uploadToDrive(accessToken: string, fileName: string, conte
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateDriveFile(accessToken: string, fileId: string, content: string) {
|
||||
const auth = new google.auth.OAuth2();
|
||||
auth.setCredentials({ access_token: accessToken });
|
||||
|
||||
export async function updateDriveFile(auth: any, fileId: string, content: string) {
|
||||
const drive = google.drive({ version: 'v3', auth });
|
||||
|
||||
const media = {
|
||||
|
||||
Reference in New Issue
Block a user