2021-08-26 14:37:55 +02:00
|
|
|
'use strict';
|
|
|
|
|
2021-08-30 09:05:39 +02:00
|
|
|
const { trim } = require('lodash/fp');
|
2021-08-26 14:37:55 +02:00
|
|
|
const { getService } = require('../utils');
|
|
|
|
const { validateApiTokenCreationInput } = require('../validation/api-tokens');
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
async create(ctx) {
|
2021-08-30 09:12:10 +02:00
|
|
|
const { body } = ctx.request;
|
2021-08-26 14:37:55 +02:00
|
|
|
const apiTokenService = getService('api-token');
|
|
|
|
|
2021-08-27 16:32:36 +02:00
|
|
|
/**
|
|
|
|
* We trim both field to avoid having issues with either:
|
|
|
|
* - having a space at the end or start of the value.
|
|
|
|
* - having only spaces as value;
|
|
|
|
*/
|
2021-08-30 09:12:10 +02:00
|
|
|
const attributes = {
|
|
|
|
name: trim(body.name),
|
|
|
|
description: trim(body.description),
|
|
|
|
type: body.type,
|
|
|
|
};
|
2021-08-27 16:32:36 +02:00
|
|
|
|
2021-08-26 14:37:55 +02:00
|
|
|
try {
|
2021-08-27 08:19:14 +02:00
|
|
|
await validateApiTokenCreationInput(attributes);
|
2021-08-26 14:37:55 +02:00
|
|
|
} catch (err) {
|
|
|
|
return ctx.badRequest('ValidationError', err);
|
|
|
|
}
|
|
|
|
|
2021-08-27 16:23:19 +02:00
|
|
|
const alreadyExists = await apiTokenService.exists({ name: attributes.name });
|
|
|
|
if (alreadyExists) {
|
2021-08-26 14:37:55 +02:00
|
|
|
return ctx.badRequest('Name already taken');
|
|
|
|
}
|
|
|
|
|
|
|
|
const apiToken = await apiTokenService.create(attributes);
|
|
|
|
ctx.created({ data: apiToken });
|
|
|
|
},
|
2021-08-27 08:14:36 +02:00
|
|
|
|
|
|
|
async list(ctx) {
|
|
|
|
const apiTokenService = getService('api-token');
|
|
|
|
const apiTokens = await apiTokenService.list();
|
|
|
|
|
|
|
|
ctx.send({ data: apiTokens });
|
|
|
|
},
|
2021-08-26 14:37:55 +02:00
|
|
|
};
|