-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.js
More file actions
706 lines (655 loc) · 19.5 KB
/
database.js
File metadata and controls
706 lines (655 loc) · 19.5 KB
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
const mongoose = require('mongoose')
const { SchemaTypes } = require('mongoose')
const bcrypt = require('bcryptjs')
const Schema = mongoose.Schema
// --- Schemas ---
const userSchema = new Schema({
first_name: String,
last_name: String,
username: {
type: String,
unique: true
},
email: {
type: String,
unique: true
},
password: String,
skill: String,
bio: String,
profile_header: String,
extended_bio: String,
icon_url: String,
social_links: [{ site: String, url: String }],
contact_email: String,
show_contact_email: Boolean,
contact_schedule: String,
created_on: Date,
login_history: [{timestamp: Date, userAgent: String}]
})
const projectSchema = new Schema({
name: String,
slug: String,
description: String,
description_short: String,
created_on: Date,
website: String,
category: String,
email: String,
logo_url: String,
banner_url: String,
image_url: String,
socials: [{ site: String, url: String }],
reviews: [{ author: {type: SchemaTypes.ObjectID, ref: 'guildcoder_users'}, content: String }],
owners: [ {type: SchemaTypes.ObjectID, ref: 'guildcoder_users'} ],
collaborators: [ {type: SchemaTypes.ObjectID, ref: 'guildcoder_users'} ]
})
const guildSchema = new Schema({
name: String,
slug: String,
description: String,
description_short: String,
website: String,
contact_email: String,
image_url: String,
owners: [ {type: SchemaTypes.ObjectID, ref: 'guildcoder_users'} ],
members: [ {type: SchemaTypes.ObjectID, ref: 'guildcoder_users'} ],
projects: [ {type: SchemaTypes.ObjectID, ref: 'guildcoder_projects'} ],
messages: [{author: {type: SchemaTypes.ObjectID, ref: 'guildcoder_users'}, message: String, sent_on: Date, edited: Boolean}],
created_on: Date
})
const conversationSchema = new Schema({
name: String,
participants: [ {type: SchemaTypes.ObjectID, ref: 'guildcoder_users'} ],
messages: [{author: {type: SchemaTypes.ObjectID, ref: 'guildcoder_users'}, message: String, sent_on: Date, edited: Boolean}],
created_on: Date
})
// --- Models ---
const User = mongoose.model('guildcoder_users', userSchema)
const Project = mongoose.model('guildcoder_projects', projectSchema)
const Guild = mongoose.model('guildcoder_guilds', guildSchema)
const Conversation = mongoose.model('guildcoder_conversations', conversationSchema)
// --- Functions ---
exports.connectToDB = (connectionString) => {
mongoose.connect(connectionString)
}
// -- User-Related Functions --
/*
* Creates a new user with the given information.
*/
exports.createUser = (firstName, lastName, u_username, u_email, u_password, u_skill) => {
// Encrypt the password using bcrypt and save user
return bcrypt.genSalt(10).then((Salt) => {
return bcrypt.hash(u_password, Salt).then((hash) => {
// Create a user object
const newUser = new User({
first_name: firstName,
last_name: lastName,
username: u_username,
email: u_email,
password: hash,
skill: u_skill,
bio: 'Hi! 👋 ',
profile_header: 'Welcome to my profile!',
extended_bio: 'Here are some of my projects. Check them out!',
icon_url: '/images/default-user-icon.png',
social_links: [],
contact_email: u_email,
show_contact_email: false,
contact_schedule: 'Send me a message. I will try to get back to you quickly.',
created_on: new Date(),
})
// Commit it to the database
return newUser.save().then((user) => {
process.stdout.write(`Successfully added new user ${user.username}\n`)
return user
}).catch((reason) => {
process.stdout.write(`ERROR (when saving new user): ${reason}\n`)
return false
})
}).catch((err) => {
// Issue creating hashed password
process.stdout.write(`ERROR (while hashing password): ${err}`)
return false
})
}).catch((err) => {
// Issue creating hashed object salt
process.stdout.write(`ERROR (while generating password salt): ${err}`)
return false
})
}
/*
* Gets the user with the provided id.
*/
exports.getUserById = (u_Id) => {
// Fetch information about the user with the given id
return User.findOne({ _id: u_Id }).exec().then((user) => {
// User found.
return user
}).catch((reason) => {
// No user found with this id.
console.log(reason)
return false
})
}
/*
* Gets the users with the provided ids.
*/
exports.getUsersById = (u_Ids) => {
// Fetch information about the users with the given ids
return User.find({ _id: u_Ids }).exec().then((users) => {
// User found.
return users
}).catch((reason) => {
// No users found with these ids.
console.log(reason)
return false
})
}
/*
* Gets the user with the provided email.
*/
exports.getUserByEmail = (u_email) => {
// Fetch information about the user with the given email
return User.findOne({ email: u_email }).exec().then((user) => {
// User found.
return user
}).catch((reason) => {
// No user found with this email.
console.log(reason)
return false
})
}
/*
* Gets the user with the provided username.
*/
exports.getUserByUsername = (u_username) => {
// Fetch information about the user with the given username
return User.findOne({ username: u_username }).exec().then((user) => {
// User found.
return user
}).catch((reason) => {
console.log(reason)
// No user found with this username.
return false
})
}
/*
* Gets the users with the provided usernames.
*/
exports.getUsersByUsername = (u_usernames) => {
// Fetch information about the users with the given ids
return User.find({ username: u_usernames }).exec().then((users) => {
// Users found.
return users
}).catch((reason) => {
// No users found with these names.
console.log(reason)
return false
})
}
/*
* Gets an array of all existing users.
*/
exports.getAllUsers = () => {
// Fetch an array of all users
return User.find({ }).exec().then((users) => {
// Users found.
return users
}).catch((reason) => {
console.log(reason)
// Error retrieving users.
return false
})
}
/*
* Checks if the corresponding password matches that of the provided email.
*/
exports.authUser = (u_email, u_password, log_history = false, u_agent="Unknown") => {
// Fetch information about the user with the given email
return User.findOne({ email: u_email }).exec().then((user) => {
// User found. Check password.
return bcrypt.compare(u_password, user.password).then((isMatch) => {
// Check if it is a match
if (isMatch) {
// Update the user's login history.
if (log_history) {
let newLogin = {timestamp: new Date(), userAgent: String(u_agent)}
// Add the new login to the user's login history
return User.updateOne(
{ email: u_email },
{ $push: {login_history: newLogin} }
).exec().then(()=>{
// Auth was successful and login history updated.
user.login_history.push(newLogin)
return [true, user]
}).catch((reason) => {
user.login_history.push(newLogin)
// Auth was successful, but failed to update the user's login history.
process.stdout.write(`ERROR (while updating user's login history): ${reason}\n`)
return [true, user]
})
} else {
// Auth was successful. Return user without logging to user's history.
return [true, user]
}
} else {
// User's authentication was invalid.
return [false, undefined]
}
})
}).catch((reason) => {
console.log(reason)
// No user found with this email.
return [false]
})
}
/*
* Updates the user with the given email address.
*/
exports.updateUser = (u_email, object) => {
return bcrypt.genSalt(10).then((Salt) => {
return bcrypt.hash(object.password, Salt).then((hash) => {
if (object.password.length > 0) {
object.password = hash;
} else {
object.password = object.old_password
}
delete object.old_password
// Update User
return User.updateOne(
{ email: u_email },
{ $set: object }
).exec().then(() => {
// Updated user successfully
return true
}).catch((reason) => {
// Failed to update the user
process.stdout.write(`ERROR (while updating user): ${reason}\n`)
return false
})
}).catch((err) => {
// Issue creating hashed password
process.stdout.write(`ERROR (while hashing password): ${err}`)
return false
})
}).catch((err) => {
// Issue creating hashed object salt
process.stdout.write(`ERROR (while generating password salt): ${err}`)
return false
})
}
// -- Project-Related Functions --
/*
* Creates a new project with the given information.
*/
exports.createProject = (p_name, p_slug, p_description, p_description_short, p_website, p_category, p_email, p_owners) => {
// Create a project object
const newProject = new Project({
name: p_name,
slug: p_slug,
description: p_description,
description_short: p_description_short,
created_on: new Date(),
website: p_website,
category: p_category,
email: p_email,
logo_url: 'https://via.placeholder.com/100x100',
banner_url: 'https://via.placeholder.com/2300x500',
image_url: 'https://via.placeholder.com/400x300',
socials: [],
reviews: [],
owners: p_owners,
collaborators: []
})
// Commit it to the database
return newProject.save().then((project) => {
process.stdout.write(`Successfully added new project ${project.name}\n`)
return project
}).catch((reason) => {
process.stdout.write(`ERROR (when saving new project): ${reason}\n`)
return false
})
}
/*
* Gets the project with the provided slug.
*/
exports.getProjectBySlug = (p_slug) => {
// Fetch information about the project with the given slug
return Project.findOne({ slug: p_slug }).populate('owners').populate('collaborators').populate('reviews.author').exec().then((project) => {
// Project found.
return project
}).catch((reason) => {
console.log(reason)
// No project found with this slug.
return false
})
}
/*
* Gets the projects that have the provided user as the owner.
*/
exports.getProjectsByOwner = (owner) => {
// Fetch information about the projects with the given owner
return Project.find({ owners: owner }).populate('owners').populate('collaborators').populate('reviews.author').exec().then((projects) => {
// Projects found.
return projects
}).catch(() => {
// No projects found with this owner.
return false
})
}
/*
* Gets the projects that have the provided user as a collaborator.
*/
exports.getProjectsByCollaborator = (collaborator) => {
// Fetch information about the projects with the given owner
return Project.find({ collaborators: collaborator }).populate('owners').populate('collaborators').populate('reviews.author').exec().then((projects) => {
// Projects found.
return projects
}).catch(() => {
// No projects found with this collaborator.
return false
})
}
/*
* Gets an array of all existing projects.
*/
exports.getAllProjects = () => {
// Fetch an array of all users
return Project.find({}).populate('owners').populate('collaborators').populate('reviews.author').exec().then((projects) => {
// Projects found.
return projects
}).catch((reason) => {
console.log(reason)
// Error retrieving projects.
return false
})
}
/*
* Updates the project with the given slug.
*/
exports.updateProject = (p_slug, object) => {
return Project.updateOne(
{ slug: p_slug },
{ $set: object }
).exec().then(() => {
// Updated project successfully
return true
}).catch((reason) => {
// Failed to update the project
process.stdout.write(`ERROR (while updating project): ${reason}\n`)
return false
})
}
/*
* Adds a review to the project.
*/
exports.addReview = (p_slug, reviewObject) => {
return Project.updateOne(
{ slug: p_slug },
{$push: {reviews: reviewObject}}
).exec().then(() => {
// Added review successfully
return true
}).catch((reason) => {
// Failed to add the review
process.stdout.write(`ERROR (while adding review): ${reason}\n`)
return false
})
}
/*
* Adds a collaborator to the project.
*/
exports.addCollaborator = (p_slug, userObject) => {
return Project.updateOne(
{ slug: p_slug },
{$push: {collaborators: userObject}}
).exec().then(() => {
// Added collaborator successfully
return true
}).catch((reason) => {
// Failed to add the collaborator
process.stdout.write(`ERROR (while adding collaborator): ${reason}\n`)
return false
})
}
// -- Guild-Related Functions --
/*
* Creates a new guild with the given information.
*/
exports.createGuild = (g_name, g_slug, g_description, g_description_short, g_website, g_email, g_owners) => {
// Create a guild object
const newGuild = new Guild({
name: g_name,
slug: g_slug,
description: g_description,
description_short: g_description_short,
website: g_website,
owners: g_owners,
contact_email: g_email,
image_url: "https://via.placeholder.com/400x300",
members: [],
projects: [],
messages: [],
created_on: new Date()
})
// Commit it to the database
return newGuild.save().then((guild) => {
process.stdout.write(`Successfully added new guild ${guild.name}\n`)
return guild
}).catch((reason) => {
process.stdout.write(`ERROR (when saving new guild): ${reason}\n`)
return false
})
}
/*
* Gets the guild with the provided slug.
*/
exports.getGuildBySlug = (g_slug) => {
// Fetch information about the guild with the given slug
return Guild.findOne({ slug: g_slug }).populate('owners').populate('members').populate('projects').populate('messages.author').exec().then((guild) => {
// Guild found.
return guild
}).catch((reason) => {
console.log(reason)
// No guild found with this slug.
return false
})
}
/*
* Gets the guilds that have the provided user as the owner.
*/
exports.getGuildsByOwner = (owner) => {
// Fetch information about the guilds with the given owner
return Guild.find({ owners: owner }).populate('owners').populate('members').populate('projects').populate('messages.author').exec().then((guilds) => {
// Guilds found.
return guilds
}).catch(() => {
// No guilds found with this owner.
return false
})
}
/*
* Gets the guilds that have the provided user as a member.
*/
exports.getGuildsByMember = (member) => {
// Fetch information about the guilds with the given member
return Guild.find({ members: member }).populate('owners').populate('members').populate('projects').populate('messages.author').exec().then((guilds) => {
// Guilds found.
return guilds
}).catch(() => {
// No guilds found with this member.
return false
})
}
/*
* Gets an array of all existing guilds.
*/
exports.getAllGuilds = () => {
// Fetch an array of all guilds
return Guild.find({}).populate('owners').populate('members').populate('projects').populate('messages.author').exec().then((guilds) => {
// Guilds found.
return guilds
}).catch((reason) => {
console.log(reason)
// Error retrieving guilds.
return false
})
}
/*
* Updates the guild with the given slug.
*/
exports.updateProject = (g_slug, object) => {
return Guild.updateOne(
{ slug: g_slug },
{ $set: object }
).exec().then(() => {
// Updated guild successfully
return true
}).catch((reason) => {
// Failed to update the guild
process.stdout.write(`ERROR (while updating guild): ${reason}\n`)
return false
})
}
/*
* Adds a message to the guild.
*/
exports.addMessage = (g_slug, messageObject) => {
return Guild.updateOne(
{ slug: g_slug },
{$push: {messages: messageObject}}
).exec().then(() => {
// Added message successfully
return true
}).catch((reason) => {
// Failed to add the message
process.stdout.write(`ERROR (while adding message): ${reason}\n`)
return false
})
}
/*
* Adds a member to the guild.
*/
exports.addGuildMember = (g_slug, userObject) => {
return Guild.updateOne(
{ slug: g_slug },
{$push: {members: userObject}}
).exec().then(() => {
// Added member successfully
return true
}).catch((reason) => {
// Failed to add the member
process.stdout.write(`ERROR (while adding member): ${reason}\n`)
return false
})
}
// -- Conversation-Related Functions --
/*
* Creates a new conversation with the given information.
*/
exports.createConversation = (c_name, c_participants) => {
// Create a conversation object
const newConversation = new Conversation({
name: c_name,
participants: c_participants,
messages: [],
created_on: new Date()
})
// Commit it to the database
return newConversation.save().then((conversation) => {
process.stdout.write(`Successfully added new conversation ${conversation.name}\n`)
return conversation
}).catch((reason) => {
process.stdout.write(`ERROR (when saving new conversation): ${reason}\n`)
return false
})
}
/*
* Gets the conversation that has the provided id.
*/
exports.getConversationById = (id) => {
// Fetch information about the conversation with the given id
return Conversation.find({ _id: id }).populate('participants').populate('messages.author').exec().then((conversation) => {
// Conversation found.
return conversation[0]
}).catch(() => {
// No conversation found with this id.
return false
})
}
/*
* Gets the conversations that have the provided user as a participant.
*/
exports.getConversationsByParticipant = (participant) => {
// Fetch information about the conversations with the given participant
return Conversation.find({ participants: participant }).populate('participants').populate('messages.author').exec().then((conversations) => {
// Conversations found.
return conversations
}).catch(() => {
// No conversations found with this participant.
return false
})
}
/*
* Gets an array of all existing conversations.
*/
exports.getAllConversations = () => {
// Fetch an array of all conversations
return Conversation.find({}).populate('participants').populate('messages.author').exec().then((conversations) => {
// Conversations found.
return conversations
}).catch((reason) => {
console.log(reason)
// Error retrieving conversations.
return false
})
}
/*
* Updates the conversation with the given id.
*/
exports.updateConversation = (c_id, object) => {
return Conversation.updateOne(
{ _id: c_id },
{ $set: object }
).exec().then(() => {
// Updated conversation successfully
return true
}).catch((reason) => {
// Failed to update the conversation
process.stdout.write(`ERROR (while updating conversation): ${reason}\n`)
return false
})
}
/*
* Adds a message to the conversation.
*/
exports.addConversationMessage = (c_id, messageObject) => {
return Conversation.updateOne(
{ _id: c_id },
{$push: {messages: messageObject}}
).exec().then(() => {
// Added message successfully
return true
}).catch((reason) => {
// Failed to add the message
process.stdout.write(`ERROR (while adding message): ${reason}\n`)
return false
})
}
/*
* Adds a member to the conversation.
*/
exports.addConversationParticipant = (c_id, userObject) => {
return Conversation.updateOne(
{ _id: c_id },
{$push: {participants: userObject}}
).exec().then(() => {
// Added conversation participant successfully
return true
}).catch((reason) => {
// Failed to add the member
process.stdout.write(`ERROR (while adding conversation participant): ${reason}\n`)
return false
})
}