| 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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531 | 1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
14x
1x
13x
13x
6x
7x
2x
5x
5x
5x
1x
1x
4x
4x
1x
1x
3x
1x
8x
8x
3x
5x
2x
1x
1x
1x
3x
1x
2x
2x
2x
1x
1x
1x
25x
25x
3x
22x
1x
21x
21x
1x
20x
3x
1x
2x
1x
1x
1x
18x
3x
1x
2x
1x
1x
1x
16x
7x
1x
6x
5x
1x
1x
10x
10x
5x
1x
4x
3x
1x
1x
6x
1x
5x
1x
7x
7x
3x
4x
1x
3x
1x
2x
3x
2x
1x
| const crypto = require('crypto');
const Router = require('koa-router');
const jwt = require('jsonwebtoken');
const isLoggedIn = require('../koa-middleware/isLoggedIn');
const HttpError = require('../koa-middleware/HttpError');
const {isValidUuidV4} = require('../../utils/isValidUuidV4');
const {isValidEmail} = require('../../utils/isValidEmail');
const {isValidPassword} = require('../../utils/isValidPassword');
const router = new Router();
/**
* @swagger
* /api/v1/users/login:
* post:
* description: Will return a time-limited JWT if sent user credentials are valid.
*
* produces:
* - application/json
*
* consumes:
* - application/json
*
* parameters:
* - in: body
* name: login
* schema:
* type: object
* properties:
* email:
* type: string
* format: email
* required: true
* example: john@smith.com
*
* password:
* type: string
* required: true
* example: Pass@123
*
* responses:
* 200:
* description: Your credentials are valid and JWT is been generated and returned.
* schema:
* type: object
* properties:
* JWT:
* type: string
* example: Bearer eyJhbGciOi...rWR8FC62tYb0qA
*
* 400:
* description: Missing or invalid email or password.
* schema:
* $ref: '#/definitions/UserInputError'
*
* 401:
* description: Email/password pair do not match.
* schema:
* $ref: '#/definitions/AuthError'
*/
router.post('/api/v1/users/login',
async (ctx) => {
if (!ctx.request.body) {
throw new HttpError(
400,
'INVALID_INPUT',
`Please send JSON as an input`
);
}
const {email, password} = ctx.request.body;
if (!isValidEmail(email)) {
throw new HttpError(
400,
'INVALID_INPUT_EMAIL',
`"${email}" is invalid email`
);
}
if (!password) {
throw new HttpError(
400,
'INVALID_INPUT_PASSWORD',
`"${password}" is invalid password`
);
}
const user = await ctx.postgres.Users
.findOne({
where: {
email,
},
})
.then((response) => response && typeof response.toJSON === 'function' ? response.toJSON() : response);
if (!user) {
ctx.logger.info(`Unable to find user with email "${email}"`);
throw new HttpError(
401,
'NO_MATCH',
'Email or password do not match'
);
}
const hashedPassword = crypto
.createHmac('sha256', user.id)
.update(String(password))
.digest('hex');
if (hashedPassword !== user.hashedPassword) {
ctx.logger.info(`Password mismatch for user ${user.id} "${email}"`);
throw new HttpError(
401,
'NO_MATCH',
'Email or password do not match'
);
}
ctx.body = {
JWT: 'Bearer ' + jwt.sign({
userId: user.id,
exp: Math.floor(Date.now() / 1000) + (24 * 60 * 60), // Expires in 1 day
}, process.env.JWT_SECRET || 'Pass@123'),
};
}
);
/**
* @swagger
* /api/v1/users/{id}:
* get:
* description: Returns a User that has the requested `id`.
*
* produces:
* - application/json
*
* parameters:
* - name: Authorization
* in: header
* description: Authorization header with JWT
* required: true
* type: string
*
* - in: path
* name: id
* type: string
* format: uuid
* required: true
* description: The `id` of the User we want to be returned
*
* responses:
* 200:
* description: The User object that has the requested `id`.
* schema:
* $ref: '#/definitions/User'
*
* 400:
* description: Invalid URI `id` parameter.
* schema:
* $ref: '#/definitions/UserInputError'
*
* 401:
* description: User is not logged-in.
* schema:
* $ref: '#/definitions/AuthError'
*
* 403:
* description: User is logged-in but has no permission to see the requested User.
* schema:
* $ref: '#/definitions/PermissionError'
*
* 404:
* description: The requested User is not found in the DB.
* schema:
* $ref: '#/definitions/NoFoundError'
*/
router.get('/api/v1/users/:id',
isLoggedIn(),
async (ctx) => {
const userId = ctx.params.id;
if (!isValidUuidV4(userId)) {
throw new HttpError(
400,
'INVALID_INPUT_ID',
`User id "${userId}" is invalid UUID v4`
);
}
/* A user wants to see its own data */
if (ctx.state.user.id === userId) {
if (!ctx.state.userPermissions.includes('canReadOwnUser')) {
throw new HttpError(
403,
'NO_PERMISSION',
'You must have permission "canReadOwnUser" in order to access your own User data'
);
}
ctx.body = ctx.state.user;
return;
}
if (!ctx.state.userPermissions.includes('canReadOthersUser')) {
throw new HttpError(
403,
'NO_PERMISSION',
`You must have permission "canReadOthersUser" in order to access others User data`
);
}
const user = await ctx.postgres.Users
.findOne({
where: {
id: userId,
},
})
.then((response) => response && typeof response.toJSON === 'function' ? response.toJSON() : response);
if (!user) {
throw new HttpError(
404,
'USER_NO_FOUND',
`Unable to find user with id "${userId}"`
);
}
ctx.body = user;
}
);
/**
* @swagger
* /api/v1/users/{id}:
* put:
* description: Updating User that has the requested `id` and then we'll return his updated info.
*
* produces:
* - application/json
*
* parameters:
* - name: Authorization
* in: header
* description: Authorization header with JWT
* required: true
* type: string
*
* - in: path
* name: id
* type: string
* format: uuid
* required: true
* description: The `id` of the User we want to update
*
* - in: body
* name: update
* type: object
* description: Holds only the info that we want to update.
* For example, if we want to update only the User firstName, then we'll send `{"firstName":"New first name"}`
* example: {"firstName": "Johnny"}
* parameters:
* firstName:
* type: string
* lastName:
* type: string
* email:
* type: string
* format: email
* password:
* type: string
*
* responses:
* 200:
* description: The User object that has the requested `id`.
* schema:
* $ref: '#/definitions/User'
*
* 400:
* description: Invalid URI `id` parameter or invalid request body.
* schema:
* $ref: '#/definitions/UserInputError'
*
* 401:
* description: User is not logged-in.
* schema:
* $ref: '#/definitions/AuthError'
*
* 403:
* description: User is logged-in but has no permission to update the requested User.
* schema:
* $ref: '#/definitions/PermissionError'
*/
router.put('/api/v1/users/:id',
isLoggedIn(),
async (ctx) => {
const userId = ctx.params.id;
if (!isValidUuidV4(userId)) {
throw new HttpError(
400,
'INVALID_INPUT_ID',
`User id "${userId}" is invalid UUID v4`
);
}
if (!ctx.request.body) {
throw new HttpError(
400,
'INVALID_INPUT',
`Please send JSON as an input`
);
}
const {firstName, lastName, email, password} = ctx.request.body;
if (ctx.state.user.id !== userId) {
throw new HttpError(
403,
'NO_PERMISSION',
'You must cannot update the user of someone else'
);
}
/* Checks for updating the logged-in user First name */
if (firstName && ctx.state.user.firstName !== firstName) {
if (!ctx.state.userPermissions.includes('canWriteOwnFirstName')) {
throw new HttpError(
403,
'NO_PERMISSION',
'You must have permission "canWriteOwnFirstName" in order to update your first name'
);
}
if (typeof firstName !== 'string') {
throw new HttpError(
400,
'INVALID_INPUT_FIRST_NAME',
`"${firstName}" is invalid first name`
);
}
await ctx.postgres.Users
.update(
{firstName},
{where: {id: userId}}
);
ctx.state.user.firstName = firstName;
}
/* Checks for updating the logged-in user Last name */
if (lastName && ctx.state.user.lastName !== lastName) {
if (!ctx.state.userPermissions.includes('canWriteOwnLastName')) {
throw new HttpError(
403,
'NO_PERMISSION',
'You must have permission "canWriteOwnLastName" in order to update your last name'
);
}
if (typeof lastName !== 'string') {
throw new HttpError(
400,
'INVALID_INPUT_LAST_NAME',
`"${lastName}" is invalid last name`
);
}
await ctx.postgres.Users
.update(
{lastName},
{where: {id: userId}}
);
ctx.state.user.lastName = lastName;
}
/* Checks for updating the logged-in user Email */
if (email && ctx.state.user.email !== email) {
if (!ctx.state.userPermissions.includes('canWriteOwnEmail')) {
throw new HttpError(
403,
'NO_PERMISSION',
'You must have permission "canWriteOwnEmail" in order to update your email'
);
}
if (!isValidEmail(email)) {
throw new HttpError(
400,
'INVALID_INPUT_EMAIL',
`"${email}" is invalid email`
);
}
await ctx.postgres.Users
.update(
{email},
{where: {id: userId}}
);
ctx.state.user.email = email;
}
/* Checks for setting new Password for the logged-in user */
const hashedPassword = crypto
.createHmac('sha256', ctx.state.user.id)
.update(String(password))
.digest('hex');
if (password && ctx.state.user.hashedPassword !== hashedPassword) {
if (!ctx.state.userPermissions.includes('canWriteOwnPassword')) {
throw new HttpError(
403,
'NO_PERMISSION',
'You must have permission "canWriteOwnPassword" in order to update your password'
);
}
if (!isValidPassword(password)) {
throw new HttpError(
400,
'INVALID_INPUT_PASSWORD',
`"${password}" is invalid password`
);
}
await ctx.postgres.Users
.update(
{hashedPassword},
{where: {id: userId}}
);
ctx.state.user.hashedPassword = hashedPassword;
}
if (ctx.state.userPermissions.includes('canReadOwnUser')) {
ctx.body = ctx.state.user;
} else {
ctx.body = {};
}
}
);
/**
* @swagger
* /api/v1/users/{id}/invitations:
* get:
* description: Returns a list of all Invitations that User with the requested `id` have.
* This list will include Invitations that the user is accepted, kicked, or pending to accept.
*
* produces:
* - application/json
*
* parameters:
* - name: Authorization
* in: header
* description: Authorization header with JWT
* required: true
* type: string
*
* - in: path
* name: id
* type: string
* format: uuid
* required: true
* description: The `id` of the User we want to see all Invitations
*
* responses:
* 200:
* description: List of all Invitations for User that has the requested `id`.
* schema:
* type: array
* items:
* $ref: '#/definitions/Invitation'
*
* 400:
* description: Invalid URI `id` parameter.
* schema:
* $ref: '#/definitions/UserInputError'
*
* 401:
* description: User is not logged-in.
* schema:
* $ref: '#/definitions/AuthError'
*
* 403:
* description: User is logged-in but has no permission to see the Invitations
* schema:
* $ref: '#/definitions/PermissionError'
*/
router.get('/api/v1/users/:id/invitations',
isLoggedIn(),
async (ctx) => {
const userId = ctx.params.id;
if (!isValidUuidV4(userId)) {
throw new HttpError(
400,
'INVALID_INPUT_ID',
`User id "${userId}" is invalid UUID v4`
);
}
if (ctx.state.user.id !== userId) {
throw new HttpError(
403,
'NO_PERMISSION',
'You must cannot get a list of group invitations for someone else'
);
}
if (!ctx.state.userPermissions.includes('canReadJoinedGroups')) {
throw new HttpError(
403,
'NO_PERMISSION',
'You must have permission "canReadJoinedGroups" in order to get a list of your group invitations'
);
}
const invitations = await ctx.postgres.Invitations
.findAll({
where: {toUserId: userId},
})
.then((responses) => Array.isArray(responses) ? responses.map((response) => response.toJSON()) : []);
ctx.body = invitations;
}
);
module.exports = router;
|