-
-
Notifications
You must be signed in to change notification settings - Fork 768
/
Copy pathuser-store.ts
338 lines (287 loc) · 9.58 KB
/
user-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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/* eslint camelcase: "off" */
import type { Logger, LogProvider } from '../logger';
import User from '../types/user';
import NotFoundError from '../error/notfound-error';
import type {
ICreateUser,
IUserLookup,
IUserStore,
IUserUpdateFields,
} from '../types/stores/user-store';
import type { Db } from './db';
import type { IFlagResolver } from '../types';
const TABLE = 'users';
const PASSWORD_HASH_TABLE = 'used_passwords';
const USER_COLUMNS_PUBLIC = [
'id',
'name',
'username',
'email',
'image_url',
'seen_at',
'is_service',
'scim_id',
];
const USER_COLUMNS = [...USER_COLUMNS_PUBLIC, 'login_attempts', 'created_at'];
const emptify = (value) => {
if (!value) {
return undefined;
}
return value;
};
const safeToLower = (s?: string) => (s ? s.toLowerCase() : s);
const mapUserToColumns = (user: ICreateUser) => ({
name: user.name,
username: user.username,
email: safeToLower(user.email),
image_url: user.imageUrl,
});
const rowToUser = (row) => {
if (!row) {
throw new NotFoundError('No user found');
}
return new User({
id: row.id,
name: emptify(row.name),
username: emptify(row.username),
email: emptify(row.email),
imageUrl: emptify(row.image_url),
loginAttempts: row.login_attempts,
seenAt: row.seen_at,
createdAt: row.created_at,
isService: row.is_service,
scimId: row.scim_id,
});
};
class UserStore implements IUserStore {
private db: Db;
private logger: Logger;
private flagResolver: IFlagResolver;
constructor(db: Db, getLogger: LogProvider, flagResolver: IFlagResolver) {
this.db = db;
this.logger = getLogger('user-store.ts');
this.flagResolver = flagResolver;
}
async getPasswordsPreviouslyUsed(userId: number): Promise<string[]> {
const previouslyUsedPasswords = await this.db(PASSWORD_HASH_TABLE)
.select('password_hash')
.where({ user_id: userId });
return previouslyUsedPasswords.map((row) => row.password_hash);
}
async deletePasswordsUsedMoreThanNTimesAgo(
userId: number,
keepLastN: number,
): Promise<void> {
await this.db.raw(
`
WITH UserPasswords AS (
SELECT user_id, password_hash, used_at, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY used_at DESC) AS rn
FROM ${PASSWORD_HASH_TABLE}
WHERE user_id = ?)
DELETE FROM ${PASSWORD_HASH_TABLE} WHERE user_id = ? AND (user_id, password_hash, used_at) NOT IN (SELECT user_id, password_hash, used_at FROM UserPasswords WHERE rn <= ?
);
`,
[userId, userId, keepLastN],
);
}
async update(id: number, fields: IUserUpdateFields): Promise<User> {
await this.activeUsers()
.where('id', id)
.update(mapUserToColumns(fields));
return this.get(id);
}
async insert(user: ICreateUser): Promise<User> {
const emailHash = user.email
? this.db.raw('md5(?)', [user.email])
: null;
const rows = await this.db(TABLE)
.insert({
...mapUserToColumns(user),
email_hash: emailHash,
created_at: new Date(),
})
.returning(USER_COLUMNS);
return rowToUser(rows[0]);
}
async upsert(user: ICreateUser): Promise<User> {
const id = await this.hasUser(user);
if (id) {
return this.update(id, user);
}
return this.insert(user);
}
buildSelectUser(q: IUserLookup): any {
const query = this.activeAll();
if (q.id) {
return query.where('id', q.id);
}
if (q.email) {
return query.where('email', safeToLower(q.email));
}
if (q.username) {
return query.where('username', q.username);
}
throw new Error('Can only find users with id, username or email.');
}
activeAll(): any {
return this.db(TABLE).where({
deleted_at: null,
});
}
activeUsers(): any {
return this.db(TABLE).where({
deleted_at: null,
is_service: false,
is_system: false,
});
}
async hasUser(idQuery: IUserLookup): Promise<number | undefined> {
const query = this.buildSelectUser(idQuery);
const item = await query.first('id');
return item ? item.id : undefined;
}
async getAll(): Promise<User[]> {
const users = await this.activeUsers().select(USER_COLUMNS);
return users.map(rowToUser);
}
async search(query: string): Promise<User[]> {
const users = await this.activeUsers()
.select(USER_COLUMNS_PUBLIC)
.where('name', 'ILIKE', `%${query}%`)
.orWhere('username', 'ILIKE', `${query}%`)
.orWhere('email', 'ILIKE', `${query}%`);
return users.map(rowToUser);
}
async getAllWithId(userIdList: number[]): Promise<User[]> {
const users = await this.activeUsers()
.select(USER_COLUMNS_PUBLIC)
.whereIn('id', userIdList);
return users.map(rowToUser);
}
async getByQuery(idQuery: IUserLookup): Promise<User> {
const row = await this.buildSelectUser(idQuery).first(USER_COLUMNS);
return rowToUser(row);
}
async delete(id: number): Promise<void> {
return this.activeUsers()
.where({ id })
.update({
deleted_at: new Date(),
email: null,
username: null,
scim_id: null,
scim_external_id: null,
name: this.db.raw('name || ?', '(Deleted)'),
});
}
async getPasswordHash(userId: number): Promise<string> {
const item = await this.activeUsers()
.where('id', userId)
.first('password_hash');
if (!item) {
throw new NotFoundError('User not found');
}
return item.password_hash;
}
async setPasswordHash(
userId: number,
passwordHash: string,
disallowNPreviousPasswords: number,
): Promise<void> {
await this.activeUsers().where('id', userId).update({
password_hash: passwordHash,
});
// We apparently set this to null, but you should be allowed to have null, so need to allow this
if (passwordHash) {
await this.db(PASSWORD_HASH_TABLE).insert({
user_id: userId,
password_hash: passwordHash,
});
await this.deletePasswordsUsedMoreThanNTimesAgo(
userId,
disallowNPreviousPasswords,
);
}
}
async incLoginAttempts(user: User): Promise<void> {
return this.buildSelectUser(user).increment('login_attempts', 1);
}
async successfullyLogin(user: User): Promise<number> {
const currentDate = new Date();
const updateQuery = this.buildSelectUser(user).update({
login_attempts: 0,
seen_at: currentDate,
});
let firstLoginOrder = 0;
const existingUser =
await this.buildSelectUser(user).first('first_seen_at');
if (!existingUser.first_seen_at) {
const countEarlierUsers = await this.db(TABLE)
.whereNotNull('first_seen_at')
.andWhere('first_seen_at', '<', currentDate)
.count('*')
.then((res) => Number(res[0].count));
firstLoginOrder = countEarlierUsers;
await updateQuery.update({
first_seen_at: currentDate,
});
}
await updateQuery;
return firstLoginOrder;
}
async deleteAll(): Promise<void> {
await this.activeUsers().del();
}
async deleteScimUsers(): Promise<void> {
await this.db(TABLE).whereNotNull('scim_id').del();
}
async count(): Promise<number> {
return this.activeUsers()
.count('*')
.then((res) => Number(res[0].count));
}
async countServiceAccounts(): Promise<number> {
return this.db(TABLE)
.where({
deleted_at: null,
is_service: true,
})
.count('*')
.then((res) => Number(res[0].count));
}
async countRecentlyDeleted(): Promise<number> {
return this.db(TABLE)
.whereNotNull('deleted_at')
.andWhere(
'deleted_at',
'>=',
this.db.raw(`NOW() - INTERVAL '1 month'`),
)
.andWhere({ is_service: false, is_system: false })
.count('*')
.then((res) => Number(res[0].count));
}
destroy(): void {}
async exists(id: number): Promise<boolean> {
const result = await this.db.raw(
`SELECT EXISTS (SELECT 1 FROM ${TABLE} WHERE id = ? and deleted_at = null) AS present`,
[id],
);
const { present } = result.rows[0];
return present;
}
async get(id: number): Promise<User> {
const row = await this.activeUsers().where({ id }).first();
return rowToUser(row);
}
async getFirstUserDate(): Promise<Date | null> {
const firstInstanceUser = await this.db('users')
.select('created_at')
.where('is_system', '=', false)
.orderBy('created_at', 'asc')
.first();
return firstInstanceUser ? firstInstanceUser.created_at : null;
}
}
module.exports = UserStore;
export default UserStore;