-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuser.ts
403 lines (349 loc) · 8.98 KB
/
user.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import argon2 from 'argon2';
import crypto from 'crypto';
import jwt, { Secret } from 'jsonwebtoken';
import { OptionalId } from '../mongo';
import { Collection, ObjectId } from 'mongodb';
import AbstractModel from './abstractModel';
import objectHasOnlyProps from '../utils/objectHasOnlyProps';
import { NotificationsChannelsDBScheme } from '../types/notification-channels';
import { BankCard, UserDBScheme } from '@hawk.so/types';
import uuid from 'uuid/v4';
/**
* Utility type for making specific fields optional
*/
type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>
/**
* Tokens pair for User authentication.
* Authorization by access token and refreshing pair by refresh token (after access token was expired).
*/
export interface TokensPair {
/**
* User's access token
*/
accessToken: string;
/**
* User's refresh token for getting new tokens pair
*/
refreshToken: string;
}
/**
* Membership collection DB implementation
*/
export interface MembershipDBScheme {
/**
* Document id
*/
_id: ObjectId;
/**
* User's workspace id
*/
workspaceId: ObjectId;
/**
* Shows if member is pending
*/
isPending?: boolean;
}
/**
* This structure represents how user notifications are stored at the DB (in 'users' collection)
*/
export interface UserNotificationsDBScheme {
/**
* Channels with their settings
*/
channels: NotificationsChannelsDBScheme;
/**
* Types of notifications to receive
*/
whatToReceive: { [key in UserNotificationType]: boolean };
}
/**
* Available options of 'What to receive'
*/
export enum UserNotificationType {
/**
* When user is assigned to the issue (event)
*/
IssueAssigning = 'IssueAssigning',
/**
* Regular digest of what happened on the project for the week
*/
WeeklyDigest = 'WeeklyDigest',
/**
* Only important messages from Hawk team
*/
SystemMessages = 'SystemMessages',
}
/**
* User model
*/
export default class UserModel extends AbstractModel<UserDBScheme> implements UserDBScheme {
/**
* User's id
*/
public _id!: ObjectId;
/**
* User's email
*/
public email?: string;
/**
* User's password
*/
public password?: string;
/**
* User's image url
*/
public image?: string;
/**
* User's name
*/
public name?: string;
/**
* User's GitHub profile id
*/
public githubId?: string;
/**
* User's original password (this field appears only after registration).
* Using to send password to user after registration
*/
public generatedPassword?: string;
/**
* User notifications settings
*/
public notifications!: UserNotificationsDBScheme;
/**
* Saved bank cards for one-click payments
*/
public bankCards?: BankCard[]
/**
* Model's collection
*/
protected collection: Collection<UserDBScheme>;
/**
* Collection of user's workspaces
*/
private membershipCollection: Collection<MembershipDBScheme>;
/**
* Model constructor
* @param modelData - user data
*/
constructor(modelData: UserDBScheme) {
/**
* Fallback for name using email
*/
if (modelData.email && !modelData.name) {
modelData.name = modelData.email;
}
super(modelData);
this.membershipCollection = this.dbConnection.collection('membership:' + this._id);
this.collection = this.dbConnection.collection<UserDBScheme>('users');
}
/**
* Generate 16bytes password
*/
public static generatePassword(): Promise<string> {
return new Promise((resolve, reject) => {
crypto.randomBytes(8, (err, buff) => {
if (err) {
return reject(err);
}
resolve(buff.toString('hex'));
});
});
}
/**
* Compose default notifications settings for new users.
*
* @param email - user email from the sign-up form will be used as email-channel endpoint
*/
public static generateDefaultNotificationsSettings(email: string): UserNotificationsDBScheme {
return {
channels: {
email: {
endpoint: email,
isEnabled: true,
minPeriod: 0,
},
},
whatToReceive: {
IssueAssigning: true,
WeeklyDigest: true,
SystemMessages: true,
},
};
}
/**
* Hash password
* @param password - password to hash
*/
public static async hashPassword(password: string): Promise<string> {
return argon2.hash(password);
}
/**
* Change user's password
* Hashes new password and updates the document
*
* @param userId - user ID
* @param newPassword - new user password
*/
public async changePassword(newPassword: string): Promise<void> {
const hashedPassword = await UserModel.hashPassword(newPassword);
const status = await this.update(
{ _id: new ObjectId(this._id) },
{ password: hashedPassword }
);
if (status !== 1) {
throw new Error("Can't change password");
}
}
/**
* Update user profile data
* @param userId - user ID
* @param user – user object
*/
public async updateProfile(user: Partial<UserDBScheme>): Promise<void> {
if (!await objectHasOnlyProps(user, {
name: true,
email: true,
image: true,
notifications: true,
})) {
throw new Error('User object has invalid properties');
}
try {
await this.update(
{ _id: new ObjectId(this._id) },
user
);
} catch (e) {
throw new Error('Can\'t update profile');
}
}
/**
* Generates JWT
*/
public async generateTokensPair(): Promise<TokensPair> {
const accessToken = await jwt.sign(
{
userId: this._id,
},
process.env.JWT_SECRET_ACCESS_TOKEN as Secret,
{ expiresIn: '15m' }
);
const refreshToken = await jwt.sign(
{
userId: this._id,
},
process.env.JWT_SECRET_REFRESH_TOKEN as Secret,
{ expiresIn: '30d' }
);
return {
accessToken,
refreshToken,
};
}
/**
* Compare unhashed password with user's password
* @param password - password to check
*/
public async comparePassword(password: string): Promise<boolean> {
if (!this.password) {
return false;
}
return argon2.verify(this.password, password);
}
/**
* Adds new workspace to the user's membership list
* @param workspaceId - user's id to add
* @param isPending - if true, mark user's membership as pending
*/
public async addWorkspace(workspaceId: string, isPending = false): Promise<object> {
const doc: OptionalId<MembershipDBScheme> = {
workspaceId: new ObjectId(workspaceId),
};
if (isPending) {
doc.isPending = isPending;
}
const documentId = (await this.membershipCollection.insertOne(doc)).insertedId;
return {
id: documentId,
workspaceId,
};
}
/**
* Remove workspace from membership collection
* @param workspaceId - id of workspace to remove
*/
public async removeWorkspace(workspaceId: string): Promise<{ workspaceId: string }> {
await this.membershipCollection.deleteOne({
workspaceId: new ObjectId(workspaceId),
});
return {
workspaceId,
};
}
/**
* Mark workspace as removed.
* @param workspaceId - id of workspace to remove
*/
public async markWorkspaceAsRemoved(workspaceId: string): Promise<{ workspaceId: string }> {
await this.membershipCollection.updateOne({
workspaceId: new ObjectId(workspaceId),
}, {
$set: { isRemoved: true },
});
return {
workspaceId,
};
}
/**
* Confirm membership of workspace by id
* @param workspaceId - workspace id to confirm
*/
public async confirmMembership(workspaceId: string): Promise<void> {
await this.membershipCollection.updateOne(
{
workspaceId: new ObjectId(workspaceId),
},
{ $unset: { isPending: '' } }
);
}
/**
* Get user's workspaces ids
* Returns all user's workspaces if ids = []
* @param ids - workspaces id to filter them if there are workspaces that doesn't belong to the user
*/
public async getWorkspacesIds(ids: (string | ObjectId)[] = []): Promise<string[]> {
const idsAsObjectId = ids.map(id => new ObjectId(id));
const searchQuery = ids.length ? {
workspaceId: {
$in: idsAsObjectId,
},
isRemoved: { $exists: false },
} : { isRemoved: { $exists: false } };
const membershipDocuments = await this.membershipCollection.find(searchQuery).toArray();
return membershipDocuments.map(doc => doc.workspaceId.toString());
}
/**
* Saves new back card of the user
* @param cardData - card data to save
*/
public async saveNewBankCard(cardData: PartialBy<BankCard, 'id'>): Promise<void> {
const userWithProvidedCard = await this.collection.findOne({
_id: this._id,
'bankCards.token': cardData.token,
});
if (userWithProvidedCard) {
return;
}
await this.collection.updateOne({
_id: this._id,
}, {
$push: {
bankCards: {
id: uuid(),
...cardData,
},
},
});
}
}