-
-
Notifications
You must be signed in to change notification settings - Fork 768
/
Copy pathpublic-signup-token-store.ts
216 lines (192 loc) · 6.4 KB
/
public-signup-token-store.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import type { EventEmitter } from 'events';
import metricsHelper from '../util/metrics-helper';
import { DB_TIME } from '../metric-events';
import type { Logger, LogProvider } from '../logger';
import NotFoundError from '../error/notfound-error';
import type { PublicSignupTokenSchema } from '../openapi/spec/public-signup-token-schema';
import type { IPublicSignupTokenStore } from '../types/stores/public-signup-token-store';
import type { UserSchema } from '../openapi/spec/user-schema';
import type { IPublicSignupTokenCreate } from '../types/models/public-signup-token';
import type { Db } from './db';
const TABLE = 'public_signup_tokens';
const TOKEN_USERS_TABLE = 'public_signup_tokens_user';
interface ITokenInsert {
secret: string;
name: string;
expires_at: Date;
created_at: Date;
created_by?: string;
role_id: number;
}
interface ITokenRow extends ITokenInsert {
users: UserSchema[];
}
interface ITokenUserRow {
secret: string;
user_id: number;
created_at: Date;
}
const tokenRowReducer = (acc, tokenRow) => {
const {
userId,
userName,
userUsername,
roleId,
roleName,
roleType,
...token
} = tokenRow;
if (!acc[tokenRow.secret]) {
acc[tokenRow.secret] = {
secret: token.secret,
name: token.name,
url: token.url,
expiresAt: token.expires_at,
enabled: token.enabled,
createdAt: token.created_at,
createdBy: token.created_by,
role: {
id: roleId,
name: roleName,
type: roleType,
},
users: [],
};
}
const currentToken = acc[tokenRow.secret];
if (userId) {
currentToken.users.push({
id: userId,
name: userName,
username: userUsername,
});
}
return acc;
};
const toRow = (newToken: IPublicSignupTokenCreate) => {
if (!newToken) return;
return {
secret: newToken.secret,
name: newToken.name,
expires_at: newToken.expiresAt,
created_by: newToken.createdBy || null,
role_id: newToken.roleId,
url: newToken.url,
};
};
const toTokens = (rows: any[]): PublicSignupTokenSchema[] => {
const tokens = rows.reduce(tokenRowReducer, {});
return Object.values(tokens);
};
export class PublicSignupTokenStore implements IPublicSignupTokenStore {
private logger: Logger;
private timer: Function;
private db: Db;
constructor(db: Db, eventBus: EventEmitter, getLogger: LogProvider) {
this.db = db;
this.logger = getLogger('public-signup-tokens.js');
this.timer = (action: string) =>
metricsHelper.wrapTimer(eventBus, DB_TIME, {
store: 'public-signup-tokens',
action,
});
}
count(): Promise<number> {
return this.db(TABLE)
.count('*')
.then((res) => Number(res[0].count));
}
private makeTokenUsersQuery() {
return this.db<ITokenRow>(`${TABLE} as tokens`)
.leftJoin(
`${TOKEN_USERS_TABLE} as token_project_users`,
'tokens.secret',
'token_project_users.secret',
)
.leftJoin(`users`, 'token_project_users.user_id', 'users.id')
.leftJoin(`roles`, 'tokens.role_id', 'roles.id')
.select(
'tokens.secret',
'tokens.name',
'tokens.expires_at',
'tokens.enabled',
'tokens.created_at',
'tokens.created_by',
'tokens.url',
'token_project_users.user_id as userId',
'users.name as userName',
'users.username as userUsername',
'roles.id as roleId',
'roles.name as roleName',
'roles.type as roleType',
);
}
async getAll(): Promise<PublicSignupTokenSchema[]> {
const stopTimer = this.timer('getAll');
const rows = await this.makeTokenUsersQuery();
stopTimer();
return toTokens(rows);
}
async addTokenUser(secret: string, userId: number): Promise<void> {
await this.db<ITokenUserRow>(TOKEN_USERS_TABLE).insert(
{ user_id: userId, secret },
['created_at'],
);
}
async insert(
newToken: IPublicSignupTokenCreate,
): Promise<PublicSignupTokenSchema> {
const response = await this.db<ITokenRow>(TABLE).insert(
// @ts-expect-error - knex expects us to return a DbRecordArr<OurType>, we return OurType, which works fine.
toRow(newToken),
['secret'],
);
return this.get(response[0].secret);
}
async isValid(secret: string): Promise<boolean> {
const result = await this.db.raw(
`SELECT EXISTS (SELECT 1 FROM ${TABLE} WHERE secret = ? AND expires_at::date > ? AND enabled = true) AS valid`,
[secret, new Date()],
);
const { valid } = result.rows[0];
return valid;
}
destroy(): void {}
async exists(secret: string): Promise<boolean> {
const result = await this.db.raw(
`SELECT EXISTS (SELECT 1 FROM ${TABLE} WHERE secret = ?) AS present`,
[secret],
);
const { present } = result.rows[0];
return present;
}
async get(key: string): Promise<PublicSignupTokenSchema> {
const rows = await this.makeTokenUsersQuery().where(
'tokens.secret',
key,
);
if (rows.length > 0) {
return toTokens(rows)[0];
}
throw new NotFoundError('Could not find public signup token.');
}
async delete(secret: string): Promise<void> {
return this.db<ITokenInsert>(TABLE).where({ secret }).del();
}
async deleteAll(): Promise<void> {
return this.db<ITokenInsert>(TABLE).del();
}
async update(
secret: string,
{ expiresAt, enabled }: { expiresAt?: Date; enabled?: boolean },
): Promise<PublicSignupTokenSchema> {
const rows = await this.makeTokenUsersQuery()
.update({ expires_at: expiresAt, enabled })
.where('secret', secret)
.returning('*');
if (rows.length > 0) {
return toTokens(rows)[0];
}
throw new NotFoundError('Could not find public signup token.');
}
}