File size: 1,394 Bytes
a705c01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
53
54
55
56
57
58
59
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: {}
  });
});