| const ApiKey = require('../models/ApiKey'); | |
| const asyncHandler = require('../utils/asyncHandler'); | |
| const ErrorResponse = require('../utils/errorResponse'); | |
| // @desc Generate a new API Key | |
| // @route POST /api/users/keys | |
| // @access Private | |
| exports.createKey = asyncHandler(async (req, res, next) => { | |
| const { name } = req.body; | |
| const key = ApiKey.generateKey(); | |
| const apiKey = await ApiKey.create({ | |
| key, | |
| userId: req.user.id, | |
| name: name || 'Default Key' | |
| }); | |
| res.status(201).json({ | |
| success: true, | |
| data: apiKey | |
| }); | |
| }); | |
| // @desc Get all API Keys for a user | |
| // @route GET /api/users/keys | |
| // @access Private | |
| exports.getKeys = asyncHandler(async (req, res, next) => { | |
| const keys = await ApiKey.find({ userId: req.user.id }); | |
| res.status(200).json({ | |
| success: true, | |
| data: keys | |
| }); | |
| }); | |
| // @desc Delete an API Key | |
| // @route DELETE /api/users/keys/:id | |
| // @access Private | |
| exports.deleteKey = asyncHandler(async (req, res, next) => { | |
| const key = await ApiKey.findById(req.params.id); | |
| if (!key) { | |
| return next(new ErrorResponse('Key not found', 404)); | |
| } | |
| // Make sure user owns the key | |
| if (key.userId.toString() !== req.user.id) { | |
| return next(new ErrorResponse('Not authorized to delete this key', 401)); | |
| } | |
| await key.deleteOne(); | |
| res.status(200).json({ | |
| success: true, | |
| data: {} | |
| }); | |
| }); | |