1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-11-01 19:07:38 +01:00
unleash.unleash/src/test/fixtures/fake-api-token-store.ts
Fredrik Strand Oseberg 874d8459ce
Feat/add alias to api tokens (#1931)
* refactor: remove unused API definition routes

* feat: embed proxy endpoints

* feat: check token metadata for alias if none is found

* fix: rename param

* feat: add test for retrieving token by alias

* fix: update schema

* fix: refactor to alias

* fix: refactor to null

* fix: update snapshot

* fix: update openapi snapshot

* fix: add check to getUserForToken

* refactor: add more token alias tests

* refactor: use timingSafeEqual for token comparisons

Co-authored-by: olav <mail@olav.io>
2022-08-19 10:48:33 +02:00

79 lines
2.1 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 === null || token.expiresAt > new Date(),
);
}
async insert(newToken: IApiTokenCreate): Promise<IApiToken> {
const apiToken = {
createdAt: new Date(),
project: newToken.projects?.join(',') || '*',
alias: null,
...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;
}
}