112 lines
2.9 KiB
JavaScript
Raw Normal View History

'use strict';
2021-08-30 09:05:39 +02:00
const { trim } = require('lodash/fp');
const has = require('lodash/has');
const { getService } = require('../utils');
const {
validateApiTokenCreationInput,
validateApiTokenUpdateInput,
} = require('../validation/api-tokens');
module.exports = {
async create(ctx) {
2021-08-30 09:12:10 +02:00
const { body } = ctx.request;
const apiTokenService = getService('api-token');
/**
* 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,
};
try {
2021-08-27 08:19:14 +02:00
await validateApiTokenCreationInput(attributes);
} catch (err) {
return ctx.badRequest('ValidationError', err);
}
const alreadyExists = await apiTokenService.exists({ name: attributes.name });
if (alreadyExists) {
return ctx.badRequest('Name already taken');
}
const apiToken = await apiTokenService.create(attributes);
ctx.created({ data: apiToken });
},
async list(ctx) {
const apiTokenService = getService('api-token');
const apiTokens = await apiTokenService.list();
ctx.send({ data: apiTokens });
},
2021-08-31 15:31:54 +02:00
async revoke(ctx) {
const { id } = ctx.params;
const apiTokenService = getService('api-token');
2021-09-02 10:47:06 +02:00
const apiToken = await apiTokenService.revoke(id);
2021-08-31 15:31:54 +02:00
2021-09-02 10:47:06 +02:00
ctx.deleted({ data: apiToken });
2021-08-31 15:31:54 +02:00
},
async get(ctx) {
const { id } = ctx.params;
const apiTokenService = getService('api-token');
2021-09-06 15:14:45 +02:00
const apiToken = await apiTokenService.getById(id);
if (!apiToken) {
ctx.notFound('API Token not found');
return;
}
ctx.send({ data: apiToken });
},
async update(ctx) {
const { body } = ctx.request;
const { id } = ctx.params;
const apiTokenService = getService('api-token');
const attributes = body;
/**
* 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;
*/
if (has(attributes, 'name')) {
attributes.name = trim(body.name);
}
if (has(attributes, 'description') || attributes.description === null) {
attributes.description = trim(body.description);
}
try {
await validateApiTokenUpdateInput(attributes);
} catch (err) {
return ctx.badRequest('ValidationError', err);
}
const apiTokenExists = await apiTokenService.getById(id);
if (!apiTokenExists) {
return ctx.notFound('API token not found');
}
if (has(attributes, 'name')) {
const nameAlreadyTaken = await apiTokenService.getByName(attributes.name);
if (!!nameAlreadyTaken && nameAlreadyTaken.id !== id) {
return ctx.badRequest('Name already taken');
}
}
const apiToken = await apiTokenService.update(id, attributes);
ctx.send({ data: apiToken });
},
};