All checks were successful
Build and Push Docker Images / build (push) Successful in 2m34s
64 lines
1.7 KiB
TypeScript
64 lines
1.7 KiB
TypeScript
import express, { type Router, type Response } from 'express'
|
|
import { ApiKeyModel } from '../../../models/apikey.model.ts'
|
|
import { verifyAccessToken, type AuthRequest } from '../../../middleware/auth.ts'
|
|
|
|
const router = express.Router()
|
|
|
|
router.use(verifyAccessToken)
|
|
|
|
router.get('/', verifyAccessToken, async (req: AuthRequest, res: Response) => {
|
|
try {
|
|
const userId = req.userId
|
|
const doc = await ApiKeyModel.findOne({ userId: userId })
|
|
|
|
const apiKey = doc?.apiKey || ''
|
|
|
|
res.json({ apiKey })
|
|
} catch (error) {
|
|
console.error('Error fetching API key:', error)
|
|
res.status(500).json({ error: 'Failed to fetch API key' })
|
|
}
|
|
})
|
|
|
|
router.post('/', verifyAccessToken, async (req: AuthRequest, res: Response) => {
|
|
try {
|
|
const { apiKey } = req.body
|
|
if (!apiKey || !apiKey.trim()) {
|
|
return res.status(400).json({ error: 'Invalid API key' })
|
|
}
|
|
console.log(req.body)
|
|
const userId = req.userId
|
|
|
|
await ApiKeyModel.updateOne(
|
|
{},
|
|
{ $set: { userId: userId, apiKey: apiKey, lastUsed: new Date() } },
|
|
{ upsert: true },
|
|
)
|
|
|
|
res.json({ success: true })
|
|
} catch (error) {
|
|
console.error('Error saving API key:', error)
|
|
res.status(500).json({ error: 'Failed to save API key' })
|
|
}
|
|
})
|
|
|
|
router.delete('/', verifyAccessToken, async (req: AuthRequest, res: Response) => {
|
|
try {
|
|
const userId = req.userId
|
|
const result = await ApiKeyModel.deleteOne({ userId: userId })
|
|
|
|
if (result.deletedCount === 0) {
|
|
console.log('No API key found to delete.')
|
|
return res.status(204).end()
|
|
}
|
|
|
|
console.log('API key document deleted.')
|
|
res.json({ success: true, message: 'API key deleted' })
|
|
} catch (error) {
|
|
console.error('Error deleting API key:', error)
|
|
res.status(500).json({ error: 'Failed to delete API key' })
|
|
}
|
|
})
|
|
|
|
export default router as Router
|