2023-09-20 15:26:52 +02:00
|
|
|
import prisma from '@typebot.io/lib/prisma'
|
2023-03-15 08:35:16 +01:00
|
|
|
import { Credentials } from '@typebot.io/schemas'
|
2022-01-18 18:25:18 +01:00
|
|
|
import { NextApiRequest, NextApiResponse } from 'next'
|
2023-03-15 11:51:30 +01:00
|
|
|
import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUser'
|
2022-05-13 15:22:44 -07:00
|
|
|
import {
|
|
|
|
|
badRequest,
|
|
|
|
|
forbidden,
|
|
|
|
|
methodNotAllowed,
|
|
|
|
|
notAuthenticated,
|
2023-03-15 08:35:16 +01:00
|
|
|
} from '@typebot.io/lib/api'
|
2023-10-06 16:34:10 +02:00
|
|
|
import { encrypt } from '@typebot.io/lib/api/encryption/encrypt'
|
2022-01-18 18:25:18 +01:00
|
|
|
|
|
|
|
|
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
2023-04-03 16:42:10 +02:00
|
|
|
const user = await getAuthenticatedUser(req, res)
|
2022-03-04 17:21:01 +01:00
|
|
|
if (!user) return notAuthenticated(res)
|
2022-05-13 15:22:44 -07:00
|
|
|
const workspaceId = req.query.workspaceId as string | undefined
|
|
|
|
|
if (!workspaceId) return badRequest(res)
|
2022-01-18 18:25:18 +01:00
|
|
|
if (req.method === 'GET') {
|
|
|
|
|
const credentials = await prisma.credentials.findMany({
|
2022-05-13 15:22:44 -07:00
|
|
|
where: {
|
|
|
|
|
workspace: { id: workspaceId, members: { some: { userId: user.id } } },
|
|
|
|
|
},
|
|
|
|
|
select: { name: true, type: true, workspaceId: true, id: true },
|
2022-02-07 18:06:37 +01:00
|
|
|
})
|
|
|
|
|
return res.send({ credentials })
|
|
|
|
|
}
|
|
|
|
|
if (req.method === 'POST') {
|
2022-02-22 10:16:35 +01:00
|
|
|
const data = (
|
|
|
|
|
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
|
2022-05-13 15:22:44 -07:00
|
|
|
) as Credentials
|
2023-05-25 10:32:35 +02:00
|
|
|
const { encryptedData, iv } = await encrypt(data.data)
|
2022-05-13 15:22:44 -07:00
|
|
|
const workspace = await prisma.workspace.findFirst({
|
|
|
|
|
where: { id: workspaceId, members: { some: { userId: user.id } } },
|
|
|
|
|
select: { id: true },
|
|
|
|
|
})
|
|
|
|
|
if (!workspace) return forbidden(res)
|
2022-02-07 18:06:37 +01:00
|
|
|
const credentials = await prisma.credentials.create({
|
|
|
|
|
data: {
|
|
|
|
|
...data,
|
|
|
|
|
data: encryptedData,
|
|
|
|
|
iv,
|
2022-05-13 15:22:44 -07:00
|
|
|
workspaceId,
|
|
|
|
|
},
|
2022-01-18 18:25:18 +01:00
|
|
|
})
|
|
|
|
|
return res.send({ credentials })
|
|
|
|
|
}
|
|
|
|
|
return methodNotAllowed(res)
|
|
|
|
|
}
|
|
|
|
|
|
2022-12-16 08:39:14 +01:00
|
|
|
export default handler
|