2
0

feat(user): Revokable API tokens

This commit is contained in:
Baptiste Arnaud
2022-06-03 13:20:19 +02:00
parent e5d7f1d1ce
commit a0929c492b
20 changed files with 472 additions and 43 deletions

View File

@ -7,10 +7,10 @@ import {
WorkspaceRole,
WorkspaceInvitation,
} from 'db'
import { randomUUID } from 'crypto'
import type { Adapter, AdapterUser } from 'next-auth/adapters'
import cuid from 'cuid'
import { got } from 'got'
import { generateId } from 'utils'
type InvitationWithWorkspaceId = Invitation & {
typebot: {
@ -38,7 +38,9 @@ export function CustomAdapter(p: PrismaClient): Adapter {
data: {
...data,
id: user.id,
apiToken: randomUUID(),
apiTokens: {
create: { name: 'Default', token: generateId(24) },
},
workspaces:
workspaceInvitations.length > 0
? undefined

View File

@ -8,7 +8,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
if (!user) return notAuthenticated(res)
const id = req.query.id.toString()
const id = req.query.userId.toString()
if (req.method === 'PUT') {
const data = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const typebots = await prisma.user.update({

View File

@ -0,0 +1,39 @@
import { withSentry } from '@sentry/nextjs'
import prisma from 'libs/prisma'
import { NextApiRequest, NextApiResponse } from 'next'
import { getAuthenticatedUser } from 'services/api/utils'
import { generateId, methodNotAllowed, notAuthenticated } from 'utils'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
if (!user) return notAuthenticated(res)
if (req.method === 'GET') {
const apiTokens = await prisma.apiToken.findMany({
where: { ownerId: user.id },
select: {
id: true,
name: true,
createdAt: true,
},
orderBy: { createdAt: 'desc' },
})
return res.send({ apiTokens })
}
if (req.method === 'POST') {
const data = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const apiToken = await prisma.apiToken.create({
data: { name: data.name, ownerId: user.id, token: generateId(24) },
})
return res.send({
apiToken: {
id: apiToken.id,
name: apiToken.name,
createdAt: apiToken.createdAt,
token: apiToken.token,
},
})
}
methodNotAllowed(res)
}
export default withSentry(handler)

View File

@ -0,0 +1,21 @@
import { withSentry } from '@sentry/nextjs'
import prisma from 'libs/prisma'
import { NextApiRequest, NextApiResponse } from 'next'
import { getAuthenticatedUser } from 'services/api/utils'
import { methodNotAllowed, notAuthenticated } from 'utils'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
if (!user) return notAuthenticated(res)
if (req.method === 'DELETE') {
const id = req.query.tokenId.toString()
const apiToken = await prisma.apiToken.delete({
where: { id },
})
return res.send({ apiToken })
}
methodNotAllowed(res)
}
export default withSentry(handler)