1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-12-22 19:07:54 +01:00
unleash.unleash/src/migrations/20220331085057-add-api-link-table.js
sighphyre e889d8e29c feat: Implement multi token support for client tokens
This adds support for multi project tokens to be created. Backward compatibility is handled at 3 different layers here:

- The API is made backwards compatible though a permissive data type that accepts either a project?: string or projects?: string[] property, validation is done through JOI here, which ensures that projects and project are not set together. In the case of neither, this defaults to the previous default of ALL_PROJECTS
- The service layer method to handle adding tokens has been made tolerant to either of the above case and has been deprecated, a new method supporting only the new structure of using projects has been added
- Existing compatibility for consumers of Unleash as a library should not be affected either, the ApiUser constructor is now tolerant to the the first input and will internally map to the new cleaned structure
2022-04-06 08:11:41 +02:00

42 lines
1.2 KiB
JavaScript

'use strict';
exports.up = function (db, cb) {
db.runSql(
`
CREATE TABLE IF NOT EXISTS api_token_project
(
secret text NOT NULL,
project text NOT NULL,
FOREIGN KEY (secret) REFERENCES api_tokens (secret) ON DELETE CASCADE,
FOREIGN KEY (project) REFERENCES projects(id) ON DELETE CASCADE
);
INSERT INTO api_token_project SELECT secret, project FROM api_tokens WHERE project IS NOT NULL;
ALTER TABLE api_tokens DROP COLUMN "project";
`,
cb,
);
};
//This is a lossy down migration, tokens with multiple projects are discarded
exports.down = function (db, cb) {
db.runSql(
`
ALTER TABLE api_tokens ADD COLUMN project VARCHAR REFERENCES PROJECTS(id) ON DELETE CASCADE;
DELETE FROM api_tokens WHERE secret LIKE '[]%';
UPDATE api_tokens
SET project = subquery.project
FROM(
SELECT token.secret, link.project FROM api_tokens AS token LEFT JOIN api_token_project AS link ON
token.secret = link.secret
) AS subquery
WHERE api_tokens.project = subquery.project;
DROP TABLE api_token_project;
`,
cb,
);
};