1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-10-18 20:09:08 +02:00
unleash.unleash/src/test/fixtures/fake-api-token-store.ts
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

76 lines
2.0 KiB
TypeScript

import { IApiTokenStore } from '../../lib/types/stores/api-token-store';
import { IApiToken, IApiTokenCreate } from '../../lib/types/models/api-token';
import NotFoundError from '../../lib/error/notfound-error';
import EventEmitter from 'events';
export default class FakeApiTokenStore
extends EventEmitter
implements IApiTokenStore
{
tokens: IApiToken[] = [];
async delete(key: string): Promise<void> {
this.tokens.splice(
this.tokens.findIndex((t) => t.secret === key),
1,
);
}
async count(): Promise<number> {
return this.tokens.length;
}
async deleteAll(): Promise<void> {
this.tokens = [];
}
destroy(): void {}
async exists(key: string): Promise<boolean> {
return this.tokens.some((token) => token.secret === key);
}
async get(key: string): Promise<IApiToken> {
const token = this.tokens.find((t) => t.secret === key);
if (token) {
return token;
}
throw new NotFoundError(`Could not find token with secret ${key}`);
}
async getAll(): Promise<IApiToken[]> {
return this.tokens;
}
async getAllActive(): Promise<IApiToken[]> {
return this.tokens.filter((token) => token.expiresAt > new Date());
}
async insert(newToken: IApiTokenCreate): Promise<IApiToken> {
const apiToken = {
createdAt: new Date(),
project: newToken.projects?.join(',') || '*',
...newToken,
};
this.tokens.push(apiToken);
this.emit('insert');
return apiToken;
}
async markSeenAt(secrets: string[]): Promise<void> {
this.tokens
.filter((t) => secrets.includes(t.secret))
.forEach((t) => {
// eslint-disable-next-line no-param-reassign
t.seenAt = new Date();
});
}
async setExpiry(secret: string, expiresAt: Date): Promise<IApiToken> {
const t = await this.get(secret);
t.expiresAt = expiresAt;
return t;
}
}