-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
398 lines (351 loc) · 12.6 KB
/
db.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
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
const firebase = require("./firebase.js");
const db = firebase.database();
const usersRef = db.ref('users');
const postsRef = db.ref('posts');
const categoriesRef = db.ref('categories');
// Middleware. Checks if a session cookie corresponding to a user exists.
// Redirects to '/login' if none is found.
async function auth(req, res, next) {
const user = await getUser(req);
if (user === undefined)
return res.redirect('/login');
console.log("Authorized.");
next();
}
// Called on login. Creates session cookie for client.
// If new user (not in db), push to db.
async function setSessionCookie(req, res) {
try {
//console.log("Cookie Set Requested");
const idToken = req.body.idToken.toString();
// Set session expiration to 5 days.
const expiresIn = 60 * 60 * 24 * 5 * 1000;
firebase.auth().verifyIdToken(idToken).then(async () => {
const sessionCookie = await firebase.auth().createSessionCookie(idToken, { expiresIn });
res.cookie("session", sessionCookie);
const claims = await firebase.auth().verifySessionCookie(sessionCookie, true);
const email = claims.email;
/*
// Check Email Suffix, if not fuhsd, logout
if (!email.endsWith("@student.fuhsd.org")) {
console.log("Rejected Email: ", email);
return res.redirect('/sessionLogout');
}
*/
// If none such user exists
const user = await getUserFromClaims(claims);
if (user === undefined) {
console.log("User not found, creating new user");
const newUser = {
"email": email,
"name": claims.name,
"admin": false,
"categories": { "announcements": true },
};
usersRef.push(newUser);
}
res.redirect('/');
})
} catch (e) {
console.log("ERROR ON COOKIE SET, ", e)
//if it throws an error, that means the token is invalid
res.status(403).send('UNAUTHORIZED REQUEST!');
}
}
async function getSessionClaims(req) {
// If no cookies exist
if (!req.cookies)
return undefined;
let session_cookie = req.cookies.session;
// If no session cookie exists
if (session_cookie === undefined)
undefined;
// Fetch Session claims
try {
return firebase.auth().verifySessionCookie(session_cookie, true);
} catch (error) {
console.log(error);
return undefined;
}
}
function createCategory(req) {
const newCategoryName = req.body.newCategoryName;
const members = req.body.members.split(",").map(str => str.trim()).filter(str => str != "");
const moderators = req.body.moderators.split(",").map(str => str.trim()).filter(str => str != "");
for (email in members)
if (getUserByEmail(email) == undefined)
return `None such user '${email}'`;
for (email in moderators)
if (getUserByEmail(email) == undefined)
return `None such user '${email}'`;
const category = members.length > 0 ? {
private: true,
members: members,
moderators: moderators,
} : {
private: false,
moderators: moderators,
};
let pair = {};
pair[newCategoryName] = category;
categoriesRef.update(pair);
}
async function getCategories() {
const snapshot = await categoriesRef.once('value')
let categories = [];
snapshot.forEach((data) => {
categories[data.key] = data.val();
})
return categories;
}
// Sanity check of post. Current checks:
// -> Bad attachments (injection / inapporpiate)
// -> Unauthorized post on category.
async function validatePost(post) {
// Filter out bad attachment links. (Security)
if (post.attachments !== undefined)
for (const attachment of post.attachments)
if (!attachment.startsWith("https://"))
return "Invalid link";
// Check Category privilege
// unnecessary with new bulletin filter in create post form
/*
let auth = true;
await categoriesRef.once("value", snapshot => {
snapshot.forEach((data) => {
if (data.key != post.category) return;
let category = data.val();
// Retro-activity for old categories
// with new db likely won't be needed in the future ...
if (category.private == undefined) return;
auth = category.private ? category.members.includes(post.author) : true;
});
});
if (!auth)
return `Not a member of category '${post.category}'`;
*/
return undefined;
}
async function pushPost(post) {
console.log(post);
let err = await validatePost(post);
if (err != undefined) {
console.log("Invalid post. Error: ", err);
return err;
}
let newPost = {
title: post.title,
text: post.text,
author: post.author,
authorName: post.authorName,
postTime: new Date().valueOf(),
category: post.category,
attachments: post.attachments,
approved: false
};
if (!newPost.title || !newPost.text) {
return;
}
postsRef.push(newPost);
}
async function approvePost(postKey) {
console.log("approving post", postKey)
return postsRef.child(postKey).once("value")
.then(data => {
if (data.key != postKey) return;
const post = data.val();
post.approved = true;
data.ref.update(post);
})
.catch(e => undefined)
}
async function getUserFromClaims(claims) {
if (claims == undefined) {
console.log("Got undefined claims at 'getUserFromClaims'");
return undefined;
}
const email = claims.email;
// Query user by email
return getUserByEmail(email);
}
async function getUserByEmail(email) {
// Query user by email
return (
usersRef.orderByChild('email').equalTo(email).limitToLast(1).once("value")
.then((snapshot) => {
const val = snapshot.val();
const userID = Object.keys(val)[0];
return val[userID];
}).catch((error) => {
return undefined;
})
);
}
async function getUser(req) {
try {
return getUserFromClaims(await getSessionClaims(req));
} catch (error) {
return undefined;
}
}
async function getPostByKey(key) {
return postsRef.child(key).once("value")
.then(data => {
const post = data.val();
post.key = data.key;
return post;
})
.catch(e => undefined);
}
// Fetches a list of posts.
// NOTE: Draft function, later revisions may use an actual algorithm to tailor the posts
// to the user.
function getPosts(category, amount, offset, only_approved, only_unapproved) {
if (!(only_approved ^ only_unapproved))
console.error("'getPosts' error, can't have both only-unapproved and only-approved")
if (!amount) amount = 2;
if (amount > 25) amount = 25;
if (!offset) offset = 0;
return category ?
postsRef.orderByChild('category').equalTo(category).limitToLast(offset + amount).once("value")
.then((snapshot) => {
let posts = [];
snapshot.forEach((data) => {
const post = data.val();
post.key = data.key;
if (only_approved) {
if ( post.approved) posts.push(post);
} else if (only_unapproved) {
if (!post.approved) posts.push(post);
}
});
posts.sort((a, b) => b.postTime - a.postTime);
console.log(offset);
return posts.slice(offset);
}).catch(e => undefined) :
postsRef.orderByChild('postTime').limitToLast(offset + amount).once("value")
.then(snapshot => {
let posts = [];
snapshot.forEach((data) => {
const post = data.val();
post.key = data.key;
if (only_approved) {
if (post.approved) posts.push(post);
} else if (only_unapproved) {
if (!post.approved) posts.push(post);
}
});
posts.sort((a, b) => b.postTime - a.postTime);
return posts.slice(offset);
})
.catch(e => undefined);
}
async function getPostsByCategory (category, offset=0, amount=5) {
console.log(category);
const posts = getPosts(category, amount, offset, true);
return posts;
}
// Gets posts of categories configured by the user. Given an offset
async function getPostsForUser(user, offset = 0, amount = 5) {
let categories = Object.keys(user.categories).map(category => category);
const posts = [];
for (const category of categories) {
let amount = 20;
const categoryPosts = await getPosts(category, amount, 0, true);
posts.push(...categoryPosts);
};
posts.sort((a, b) => b.postTime - a.postTime);
console.log(posts.length);
return posts.slice(offset, offset+amount);
}
// Gets posts where the author is the specified user
function getPostsByUser(user, approved_only) {
return postsRef.orderByChild('author').equalTo(user.email).once("value")
.then((snapshot) => {
let posts = [];
snapshot.forEach(data => {
const post = data.val();
if (!approved_only || post.approved)
posts.push(data.val());
});
return posts.reverse();
}).catch(e => undefined)
}
async function pinPost (category, postKey) {
categoriesRef.child(category).once("value").then(data => {
let category = data.val();
category.pin = postKey;
data.ref.update(category);
}).catch(e => undefined);
}
async function searchPosts(query, bulletin) {
query = query.toLowerCase();
let posts = [];
if (bulletin) {
let snapshot = await (postsRef.orderByChild('category').equalTo(bulletin)).once("value");
snapshot.forEach( data => posts.push(data.val()) );
posts = posts.filter(function(post) {
return (post.text.toLowerCase().includes(query) || post.title.toLowerCase().includes(query)) && post.approved;
});
} else {
let snapshot = await postsRef.once("value");
snapshot.forEach( data => posts.push(data.val()) );
posts = posts.filter(function(post) {
return (post.text.toLowerCase().includes(query) || post.title.toLowerCase().includes(query)) && post.approved;
});
}
return posts.reverse();
}
async function getCategory(category) {
return (
categoriesRef.child(category).once("value")
.then(data => data.val())
.catch(e => undefined)
);
}
// Adds a category to the user's category list.
async function addCategory(req, newCategory) {
const user = await getUser(req);
// Get snapshot referencing user, edit values, then update.
await usersRef.orderByChild('email').equalTo(user.email).limitToLast(1).once("value", snapshot => {
const val = snapshot.val();
const userID = Object.keys(val)[0];
if (val[userID].categories == undefined) val[userID].categories = {};
val[userID].categories[newCategory] = true;
snapshot.ref.update(val);
});
}
async function removeCategory(req, category) {
const user = await getUser(req);
// Get snapshot referencing user, edit values, then update.
await usersRef.orderByChild('email').equalTo(user.email).limitToLast(1).once("value", function(snapshot) {
const val = snapshot.val();
const userID = Object.keys(val)[0];
if (val[userID].categories == undefined) val[userID].categories = {};
delete val[userID].categories[category];
snapshot.ref.update(val);
});
}
module.exports = {
// Session & Authentications
auth: auth,
setSessionCookie: setSessionCookie,
// Queries
getUser: getUser,
getUserByEmail: getUserByEmail,
getPosts: getPosts,
getPostByKey: getPostByKey,
getPostsByUser: getPostsByUser,
getPostsByCategory: getPostsByCategory,
getCategory: getCategory,
addCategory: addCategory,
removeCategory: removeCategory,
getPostsForUser: getPostsForUser,
searchPosts: searchPosts,
// DB setting & modifying
pushPost: pushPost,
pinPost: pinPost,
createCategory: createCategory,
getCategories: getCategories,
approvePost: approvePost,
}