2022-02-07 18:06:37 +01:00
|
|
|
import { Credentials as CredentialsFromDb } from 'db'
|
2022-03-04 18:36:26 +01:00
|
|
|
import { OAuth2Client, Credentials } from 'google-auth-library'
|
2022-02-07 18:06:37 +01:00
|
|
|
import { GoogleSheetsCredentialsData } from 'models'
|
|
|
|
import { decrypt, encrypt } from 'utils'
|
2022-01-18 18:25:18 +01:00
|
|
|
import prisma from './prisma'
|
|
|
|
|
|
|
|
export const oauth2Client = new OAuth2Client(
|
2022-05-30 16:40:13 +02:00
|
|
|
process.env.GOOGLE_CLIENT_ID,
|
2022-01-18 18:25:18 +01:00
|
|
|
process.env.GOOGLE_CLIENT_SECRET,
|
|
|
|
`${process.env.NEXTAUTH_URL}/api/credentials/google-sheets/callback`
|
|
|
|
)
|
|
|
|
|
|
|
|
export const getAuthenticatedGoogleClient = async (
|
|
|
|
userId: string,
|
|
|
|
credentialsId: string
|
2022-04-20 10:05:33 -07:00
|
|
|
): Promise<
|
|
|
|
{ client: OAuth2Client; credentials: CredentialsFromDb } | undefined
|
|
|
|
> => {
|
|
|
|
const credentials = (await prisma.credentials.findFirst({
|
2022-05-13 15:22:44 -07:00
|
|
|
where: { id: credentialsId, workspace: { members: { some: { userId } } } },
|
2022-03-04 14:40:13 +01:00
|
|
|
})) as CredentialsFromDb | undefined
|
2022-05-13 15:22:44 -07:00
|
|
|
if (!credentials) return
|
2022-02-07 18:06:37 +01:00
|
|
|
const data = decrypt(
|
|
|
|
credentials.data,
|
|
|
|
credentials.iv
|
|
|
|
) as GoogleSheetsCredentialsData
|
2022-03-04 18:36:26 +01:00
|
|
|
|
2022-02-07 18:06:37 +01:00
|
|
|
oauth2Client.setCredentials(data)
|
2022-03-04 18:36:26 +01:00
|
|
|
oauth2Client.on('tokens', updateTokens(credentialsId, data))
|
2022-04-20 10:05:33 -07:00
|
|
|
return { client: oauth2Client, credentials }
|
2022-01-18 18:25:18 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
const updateTokens =
|
2022-03-04 18:36:26 +01:00
|
|
|
(credentialsId: string, existingCredentials: GoogleSheetsCredentialsData) =>
|
|
|
|
async (credentials: Credentials) => {
|
|
|
|
const newCredentials = {
|
|
|
|
refresh_token: existingCredentials.refresh_token,
|
|
|
|
...credentials,
|
|
|
|
}
|
|
|
|
const { encryptedData, iv } = encrypt(newCredentials)
|
|
|
|
await prisma.credentials.update({
|
2022-01-18 18:25:18 +01:00
|
|
|
where: { id: credentialsId },
|
2022-02-07 18:06:37 +01:00
|
|
|
data: { data: encryptedData, iv },
|
2022-01-18 18:25:18 +01:00
|
|
|
})
|
2022-02-07 18:06:37 +01:00
|
|
|
}
|