-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
634 lines (565 loc) · 14.2 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
import { PrismaClient } from "@prisma/client"
import { ApolloServer, AuthenticationError, makeExecutableSchema } from 'apollo-server'
import { rule, shield, and, or, not } from 'graphql-shield'
import { GraphQLJSON } from 'graphql-scalars'
import * as dotenv from 'dotenv'
import jwt from 'jsonwebtoken'
const bcrypt = require('bcryptjs');
const jwtSecret: string = process.env.APP_SECRET!
const accessTokenExpires: any = parseInt(process.env.ACCESS_TOKEN_EXPIRES!)
const refreshTokenExpires: any = parseInt(process.env.REFRESH_TOKEN_EXPIRES!)
import { applyMiddleware } from "graphql-middleware";
const prisma = new PrismaClient();
const typeDefs = `#graphql
scalar JSON
type City {
id: Int
postMeta: [PostMeta]
name: String
createdAt: String
User: [User]
favByUsers: [User]
}
type PostMeta {
id: Int
post: Post
}
type Post {
id: Int
content: String
title: String
user: User
userId: Int
createdAt: String
"""
One of the f.f.:
- '-1: archived'
- '1: active'
- '0: draft'
"""
state: Int
reference: Post
referencedBy: [Post]
reactionCount: JSON
mediaUpload: MediaUpload
postAnalytic: [PostAnalytic]
viewCount: Int
"Returns a report type such as 'Lighting Issues', 'Road Development Work', etc..."
type: ValueMeta
city: City
comments: [Comment]
}
type Comment {
id: Int
content: String
user: User
createdAt: String
state: Int
reactionCount: JSON
mediaUpload: MediaUpload
post: Post
parentComment: Comment
childComments: [Comment]
}
type User {
id: Int
createdAt: String
account: Account
posts: [Post]
postAnalytic: [PostAnalytic]
avatarUrl: String
defaultCity: City
cityId: Int
firstName: String
lastName: String
birthdate: String
isAnonymous: Boolean
displayName: String
}
type MediaUpload {
id: Int
postId: Int
post: Post
mediaUrls: [String]
"no usage yet - TBA"
metadata: String
}
type PostAnalytic {
id: Int
type: String
post: Post
postId: Int
value: String
user: User
userId: Int
}
type ValueMeta {
id: String
value: String
}
type Account {
username: String
emailAddress: String
"""
One of the f.f.:
- 'Moderator'
- 'Citizen'
"""
type: String
"""
One of the f.f.:
- -1: Suspended
- 0: Archive
- 1: Active
"""
status: Int
user: User
}
type Mutation {
createPost(
userId: Int
title: String!
content: String!
cityId: Int!
type: String
) : Post!
createComment(
content: String!
userId: Int!
postId: Int
commentId: Int
): Comment!
userLogin(
username: String!
password: String!
): AuthPayload!
signUp(
username: String!
password: String!
emailAddress: String
birthdate: String!
firstName: String
lastName: String
isAnonymous: Boolean!
): AuthPayload
refreshToken(
userId: Int!
): AuthPayload!
}
type Query {
allUsers: [User!]!
allPosts: [Post!]!
options: [ValueMeta!]!
user(id: Int!): User!
post(id: Int!): Post
searchUser(search: String): [User]
}
type AuthPayload {
user: User
token: String!
refreshToken: String!
expiresIn: Int,
tokenType: String
}
`;
function generateAccessToken(user: any, account: any) {
return jwt.sign({
user: {
userId: user.id,
role: account.type,
}
},
jwtSecret,
{
'expiresIn': accessTokenExpires
})
}
function generateRefreshToken(accessToken: String, user: any) {
const tokenParts = accessToken.split('.')
return jwt.sign({
accessTokenTrail: tokenParts[tokenParts.length - 1],
user: {
userId: user.id,
}
},
jwtSecret, {
'expiresIn': refreshTokenExpires
})
}
const resolvers = {
JSON: GraphQLJSON,
Query: {
allPosts: () => {
return prisma.post.findMany({
include: {
user: true,
type: true,
city: true,
mediaUpload: true,
comments: {
include: {
childComments: {
include: {
childComments: true
}
}
}
}
}
});
},
allUsers: () => {
return prisma.user.findMany({});
},
options: () => {
return prisma.valueMeta.findMany({})
},
user: (parent: any, args: any, ctx: any, info: any) => {
return prisma.user.findUnique({
where: {
id: args.id
}
})
},
post: (parent: any, args: any, ctx: any, info: any) => {
return prisma.post.findUnique({
where: {
id: args.id
}
})
},
searchUser: (parent: any, args: any, ctx: any, info: any) => {
return prisma.user.findMany({
where: {
OR: [
{
firstName: {
contains: args.search,
mode: 'insensitive'
}
},
{
lastName: {
contains: args.search,
mode: 'insensitive'
}
},
{
displayName: {
contains: args.search,
mode: 'insensitive'
}
},
]
}
})
}
},
Mutation: {
createPost: (parent: any, args: any, ctx: any, info: any) => {
return ctx.prisma.post.create({
data: {
user: {
connect: {
id: args.userId
}
},
title: args.title,
content: args.content,
state: 1,
reactionCount: {
like: 0
},
type: {
connect: {
id: args.type
}
},
city: {
connect: {
id: args.cityId
}
},
}
})
},
createComment: (parent: any, args: any, ctx: any, info: any) => {
let data = {}
if ('postId' in args) {
data = {
user: {
connect: {
id: args.userId
}
},
content: args.content,
state: 1,
reactionCount: {
like: 0
},
post: {
connect: {
id: args.postId
}
},
}
} else if ('commentId') {
data = {
user: {
connect: {
id: args.userId
}
},
content: args.content,
state: 1,
reactionCount: {
like: 0
},
parentComment: {
connect: {
id: 'commentId' in args ? args.commentId : undefined
}
}
}
}
return ctx.prisma.comment.create({
data
})
},
userLogin: async (parent: any, args: any, ctx: any, info: any) => {
const account = await ctx.prisma.account.findUnique({
where: {
username: args.username
}
})
if (!account) {
throw new Error('Account not found, please try again.')
}
const valid = await bcrypt.compare(args.password, account.password)
if (!valid) {
throw new AuthenticationError('Invalid account credentials, please try again.');
}
const user = await ctx.prisma.user.findUnique({
where: {
id: account.userId
}
})
if (!user) {
throw new Error('User info not found.')
}
const token = generateAccessToken(user, account)
const refreshToken = generateRefreshToken(token, user)
return {
user,
token,
tokenType: 'bearer',
expiresIn: accessTokenExpires,
refreshToken
}
},
signUp: async (parent: any, args: any, ctx: any, info: any) => {
let displayName = null
if (args.isAnonymous) {
displayName = args.username
} else {
displayName = `${args.firstName} ${args.lastName}`
}
const account = await prisma.account.create({
data: {
username: args.username,
password: await bcrypt.hash(args.password, 10),
emailAddress: args.emailAddress,
type: 'Citizen',
status: 1,
user: {
create: {
firstName: 'firstName' in args ? args.firstName : null,
lastName: 'lastName' in args ? args.lastName : null,
displayName: displayName,
isAnonymous: args.isAnonymous,
birthdate: args.birthdate,
cityId: 1
}
}
}
})
if (!account) {
throw new Error('Something went wrong creating account, please try again.')
}
const user = await prisma.user.findUnique({
where: {
id: account.userId!
}
})
if (!user) {
throw new Error('Something went wrong creating user info, please try again.')
}
const token = generateAccessToken(user, account)
const refreshToken = generateRefreshToken(token, user)
return {
user,
token,
tokenType: 'bearer',
expiresIn: accessTokenExpires,
refreshToken
}
},
refreshToken: async (parent: any, args: any, ctx: any, info: any) => {
const isVerified = verifyRefreshToken(ctx.refreshToken, args.userId, ctx.accessToken)
if (isVerified) {
const user = await ctx.prisma.user.findUnique({
where: {
id: args.userId
},
include: {
account: true
}
})
const token = generateAccessToken(user, user.account)
const refreshToken = generateRefreshToken(token, user)
return {
user: user,
token: token,
tokenType: 'bearer',
expiresIn: accessTokenExpires,
refreshToken: refreshToken
}
} else {
return new AuthenticationError('Refresh token expired. Please login again.')
}
}
}
};
const isAuthenticated = rule({ cache: 'contextual' })(
async (parent, args, ctx, info) => {
return ctx.user !== null && ctx.user !== undefined && !ctx.isExpired
},
)
const isCitizen = rule({ cache: 'contextual' })(
async (parent, args, ctx, info) => {
return ctx.user.role === 'Citizen'
},
)
const isModerator = rule({ cache: 'contextual' })(
async (parent, args, ctx, info) => {
return ctx.user.role === 'Moderator'
},
)
const hasRefreshToken = rule({ cache: 'contextual' })(
async (parent, args, ctx, info) => {
return ctx.refreshToken !== null && ctx.refreshToken !== undefined
},
)
const isTokenExpired = rule({ cache: 'contextual' })(
async (parent, args, ctx, info) => {
return ctx.refreshToken !== undefined && ctx.isExpired
},
)
const permissions = shield({
Query: {
allPosts: and(isAuthenticated, isCitizen),
allUsers: isAuthenticated,
options: isAuthenticated,
user: isAuthenticated,
post: isAuthenticated
},
Mutation: {
userLogin: not(isAuthenticated),
signUp: not(isAuthenticated),
createPost: isAuthenticated,
createComment: isAuthenticated,
refreshToken: hasRefreshToken
},
})
const schema = applyMiddleware(
makeExecutableSchema({
typeDefs,
resolvers
}),
permissions
)
const server = new ApolloServer({
schema: schema,
context: ({ req }) => {
const token = req.headers.authorization || '';
const refreshToken = req.headers["x-refresh-token"];
const decoded: any = decodeToken(token) || {}
let ctx: any = { prisma }
let decodedToken = null;
if ('err' in decoded && decoded['err'] !== null && decoded['err'] !== undefined) {
const tokenStatus: Number = getTokenStatus(decoded['err'])
if (tokenStatus === 1) {
ctx['isExpired'] = true
}
} else if (decoded['decoded'] !== undefined) {
decodedToken = decoded['decoded']
}
const user = getAuthenticatedUser(decodedToken)
if (refreshToken !== undefined) {
ctx['refreshToken'] = refreshToken
ctx['accessToken'] = decoded['token']
}
if (user) {
ctx['user'] = user
ctx['isExpired'] = false
}
return ctx
}
});
function getTokenStatus(err: any): Number {
if (err) {
const errName = err['name']
if (errName == 'TokenExpiredError') {
return 1
}
}
return 0
}
function getAuthenticatedUser(decoded: any) {
if (decoded !== undefined && decoded !== null && 'user' in decoded) {
const user = decoded['user']
return user
}
return null
}
function decodeToken(tokenStr: String) {
if (tokenStr == '') {
return null;
}
const tokenArr = tokenStr.split(' ')
if (tokenArr.length > 1 && tokenArr[0].toLowerCase() === 'bearer') {
const token = tokenArr[1]
return jwt.verify(token, jwtSecret, (err: any, decoded: any) => {
return { err, decoded, token }
})
}
return null
}
function verifyRefreshToken(token: any, userId: any, accessToken: any): any {
return jwt.verify(token, jwtSecret, (err: any, decoded: any) => {
if (err === undefined) {
const errName = err['name']
if (errName == 'TokenExpiredError') {
return false
}
} else {
const user = decoded['user']
if (decoded !== undefined && user !== undefined) {
if (user['userId'] !== undefined && user['userId'] !== null) {
const tokenUserId = user['userId']
const accessTokenTrail = decoded['accessTokenTrail']
const tokenParts = accessToken.split('.')
if (tokenParts.length === 3) {
return tokenUserId === userId && tokenParts[2] === accessTokenTrail
}
}
}
return false
}
return false
})
}
server.listen({ port: 4000 }).then((url) => {
console.log(`🚀 Server ready at port ${url.port}`);
dotenv.config();
});