-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
credentials.ts
50 lines (48 loc) 路 1.56 KB
/
credentials.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import prisma from '@/lib/prisma'
import { Credentials } from '@typebot.io/schemas'
import { NextApiRequest, NextApiResponse } from 'next'
import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUser'
import {
badRequest,
forbidden,
methodNotAllowed,
notAuthenticated,
encrypt,
} from '@typebot.io/lib/api'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req, res)
if (!user) return notAuthenticated(res)
const workspaceId = req.query.workspaceId as string | undefined
if (!workspaceId) return badRequest(res)
if (req.method === 'GET') {
const credentials = await prisma.credentials.findMany({
where: {
workspace: { id: workspaceId, members: { some: { userId: user.id } } },
},
select: { name: true, type: true, workspaceId: true, id: true },
})
return res.send({ credentials })
}
if (req.method === 'POST') {
const data = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as Credentials
const { encryptedData, iv } = await encrypt(data.data)
const workspace = await prisma.workspace.findFirst({
where: { id: workspaceId, members: { some: { userId: user.id } } },
select: { id: true },
})
if (!workspace) return forbidden(res)
const credentials = await prisma.credentials.create({
data: {
...data,
data: encryptedData,
iv,
workspaceId,
},
})
return res.send({ credentials })
}
return methodNotAllowed(res)
}
export default handler