115 lines
2.5 KiB
JavaScript
Raw Normal View History

'use strict';
const crypto = require('crypto');
2021-08-30 14:00:53 +02:00
/**
* @typedef {'read-only'|'full-access'} TokenType
*/
2021-08-27 09:44:29 +02:00
/**
* @typedef ApiToken
*
2021-08-30 14:00:53 +02:00
* @property {number|string} id
2021-08-27 09:44:29 +02:00
* @property {string} name
* @property {string} [description]
* @property {string} accessKey
2021-08-30 14:00:53 +02:00
* @property {TokenType} type
2021-08-27 09:44:29 +02:00
*/
/**
* @param {Object} whereParams
* @param {string} whereParams.name
* @param {string} [whereParams.description]
*
* @returns {Promise<boolean>}
*/
const exists = async (whereParams = {}) => {
const apiToken = await strapi.query('admin::api-token').findOne({ where: whereParams });
return !!apiToken;
};
/**
* @param {string} accessKey
*
* @returns {string}
*/
const hash = accessKey => {
return crypto
.createHmac('sha512', strapi.config.get('server.admin.api-token.salt'))
.update(accessKey)
.digest('hex');
};
/**
* @param {Object} attributes
2021-08-30 14:00:53 +02:00
* @param {TokenType} attributes.type
* @param {string} attributes.name
* @param {string} [attributes.description]
*
2021-08-27 09:44:29 +02:00
* @returns {Promise<ApiToken>}
*/
const create = async attributes => {
const accessKey = crypto.randomBytes(128).toString('hex');
const apiToken = await strapi.query('admin::api-token').create({
select: ['id', 'name', 'description', 'type'],
data: {
...attributes,
accessKey: hash(accessKey),
},
});
return {
...apiToken,
accessKey,
};
};
/**
* @returns {void}
*/
const createSaltIfNotDefined = () => {
if (strapi.config.get('server.admin.api-token.salt')) {
return;
}
if (process.env.API_TOKEN_SALT) {
throw new Error(
`There's something wrong with the configuration of your api-token salt. If you have changed the env variable used in the configuration file, please verify that you have created and set the variable in your .env file.`
);
}
const salt = crypto.randomBytes(16).toString('hex');
strapi.fs.appendFile('.env', `API_TOKEN_SALT=${salt}\n`);
strapi.config.set('server.admin.api-token.salt', salt);
};
/**
2021-08-30 14:00:53 +02:00
* @returns {Promise<{id: number|string, name: string, description: string, type: TokenType}>}
*/
const list = async () => {
2021-08-30 14:00:53 +02:00
return strapi.query('admin::api-token').findMany({
select: ['id', 'name', 'description', 'type'],
2021-08-27 08:39:08 +02:00
orderBy: { name: 'ASC' },
});
};
2021-08-31 15:31:54 +02:00
/**
* @param {string|number} id
*
* @returns {Promise<void>}
*/
const revoke = async id => {
return strapi.query('admin::api-token').delete({ where: { id } });
};
module.exports = {
create,
exists,
createSaltIfNotDefined,
hash,
list,
2021-08-31 15:31:54 +02:00
revoke,
};