/
api-token.ts
72 lines (61 loc) · 1.71 KB
/
api-token.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import BadDataError from '../../error/bad-data-error';
import { IEnvironment } from '../model';
export const ALL = '*';
export enum ApiTokenType {
CLIENT = 'client',
ADMIN = 'admin',
}
export interface IApiTokenCreate {
secret: string;
username: string;
type: ApiTokenType;
environment: string;
project: string;
expiresAt?: Date;
}
export interface IApiToken extends IApiTokenCreate {
createdAt: Date;
seenAt?: Date;
environment: string;
project: string;
}
export const validateApiToken = ({
type,
project,
environment,
}: Omit<IApiTokenCreate, 'secret'>): void => {
if (type === ApiTokenType.ADMIN && project !== ALL) {
throw new BadDataError(
'Admin token cannot be scoped to single project',
);
}
if (type === ApiTokenType.ADMIN && environment !== ALL) {
throw new BadDataError(
'Admin token cannot be scoped to single environment',
);
}
if (type === ApiTokenType.CLIENT && environment === ALL) {
throw new BadDataError(
'Client token cannot be scoped to all environments',
);
}
};
export const validateApiTokenEnvironment = (
{ environment }: Pick<IApiTokenCreate, 'environment'>,
environments: IEnvironment[],
): void => {
if (environment === ALL) {
return;
}
const selectedEnvironment = environments.find(
(env) => env.name === environment,
);
if (!selectedEnvironment) {
throw new BadDataError(`Environment=${environment} does not exist`);
}
if (!selectedEnvironment.enabled) {
throw new BadDataError(
'Client token cannot be scoped to disabled environments',
);
}
};