feat(user): ✨ Revokable API tokens
This commit is contained in:
@ -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({
|
39
apps/builder/pages/api/users/[userId]/api-tokens.ts
Normal file
39
apps/builder/pages/api/users/[userId]/api-tokens.ts
Normal 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)
|
@ -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)
|
Reference in New Issue
Block a user