-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathDatabaseHandler.js
357 lines (285 loc) · 9.18 KB
/
DatabaseHandler.js
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
const { hash, compare } = require('bcrypt');
const shortId = require('shortid');
const flakeId = require('flakeid');
const r = require('rethinkdbdash')({
db: 'union'
});
const idGenerator = new flakeId({
timeOffset: (2018 - 1970) * 31536000 * 1000
});
function generateSnowflake () {
return idGenerator.gen().toString();
}
/**
* Creates a user object with the provided username and password, and stores it in the DB
* @param {String} username The username of the account to create
* @param {String} password The password of the account to create
*/
async function createUser (username, password) {
const id = generateSnowflake();
const discriminator = await rollDiscriminator(username, id);
if (!discriminator) {
throw new Error('Cannot generate unique discrim. Try a different username.');
}
await r.table('users').insert({
id,
username,
discriminator,
password: await hash(password, 10),
createdAt: Date.now(),
servers: [],
online: false
});
return `${username}#${discriminator}`;
}
async function rollDiscriminator (username, id) {
const discriminator = id.substring(id.length - 4); // hahayes lazy discrim generating method
const isDiscrimTaken = await r.table('users').filter({ username, discriminator }).count().gt(0);
if (!isDiscrimTaken) {
return discriminator;
} else {
return null;
}
}
/**
* Creates a server with the provided name and iconUrl
* @param {String} name The name of the server
* @param {String} iconUrl A URL leading to an image to be used as the server's icon
* @returns {Object} The created server
*/
async function createServer (name, iconUrl, owner) {
const id = generateSnowflake();
const server = {
id,
name,
iconUrl,
owner
};
await r.table('servers').insert(server);
await addMemberToServer(owner, id);
return getServer(id);
}
/**
* Adds a member to a server
* @param {String} username The member to add to the server
* @param {Number} id The server to add the member to
*/
async function addMemberToServer (username, id) {
const user = await r.table('users').get(username);
const server = await r.table('servers').get(id);
if (!user || !server || user.servers.includes(id)) {
return;
}
await r.table('users').get(username).update({
servers: r.row('servers').append(id)
});
}
/**
* Validates username and password from the provided auth
* @param {String} auth The authentication type + base64-encoded credentials
* @returns {(Null|Object)} The user object if authentication was successful, otherwise null
*/
async function authenticate (auth) {
if (!auth) {
return null;
}
const [type, creds] = auth.split(' ');
if ('Basic' !== type || !creds) {
return null;
}
const [username, password] = Buffer.from(creds, 'base64').toString().split(':');
const [name, discriminator] = username ? username.split('#') : [];
if (!username || !password || !name || !discriminator) {
return null;
}
const user = await r.table('users').filter({ username: name, discriminator }).nth(0).default(null);
if (!user) {
return null;
}
const isPasswordValid = await compare(password, user.password);
if (!isPasswordValid) {
return null;
}
return user;
}
/**
* Retrieves a list of users in the server with the provided serverId
* @param {Number} serverId The user to get the servers of
* @returns {Array<Object>} A list of users in the server
*/
function getUsersInServer (serverId) {
return r.table('users').filter(u => u('servers').contains(serverId)).without(['servers', 'password']);
}
/**
* Checks whether a user is in a server
* @param {String} userId The user to check the servers of
* @param {Number} serverId The server to check the user's presence of
* @returns {Boolean} Whether the user is in the server
*/
function isInServer (userId, serverId) {
return r.table('users').get(userId)('servers').contains(serverId).default(false);
}
/**
* Gets a list of servers that the given user is in
* @param {String} username Username of the user to retrieve the servers of
* @returns {Array<Object>} A list of servers that the user is in
*/
async function getServersOfUser (username) {
const user = await r.table('users').get(username);
if (!user) {
return []; // This shouldn't happen but you can never be too careful
}
const servers = await r.table('servers')
.getAll(...user.servers)
.merge(server => ({
members: r.table('users').filter(u => u('servers').contains(server('id'))).without(['servers', 'password']).coerceTo('array')
}));
return servers;
}
/**
* Updates the online status of the given user
* @param {String} username Username of the user to update the presence of
* @param {Boolean} online Whether the user is online or not
*/
function updatePresenceOf (username, online) {
r.table('users').get(username).update({ online }).run();
}
/**
* Resets the online status of all members. Useful when the server is shutting down
*/
function resetPresenceStates () {
return r.table('users').update({ online: false });
}
/**
* Updates the online status of the given user
* @param {String} username Username of the user to update the presence of
* @param {Boolean} online Whether the user is online or not
*/
function getUser (username) {
return r.table('users').get(username);
}
/**
* Retrieves a user without private properties
* @param {String} username The name of the user to retrieve
* @returns {Object|Null} The user, if they exist
*/
function getMember (username) {
return r.table('users').get(username).without(['password', 'servers']);
}
/**
* Removes a member from a server
* @param {String} username The name of the user to kick from the server
* @param {Number} serverId The server to remove the member from
*/
function removeMemberFromServer (username, serverId) {
return r.table('users')
.get(username)
.update({
servers: r.row('servers').difference([serverId])
});
}
/**
* Returns the number of servers that the given user owns
* @param {String} username The username to filter servers against
* @returns {Number} The amount of servers the user owns
*/
function getOwnedServers (username) {
return r.table('servers').filter(s => s('owner').eq(username)).count();
}
/**
* Retrieves a server from the database by its ID
* @param {Number} serverId The ID of the server to retrieve
* @returns {Object|Null} The server, if it exists
*/
function getServer (serverId) {
return r.table('servers')
.get(serverId)
.merge(server => ({
members: r.table('users').filter(u => u('servers').contains(server('id'))).without(['servers', 'password']).coerceTo('array')
}));
}
/**
* Deletes a server by its ID
* @param {Number} serverId The ID of the server to delete
*/
async function deleteServer (serverId) {
await r.table('servers').get(serverId).delete();
await r.table('invites').filter(inv => inv('serverId').eq(serverId)).delete();
await r.table('users')
.filter(u => u('servers').contains(serverId))
.update({
servers: r.row('servers').difference([serverId])
});
}
/**
* Checks if the given user is the owner of the given server
* @param {String} username The name of the user to check
* @param {Number} serverId The id of the server to check
* @returns {Boolean} Whether or not the user owns the server
*/
function ownsServer (username, serverId) {
return r.table('servers').get(serverId)('owner').eq(username).default(false);
}
/**
* Checks whether the server exists
* @param {Number} serverId The id of the server to check
* @returns {Boolean} Whether the server exists or not
*/
function serverExists (serverId) {
if (!serverId) {
return false;
}
return r.table('servers').get(serverId).coerceTo('bool').default(false);
}
/**
* Generates an invite for the specified server
* @param {Number} serverId The server ID to associate the invite with
* @param {String} inviter The user who generated the invite
* @returns {String} The invite code
*/
async function generateInvite (serverId, inviter) {
const invite = shortId();
await r.table('invites').insert({
id: invite,
serverId,
inviter
});
return invite;
}
/**
* Returns an invite object from the provided code
* @param {String} code The code to lookup
* @returns {Object|Null} The invite, if it exists
*/
function getInvite (code) {
return r.table('invites').get(code);
}
function storeMessage (id, author) {
r.table('messages').insert({ id, author }).run();
}
function retrieveMessage (id) {
return r.table('messages').get(id);
}
module.exports = {
addMemberToServer,
authenticate,
createUser,
createServer,
deleteServer,
generateInvite,
getInvite,
getMember,
getOwnedServers,
getUser,
getUsersInServer,
getServer,
getServersOfUser,
isInServer,
ownsServer,
removeMemberFromServer,
resetPresenceStates,
retrieveMessage,
serverExists,
storeMessage,
updatePresenceOf,
};