⚡ (sheets) Use Google Drive picker and remove sensitive OAuth scope
BREAKING CHANGE: The Google Picker API needs to be enabled in the Google Cloud console. You also need to enable it in your NEXT_PUBLIC_GOOGLE_API_KEY. You also need to add the drive.file OAuth scope.
This commit is contained in:
53
packages/lib/google.ts
Normal file
53
packages/lib/google.ts
Normal file
@ -0,0 +1,53 @@
|
||||
import { env } from '@typebot.io/env'
|
||||
import { Credentials as CredentialsFromDb } from '@typebot.io/prisma'
|
||||
import { GoogleSheetsCredentials } from '@typebot.io/schemas'
|
||||
import { decrypt } from './api/encryption/decrypt'
|
||||
import { encrypt } from './api/encryption/encrypt'
|
||||
import prisma from './prisma'
|
||||
import { isDefined } from './utils'
|
||||
import { OAuth2Client, Credentials } from 'google-auth-library'
|
||||
|
||||
export const getAuthenticatedGoogleClient = async (
|
||||
credentialsId: string
|
||||
): Promise<OAuth2Client | undefined> => {
|
||||
const credentials = (await prisma.credentials.findFirst({
|
||||
where: { id: credentialsId },
|
||||
})) as CredentialsFromDb | undefined
|
||||
if (!credentials) return
|
||||
const data = (await decrypt(
|
||||
credentials.data,
|
||||
credentials.iv
|
||||
)) as GoogleSheetsCredentials['data']
|
||||
|
||||
const oauth2Client = new OAuth2Client(
|
||||
env.GOOGLE_CLIENT_ID,
|
||||
env.GOOGLE_CLIENT_SECRET,
|
||||
`${env.NEXTAUTH_URL}/api/credentials/google-sheets/callback`
|
||||
)
|
||||
oauth2Client.setCredentials(data)
|
||||
oauth2Client.on('tokens', updateTokens(credentialsId, data))
|
||||
return oauth2Client
|
||||
}
|
||||
|
||||
const updateTokens =
|
||||
(
|
||||
credentialsId: string,
|
||||
existingCredentials: GoogleSheetsCredentials['data']
|
||||
) =>
|
||||
async (credentials: Credentials) => {
|
||||
if (
|
||||
isDefined(existingCredentials.id_token) &&
|
||||
credentials.id_token !== existingCredentials.id_token
|
||||
)
|
||||
return
|
||||
const newCredentials: GoogleSheetsCredentials['data'] = {
|
||||
...existingCredentials,
|
||||
expiry_date: credentials.expiry_date,
|
||||
access_token: credentials.access_token,
|
||||
}
|
||||
const { encryptedData, iv } = await encrypt(newCredentials)
|
||||
await prisma.credentials.updateMany({
|
||||
where: { id: credentialsId },
|
||||
data: { data: encryptedData, iv },
|
||||
})
|
||||
}
|
@ -26,6 +26,7 @@
|
||||
"@sentry/nextjs": "7.77.0",
|
||||
"@trpc/server": "10.40.0",
|
||||
"@udecode/plate-common": "21.1.5",
|
||||
"google-auth-library": "8.9.0",
|
||||
"got": "12.6.0",
|
||||
"minio": "7.1.3",
|
||||
"remark-slate": "1.8.6",
|
||||
|
Reference in New Issue
Block a user