-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
648 lines (574 loc) · 20.8 KB
/
index.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
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
import { Router } from 'itty-router';
import Users from './classes/Users';
import Posts from './classes/Posts';
import requestPostId from './types/requestPostId';
import requestCommentId from './types/requestCommentId';
import requestLocals from './types/requestLocals';
import ValidationError from './classes/ValidationError';
import validateJson from './components/validateJson';
import validateParametersCheckMissing from './components/validateParametersCheckMissing';
import verifyPhotoUpload from './components/verifyPhotoUpload';
import validateReactionType from './components/validateReactionType';
import uuidValidateV1 from './components/uuidValidateV1';
import authJwt from './components/authJwt';
import verifyJwt from './components/verifyJwt';
declare const POSTS: KVNamespace;
declare const USERS: KVNamespace;
// Create a new router
const router = Router();
// cors headers
function cors(response: Response) {
response.headers.set(
'Access-Control-Allow-Origin',
'https://cf-summer-2022-nextjs.pages.dev',
);
response.headers.set('Access-Control-Allow-Credentials', 'true');
response.headers.set('Access-Control-Allow-Methods', 'POST, GET, DELETE');
response.headers.set('Access-Control-Allow-Headers', 'Content-Type');
response.headers.set('Access-Control-Max-Age', '86400');
return response;
}
// return 200 when client is getting server options during cors
router.options('*', () => {
return cors(new Response('All good!'));
});
// get all posts
router.get('/posts', async () => {
const listOfKeys = await POSTS.list();
const listOfPosts = [];
for (const key of listOfKeys.keys) {
listOfPosts.push(await POSTS.get(key.name));
}
return cors(new Response('[' + listOfPosts.toString() + ']'));
});
// register user if no user under that username, otherwise return user
router.get('/users/:userName', async (request) => {
if (request.params && request.params.userName) {
const storedUser = await USERS.get(request.params.userName);
if (storedUser) {
const parsedUser = JSON.parse(storedUser);
const user = new Users(parsedUser.userName, parsedUser.avatarBackgroundColor);
return cors(new Response(user.toString()));
} else {
const authResponse: any = await authJwt(request.params.userName);
const cookie = authResponse.headers.get('set-cookie');
const jwtToken = cookie.split('token=')[1].split(';')[0];
const user = new Users(request.params.userName);
await USERS.put(request.params.userName, user.toString());
const response = new Response('User has been registered!');
response.headers.set(
'set-cookie',
`token=${jwtToken}; Path=/; SameSite=None; HttpOnly; secure;`,
);
return cors(response);
}
} else {
return cors(new Response('Please include a userName in parameters', { status: 400 }));
}
});
// verify postId middleware
router.all('/posts/:postId', (request: requestPostId) => {
if (!uuidValidateV1(request.params.postId)) {
return cors(new Response('Invalid postId', { status: 400 }));
}
});
// get post by postId
router.get('/posts/:postId', async (request: requestPostId) => {
const post = await POSTS.get(request.params.postId);
if (!post) {
return cors(new Response('No post found under that id', { status: 404 }));
}
return cors(new Response(post));
});
// create posts, takes in title, content and optional photo parameter as well as username, creates post with these params
// if user account doesn't exist on post creation, create one for them if username is not taken.
// otherwise if the jwt is valid and the jwt username and request username parameter match, proceed.
router.post('/posts', async (request: any) => {
try {
// create response "success object", allowing us to set headers for it
let response = new Response('success');
let user;
let verificationResponse = '';
const requestJson = await validateJson(request);
if (!requestJson.photo) {
requestJson.photo = '';
} else {
verifyPhotoUpload(requestJson.photo);
}
const validParams = ['title', 'content', 'photo', 'username'];
validateParametersCheckMissing(validParams, Object.keys(requestJson));
// verify jwt if request headers contain cookie
try {
if (request.headers.get('Cookie')) {
const cookie = request.headers.get('Cookie');
const jwtToken = cookie.split('token=')[1].split(';')[0];
// verifyjwt is a GET http request
verificationResponse = await verifyJwt(jwtToken);
}
} catch (error) {
return cors(new Response('Invalid Token!', { status: 401 }));
}
const storedUser = await USERS.get(requestJson.username);
// if user not found set-cookie for that user
if (!storedUser) {
const authResponse: any = await authJwt(requestJson.username);
const cookie = authResponse.headers.get('set-cookie');
const jwtToken = cookie.split('token=')[1].split(';')[0];
user = new Users(requestJson.username);
await USERS.put(requestJson.username, user.toString());
response.headers.set(
'set-cookie',
`token=${jwtToken}; Path=/; SameSite=None; HttpOnly; secure;`,
);
} else {
// if user does exist check if JWT user is equal to the user in posted json
const parsedUser = JSON.parse(storedUser);
user = new Users(parsedUser.userName, parsedUser.avatarBackgroundColor);
if (requestJson.username !== verificationResponse) {
return cors(
new Response('You cannot make posts that are not under your name', {
status: 401,
}),
);
}
}
const newPost = new Posts(
requestJson.title,
requestJson.username,
user.getAvatarBackgroundColor(),
requestJson.content,
requestJson.photo,
[],
{
'😀': [],
'😂': [],
'😭': [],
'🥰': [],
'😍': [],
'🤢': [],
},
[],
Date.now().toString(),
);
await POSTS.put(newPost.getPostId(), newPost.toString());
return cors(response);
} catch (error) {
if (error instanceof ValidationError) {
return cors(new Response(error.message, { status: error.code }));
}
}
});
// middleware that verifies jwt token by sending jwt to go authentication server over cloudflare tunnel
router.all('*', async (request: any) => {
try {
if (request.headers.get('Cookie')) {
const cookie = request.headers.get('Cookie');
const jwtToken = cookie.split('token=')[1].split(';')[0];
// verifyjwt is a GET http request
const verificationResponse: any = await verifyJwt(jwtToken);
request.locals = {
userName: verificationResponse,
};
} else {
return cors(new Response('Missing authentication header!', { status: 401 }));
}
} catch (error) {
return cors(new Response('Invalid Token!', { status: 401 }));
}
});
// verify user, since user has already been verified by middleware, simply return userName as response
router.get('/verify', async (request: requestLocals) => {
return cors(new Response(request.locals.userName));
});
// logout user, set cookie to max-age 0
router.get('/users/:userName/logout', async (request: any) => {
const cookie = request.headers.get('Cookie');
const response = new Response('Sucessfully logged out!');
response.headers.set(
'set-cookie',
`${cookie}; max-age=0; Path=/; SameSite=None; HttpOnly; secure;`,
);
return cors(response);
});
// delete post by postId if user is author of that post
router.delete('/posts/:postId', async (request: requestPostId) => {
const storedPost = await POSTS.get(request.params.postId);
if (!storedPost) {
return cors(new Response('No post found under that id', { status: 404 }));
}
const parsedPost = JSON.parse(storedPost);
const post = new Posts(
parsedPost.title,
parsedPost.userName,
parsedPost.userBackgroundColor,
parsedPost.content,
parsedPost.photo,
parsedPost.upVotes,
parsedPost.reactions,
parsedPost.comments,
parsedPost.createdAt,
request.params.postId,
);
if (request.locals.userName === post.getUserName()) {
await POSTS.delete(request.params.postId);
return cors(new Response('Sucessfully deleted post!'));
} else {
return cors(new Response("You can't delete posts you don't own!", { status: 401 }));
}
});
// upvote post, each user can only upvote a post once
router.post('/posts/:postId/upvote', async (request: requestPostId) => {
try {
const storedPost = await POSTS.get(request.params.postId);
if (!storedPost) {
return cors(new Response('No post found under that id', { status: 404 }));
}
const parsedPost = JSON.parse(storedPost);
const post = new Posts(
parsedPost.title,
parsedPost.userName,
parsedPost.userBackgroundColor,
parsedPost.content,
parsedPost.photo,
parsedPost.upVotes,
parsedPost.reactions,
parsedPost.comments,
parsedPost.createdAt,
request.params.postId,
);
await post.addUpvote(request.locals.userName);
return cors(new Response('Sucessfully upvoted post!'));
} catch (error) {
if (error instanceof ValidationError) {
return cors(new Response(error.message, { status: error.code }));
}
}
});
// remove upvote from post
router.delete('/posts/:postId/upvote', async (request: requestPostId) => {
try {
const storedPost = await POSTS.get(request.params.postId);
if (!storedPost) {
return cors(new Response('No post found under that id', { status: 404 }));
}
const parsedPost = JSON.parse(storedPost);
const post = new Posts(
parsedPost.title,
parsedPost.userName,
parsedPost.userBackgroundColor,
parsedPost.content,
parsedPost.photo,
parsedPost.upVotes,
parsedPost.reactions,
parsedPost.comments,
parsedPost.createdAt,
request.params.postId,
);
await post.removeUpvote(request.locals.userName);
return cors(new Response('Sucessfully removed upvote on post!'));
} catch (error) {
if (error instanceof ValidationError) {
return cors(new Response(error.message, { status: error.code }));
}
}
});
// react to post with one of the valid emoji types, this validation is done by validateReactionType.
// each user can react to post once with every emoji
router.post('/posts/:postId/react', async (request: requestPostId) => {
try {
const requestJson = await validateJson(request);
const validParams = ['type'];
validateParametersCheckMissing(validParams, Object.keys(requestJson));
// can't use .split("") because emoji
const reactionType = requestJson.type.split(/(?!$)/u)[0];
validateReactionType(reactionType);
const storedPost = await POSTS.get(request.params.postId);
if (!storedPost) {
return cors(new Response('No post found under that id', { status: 404 }));
}
const parsedPost = JSON.parse(storedPost);
const post = new Posts(
parsedPost.title,
parsedPost.userName,
parsedPost.userBackgroundColor,
parsedPost.content,
parsedPost.photo,
parsedPost.upVotes,
parsedPost.reactions,
parsedPost.comments,
parsedPost.createdAt,
request.params.postId,
);
await post.addReaction(request.locals.userName, reactionType);
return cors(new Response('Sucessfully reacted to post!'));
} catch (error) {
if (error instanceof ValidationError) {
return cors(new Response(error.message, { status: error.code }));
}
}
});
// remove reaction from post, type is passed in so we know which emoji they react with initally
router.delete('/posts/:postId/react', async (request: requestPostId) => {
try {
const requestJson = await validateJson(request);
const validParams = ['type'];
validateParametersCheckMissing(validParams, Object.keys(requestJson));
// can't use .split("") because emoji
const reactionType = requestJson.type.split(/(?!$)/u)[0];
validateReactionType(reactionType);
const storedPost = await POSTS.get(request.params.postId);
if (!storedPost) {
return cors(new Response('No post found under that id', { status: 404 }));
}
const parsedPost = JSON.parse(storedPost);
const post = new Posts(
parsedPost.title,
parsedPost.userName,
parsedPost.userBackgroundColor,
parsedPost.content,
parsedPost.photo,
parsedPost.upVotes,
parsedPost.reactions,
parsedPost.comments,
parsedPost.createdAt,
request.params.postId,
);
await post.removeReaction(request.locals.userName, reactionType);
return cors(new Response('Sucessfully removed reaction from post!'));
} catch (error) {
if (error instanceof ValidationError) {
return cors(new Response(error.message, { status: error.code }));
}
}
});
// comment on post needs content parameter
router.post('/posts/:postId/comments', async (request: requestPostId) => {
try {
const requestJson = await validateJson(request);
const validParams = ['content'];
validateParametersCheckMissing(validParams, Object.keys(requestJson));
const storedUser = await USERS.get(request.locals.userName);
if (!storedUser) {
return cors(new Response('User not found', { status: 404 }));
}
const parsedUser = JSON.parse(storedUser);
const user = new Users(parsedUser.userName, parsedUser.avatarBackgroundColor);
const storedPost = await POSTS.get(request.params.postId);
if (!storedPost) {
return cors(new Response('No post found under that id', { status: 404 }));
}
const parsedPost = JSON.parse(storedPost);
const post = new Posts(
parsedPost.title,
parsedPost.userName,
parsedPost.userBackgroundColor,
parsedPost.content,
parsedPost.photo,
parsedPost.upVotes,
parsedPost.reactions,
parsedPost.comments,
parsedPost.createdAt,
request.params.postId,
);
await post.addComment(
request.locals.userName,
user.getAvatarBackgroundColor(),
requestJson.content,
);
return cors(new Response('Sucessfully commented on post!'));
} catch (error) {
if (error instanceof ValidationError) {
return cors(new Response(error.message, { status: error.code }));
}
}
});
// verify postId middleware
router.all('/posts/:postId/comments/:commentId', (request: requestCommentId) => {
if (!uuidValidateV1(request.params.commentId)) {
return cors(new Response('Invalid commentId', { status: 400 }));
}
});
// delete post comment by commentId and postId
router.delete('/posts/:postId/comments/:commentId', async (request: requestCommentId) => {
try {
const storedPost = await POSTS.get(request.params.postId);
if (!storedPost) {
return cors(new Response('No post found under that id', { status: 404 }));
}
const parsedPost = JSON.parse(storedPost);
const post = new Posts(
parsedPost.title,
parsedPost.userName,
parsedPost.userBackgroundColor,
parsedPost.content,
parsedPost.photo,
parsedPost.upVotes,
parsedPost.reactions,
parsedPost.comments,
parsedPost.createdAt,
request.params.postId,
);
await post.removeComment(request.locals.userName, request.params.commentId);
return cors(new Response('Sucessfully deleted comment on post!'));
} catch (error) {
if (error instanceof ValidationError) {
return cors(new Response(error.message, { status: error.code }));
}
}
});
// upvote comment by commentId and postId, each comment can only be upvoted once by each user
router.post(
'/posts/:postId/comments/:commentId/upvote',
async (request: requestCommentId) => {
try {
const storedPost = await POSTS.get(request.params.postId);
if (!storedPost) {
return cors(new Response('No post found under that id', { status: 404 }));
}
const parsedPost = JSON.parse(storedPost);
const post = new Posts(
parsedPost.title,
parsedPost.userName,
parsedPost.userBackgroundColor,
parsedPost.content,
parsedPost.photo,
parsedPost.upVotes,
parsedPost.reactions,
parsedPost.comments,
parsedPost.createdAt,
request.params.postId,
);
await post.addCommentUpVote(request.locals.userName, request.params.commentId);
return cors(new Response('Sucessfully upvoted commented!'));
} catch (error) {
if (error instanceof ValidationError) {
return cors(new Response(error.message, { status: error.code }));
}
}
},
);
// remove comment upvote by commentId and postId
router.delete(
'/posts/:postId/comments/:commentId/upvote',
async (request: requestCommentId) => {
try {
const storedPost = await POSTS.get(request.params.postId);
if (!storedPost) {
return cors(new Response('No post found under that id', { status: 404 }));
}
const parsedPost = JSON.parse(storedPost);
const post = new Posts(
parsedPost.title,
parsedPost.userName,
parsedPost.userBackgroundColor,
parsedPost.content,
parsedPost.photo,
parsedPost.upVotes,
parsedPost.reactions,
parsedPost.comments,
parsedPost.createdAt,
request.params.postId,
);
await post.removeCommentUpVote(request.locals.userName, request.params.commentId);
return cors(new Response('Sucessfully removed upvote on comment!'));
} catch (error) {
if (error instanceof ValidationError) {
return cors(new Response(error.message, { status: error.code }));
}
}
},
);
// react to comment by commentId and postId, user can react once with each reaction type
router.post(
'/posts/:postId/comments/:commentId/react',
async (request: requestCommentId) => {
try {
const requestJson = await validateJson(request);
const validParams = ['type'];
validateParametersCheckMissing(validParams, Object.keys(requestJson));
const reactionType = requestJson.type.split(/(?!$)/u)[0];
validateReactionType(reactionType);
const storedPost = await POSTS.get(request.params.postId);
if (!storedPost) {
return cors(new Response('No post found under that id', { status: 404 }));
}
const parsedPost = JSON.parse(storedPost);
const post = new Posts(
parsedPost.title,
parsedPost.userName,
parsedPost.userBackgroundColor,
parsedPost.content,
parsedPost.photo,
parsedPost.upVotes,
parsedPost.reactions,
parsedPost.comments,
parsedPost.createdAt,
request.params.postId,
);
await post.addCommentReaction(
request.locals.userName,
request.params.commentId,
reactionType,
);
return cors(new Response('Sucessfully reacted to comment!'));
} catch (error) {
if (error instanceof ValidationError) {
return cors(new Response(error.message, { status: error.code }));
}
}
},
);
// remove reaction to comment by commentId and postId
// type is specified so we know what type they initally reacted with
router.delete(
'/posts/:postId/comments/:commentId/react',
async (request: requestCommentId) => {
try {
const requestJson = await validateJson(request);
const validParams = ['type'];
validateParametersCheckMissing(validParams, Object.keys(requestJson));
const reactionType = requestJson.type.split(/(?!$)/u)[0];
validateReactionType(reactionType);
const storedPost = await POSTS.get(request.params.postId);
if (!storedPost) {
return cors(new Response('No post found under that id', { status: 404 }));
}
const parsedPost = JSON.parse(storedPost);
const post = new Posts(
parsedPost.title,
parsedPost.userName,
parsedPost.userBackgroundColor,
parsedPost.content,
parsedPost.photo,
parsedPost.upVotes,
parsedPost.reactions,
parsedPost.comments,
parsedPost.createdAt,
request.params.postId,
);
await post.removeCommentReaction(
request.locals.userName,
request.params.commentId,
reactionType,
);
return cors(new Response('Sucessfully removed reaction from comment!'));
} catch (error) {
if (error instanceof ValidationError) {
return cors(new Response(error.message, { status: error.code }));
}
}
},
);
/*
This is the last route we define, it will match anything that hasn't hit a route we've defined
above, therefore it's useful as a 404 (and avoids us hitting worker exceptions, so make sure to include it!).
Visit any page that doesn't exist (e.g. /foobar) to see it in action.
*/
router.all('*', () => cors(new Response('404, not found!', { status: 404 })));
/*
This snippet ties our worker to the router we defined above, all incoming requests
are passed to the router where your routes are called and the response is sent.
*/
addEventListener('fetch', (e) => {
e.respondWith(router.handle(e.request));
});