This repository was archived by the owner on May 22, 2025. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
1809 lines (1759 loc) · 67.5 KB
/
Copy pathindex.js
File metadata and controls
1809 lines (1759 loc) · 67.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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//sudo -u postgres psql <- Personal reference only, this gets a SQL console session
///// APP IMPORTS /////
import express from 'express';
import path from 'path';
import chalk from 'chalk';
import sql from './db.js';
import crypto from 'crypto';
import util from 'util';
import {nanoid} from 'nanoid';
import fs from 'fs';
import * as archiver from 'archiver';
import pg from 'pg';
import d from './config.json' assert { type: "json" };
import https from 'https';
import http from 'http';
import compression from 'compression';
import { minify_sync } from 'terser';
import { minify } from 'html-minifier-terser';
//////////////////////
// Host our web app and define our APIs
const app = express();
app.use(express.json({limit: '1gb'})); // Set max attachment file size here.
app.use(compression());
const devMode = d['devmode'];
const port = devMode ? 8080 : 80;
// Connect secondary connection to SQL.
const {Client} = pg;
const client = new Client({
connectionString: `postgres://${d.username}:${d.password}@${d.host}:${d.port}/${d.database}`
});
console.clear();
const c = {
white: msg => {
console.log(msg);
},
notice: msg => {
console.log(chalk.yellow(msg));
},
boldDanger: msg => {
console.log(chalk.bgRed(msg));
},
error: msg => {
console.error(msg)
console.log(chalk.red(msg))
},
runBigProcess: msg => {
console.log(chalk.bgMagenta(msg))
},
success: msg => {
console.log(chalk.bgGreen(msg));
},
successText: msg => {
console.log(chalk.green(msg));
},
inverse: msg => {
console.log(chalk.inverse(msg));
}
};
let serve = {};
function str(data){
return JSON.stringify(data);
}
/**
* Generates a password hash and salt for storing in the DB.
* @param {string} password User inputted password
* @param {string} salt Salt, generates a random salt if length < 16, default = random
* @return Object
*/
async function generatePasswordHash(password, salt = ''){
try{
const randomBytes = util.promisify(crypto.randomBytes);
if (salt.length < 16){
salt = (await randomBytes(8)).toString('hex');
}
const hash = crypto.createHash('sha512').update(password + salt).digest('hex');
return {hash: hash, salt: salt};
}
catch(e){
console.error(e);
}
}
/**
* Resets the DB entirely. DANGEROUS!!
*/
async function reset(){
c.boldDanger('\n Deleting and resetting DB.. ');
try {
console.log(await sql`DROP TABLE TaskMessages CASCADE;`);
}
catch(e){
c.notice(e.message);
}
try {
console.log(await sql`DROP TABLE TagsTables CASCADE;`);
}
catch(e){
c.notice(e.message);
}
try {
console.log(await sql`DROP TABLE Tags CASCADE;`);
}
catch(e){
c.notice(e.message);
}
try {
console.log(await sql`DROP TABLE UserGroups CASCADE;`);
}
catch(e){
c.notice(e.message);
}
try {
console.log(await sql`DROP TABLE UserSessionToken CASCADE;`);
}
catch(e){
c.notice(e.message);
}
try {
console.log(await sql`DROP TABLE Tasks CASCADE;`);
}
catch(e){
c.notice(e.message);
}
try {
console.log(await sql`DROP TABLE TaskViews CASCADE;`);
}
catch(e){
c.notice(e.message);
}
try {
console.log(await sql`DROP TABLE Groups CASCADE;`);
}
catch(e){
c.notice(e.message);
}
try {
console.log(await sql`DROP TABLE Users CASCADE;`);
}
catch(e){
c.notice(e.message);
}
try {
console.log(await sql`DROP TABLE Attachments CASCADE;`);
fs.rmSync(path.resolve('attachments'), {recursive: true, force: true});
}
catch(e){
c.notice(e.message);
}
}
/**
* Checks the postgres database to ensure tables are of correct specifications.
* If not, we can initialize or create what's missing.
*/
async function dbCheck(){
c.runBigProcess('\n' + ' Running DB initialization.. ');
// Create attachments table
try {
await sql`CREATE TABLE Attachments(
AttachmentID SERIAL PRIMARY KEY,
FileName TEXT NOT NULL,
DateAdded TIMESTAMP NOT NULL,
ModifiedDate TIMESTAMP NOT NULL,
FilePath TEXT NOT NULL
);`
const p = path.resolve('default-pfp.jpeg');
const attachmentID = await sql`
INSERT INTO Attachments(FileName, DateAdded, ModifiedDate, FilePath) VALUES
(${path.basename(p)}, ${Date.now()}, ${Date.now()}, ${p}) RETURNING AttachmentID;
`;
if (attachmentID[0].attachmentid != 1){
c.boldDanger(' This app requires SERIAL type to start at 1, please adjust your table settings and try again. ');
process.exit();
}
fs.mkdirSync(path.resolve('attachments'));
c.white('* Attachments table created.');
c.white(' * Default attachments loaded.');
}
catch(e){
if (e.message.includes('already exists')){
c.notice(`* Attachments table already exists, skipping...`);
}
else{
c.error('* ' + e);
}
}
// Create users table
try {
await sql`CREATE TABLE Users(
UserID VARCHAR(21) NOT NULL PRIMARY KEY,
Username VARCHAR(100) NOT NULL,
Admin BOOLEAN NOT NULL,
PfpAttachmentID INT,
Email VARCHAR(320),
PhoneNumber INT,
PasswordHash VARCHAR(128) NOT NULL,
PasswordSalt VARCHAR(16) NOT NULL,
FOREIGN KEY (PfpAttachmentID) REFERENCES Attachments(AttachmentID)
ON DELETE SET NULL
ON UPDATE CASCADE
);`
// Add the default admin user
const adminCreds = await generatePasswordHash('admin');
await sql`
INSERT INTO Users(UserID, Username, Admin, PasswordHash, PasswordSalt, PfpAttachmentID)
VALUES (${nanoid()}, 'admin', TRUE, ${adminCreds.hash}, ${adminCreds.salt}, ${1});
`;
c.white('* Users table created.');
}
catch(e){
if (e.message.includes('already exists')){
c.notice(`* Users table already exists, skipping...`);
}
else{
c.error('* PostgreSQL Error:' + e.messasge);
}
}
// Create UserSessionToken table
try {
await sql`CREATE TABLE UserSessionToken(
Token VARCHAR(21) NOT NULL PRIMARY KEY,
IssuedDate TIMESTAMP NOT NULL,
ExpireDate TIMESTAMP,
UserID VARCHAR(21) NOT NULL,
FOREIGN KEY (UserID) REFERENCES Users(UserID)
ON DELETE CASCADE
ON UPDATE CASCADE
);`
c.white('* UserSessionToken table created.');
}
catch(e){
if (e.message.includes('already exists')){
c.notice(`* UserSessionToken table already exists, skipping...`);
}
else{
c.error('* ' + e);
}
}
// Create Groups table
try {
await sql`CREATE TABLE Groups(
GroupID SERIAL NOT NULL PRIMARY KEY,
GroupName VARCHAR(100) NOT NULL,
AdminID VARCHAR(21) NOT NULL,
FOREIGN KEY (AdminID) REFERENCES Users(UserID)
ON DELETE CASCADE
ON UPDATE CASCADE
);`
c.white('* Groups table created.');
}
catch(e){
if (e.message.includes('already exists')){
c.notice(`* Groups table already exists, skipping...`);
}
else{
c.error('* ' + e);
}
}
// Create TaskViews (TaskQueries) table
try {
await sql`CREATE TABLE TaskViews(
TaskViewID SERIAL PRIMARY KEY,
FilterName TEXT,
TagQuery TEXT,
VaultID INT NOT NULL,
SortBy TEXT,
GroupBy TEXT,
DescIncludes TEXT,
TitleIncludes TEXT,
TagIncludes TEXT,
IsDone BOOLEAN,
IsNotDone BOOLEAN,
StartDate TIMESTAMP,
EndDate TIMESTAMP,
FOREIGN KEY (VaultID) REFERENCES Groups(GroupID)
ON DELETE CASCADE
ON UPDATE CASCADE
);`
c.white('* TaskViews table created.');
}
catch(e){
if (e.message.includes('already exists')){
c.notice(`* TaskViews table already exists, skipping...`);
}
else{
c.error('* ' + e);
}
}
// Create Tasks table
try {
await sql`CREATE TABLE Tasks(
TaskID SERIAL NOT NULL PRIMARY KEY,
TaskName TEXT,
GroupID INT,
AttachmentID INT,
Description TEXT,
Priority INT,
DueDate TIMESTAMP,
CreatedDate TIMESTAMP,
CompletedDate TIMESTAMP,
ArchivedDate TIMESTAMP,
FOREIGN KEY (GroupID) REFERENCES Groups(GroupID)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (AttachmentID) REFERENCES Attachments(AttachmentID)
ON DELETE SET NULL
ON UPDATE CASCADE
);`
c.white('* Tasks table created.');
}
catch(e){
if (e.message.includes('already exists')){
c.notice(`* Tasks table already exists, skipping...`);
}
else{
c.error('* ' + e);
}
}
// Create user groups table (user in group)
try {
await sql`CREATE TABLE UserGroups(
UserID VARCHAR(21) NOT NULL,
GroupID INT NOT NULL,
PRIMARY KEY (UserID, GroupID),
FOREIGN KEY (UserID) REFERENCES Users(UserID)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (GroupID) REFERENCES Groups(GroupID)
ON DELETE CASCADE
ON UPDATE CASCADE
);`
c.white('* UserGroups table created.');
}
catch(e){
if (e.message.includes('already exists')){
c.notice(`* UserGroups table already exists, skipping...`);
}
else{
c.error('* ' + e);
}
}
// Create Tags table
try {
await sql`CREATE TABLE Tags(
TagID SERIAL NOT NULL PRIMARY KEY,
TagName TEXT NOT NULL,
TagColor VARCHAR(7) NOT NULL,
GroupID INT NOT NULL,
FOREIGN KEY (GroupID) REFERENCES Groups(GroupID)
ON UPDATE CASCADE
ON DELETE CASCADE
);`
c.white('* Tags table created.');
}
catch(e){
if (e.message.includes('already exists')){
c.notice(`* Tags table already exists, skipping...`);
}
else{
c.error('* ' + e);
}
}
// Create TagsTables table
try {
await sql`CREATE TABLE TagsTables(
TagID INT NOT NULL,
TaskID INT NOT NULL,
PRIMARY KEY (TagID, TaskID),
FOREIGN KEY (TagID) REFERENCES Tags(TagID)
ON UPDATE CASCADE
ON DELETE CASCADE,
FOREIGN KEY (TaskID) REFERENCES Tasks(TaskID)
ON UPDATE CASCADE
ON DELETE CASCADE
);`
c.white('* TagsTable table created.');
}
catch(e){
if (e.message.includes('already exists')){
c.notice(`* Tags table already exists, skipping...`);
}
else{
c.error('* ' + e);
}
}
/*
// Create Task message table
try {
await sql`CREATE TABLE TaskMessages(
MessageID SERIAL PRIMARY KEY,
TaskID INT NOT NULL,
UserID INT NOT NULL,
Message TEXT NOT NULL,
Tstamp TIMESTAMP NOT NULL,
FOREIGN KEY (TaskID) REFERENCES Tasks(TaskID)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (UserID) REFERENCES Users(UserID)
ON DELETE CASCADE
ON UPDATE CASCADE
);`
c.white('* TaskMessages table created.');
}
catch(e){
if (e.message.includes('already exists')){
c.notice(`* TaskMessages table already exists, skipping...`);
}
else{
c.error('* ' + e);
}
}*/
/*
c.runBigProcess('\n' + ' Running Task attachment integrity checks...');
// Check for task-attachment integrity.
const test1 = await sql`
SELECT AttachmentID, TaskID, TaskName FROM Tasks;
`;
let caught = 0;
for (let i = 0; i < test1.length; i++){
let id = test1[i].attachmentid;
if (id != null){
let getTest = await getAttachment(id, true);
if (getTest == -1){
await sql`
UPDATE Tasks
SET AttachmentID = NULL
WHERE TaskID = ${test1[i].taskid};
`;
caught++;
}
else{
// TO-DO: Check every array pair in txt file if it is
/*
getTest maybe is =
{
hexData: '5b32322c32332c32342c32355d',
fileName: 'attachments.txt',
lastModified: 2024-12-06T17:41:23.074Z,
dateAdded: 2024-12-06T17:41:23.074Z
}
*//*
if (getTest.fileName.split('.')[1] == 'txt'){
try {
let t = JSON.parse(Buffer.from(getTest.hexData, 'hex').toString('utf-8'));
for (let j = 0; j < t.length; j++){
let getTest2 = await getAttachment(t[j], true);
if (getTest2 == -1){
await sql`
DELETE FROM Attachments WHERE AttachmentID = ${t.splice(j, 1)[0]};
`;
caught++;
}
}
// Rewrite back to the file.
deleteAttachment(id);
let dx = writeAttachment('txt', JSON.stringify(t));
const nid = (await sql`
INSERT INTO Attachments(FileName, DateAdded, DateModified, FilePath)
VALUES (${nanoid()}, ${Date.now()}, ${Date.now()}, ${dx}) RETURNING AttachmentID;
`)[0].attachmentid;
await sql`
UPDATE Tasks
SET AttachmentID = ${nid}
WHERE TaskID = ${test1[i].taskid};
`;
}
catch(e){
// Corrupt file, remove it.
await sql`
UPDATE Tasks
SET AttachmentID = NULL
WHERE TaskID = ${test1[i].taskid};
`;
caught++;
}
}
}
}
}
c.notice(`# files caught: ${caught}`);*/
// Test for junk attachments (TO-DO);
c.white('\n');
}
async function cleanAttachments(){
c.runBigProcess('\n Cleaning attachments folder... ');
let corrections = 0;
let checked = 0;
// Now manually check the rest files.
const gt = (await sql`
SELECT FilePath FROM Attachments;
`).map(i => path.basename(i.filepath));
let dm = fs.readdirSync(path.resolve('attachments'));
for (let i = 0; i < dm.length; i++){
checked++;
let pl = path.basename(path.resolve('attachments/' + dm[i]));
if (!gt.includes(pl)){
if (path.extname(pl) == '.echoattachments'){
let rd = JSON.parse(fs.readFileSync(path.resolve('attachments/' + dm[i])));
for (let j = 0; j < rd.length; j++){
checked++;
const pc = await sql`
SELECT FilePath FROM Attachments WHERE
AttachmentID = ${rd[j]};
`;
if (pc.length != 0){
fs.rmSync(pc[0].filepath);
await sql`
DELETE FROM Attachments WHERE
AttachmentID = ${rd[j]};
`
corrections++;
}
}
fs.rmSync(path.resolve('attachments/' + dm[i]));
}
else{
fs.rmSync(path.resolve('attachments/' + dm[i]));
corrections++;
}
}
}
c.notice(`${checked} items checked, ${corrections} corrections made.\n\n`);
}
/**
* Verify that the session token is not expired, real, and
* return the UserID if so.
* @param {string} sessionToken
* @returns {int} UserID
*/
async function verifySessionToken(sessionToken){
// Let's clean the session token table by wiping expired ones.
await sql`
DELETE FROM UserSessionToken WHERE
ExpireDate <= ${Date.now()};
`;
// Let's query the session token table.
const res = await sql`
SELECT UserID FROM UserSessionToken WHERE
Token = ${sessionToken} AND IssuedDate <= ${Date.now()} AND
ExpireDate > ${Date.now()};
`;
if (res.length == 0 || res.length > 1){
return -1;
}
else{
return res[0].userid;
}
}
/**
* Get all groups that the user is in.
* @param {int} userID
*/
async function getAllUserGroups(userID){
// First let's query for all the groups we are in.
let res = await sql`SELECT * FROM UserGroups WHERE
UserID = ${userID}`;
// Check if there is no groups.
if (res.length == 0){
// We need to create a default group, and also add to UserGroups this relation.
const t = await sql`INSERT INTO Groups(AdminID, GroupName)
VALUES (${userID}, 'Personal Vault') RETURNING GroupID;`;
const groupID = t[0].groupid;
await sql`INSERT INTO UserGroups(UserID, GroupID)
VALUES (${userID}, ${groupID})`
res = await sql`SELECT * FROM UserGroups WHERE UserID = ${userID}`;
}
return res;
}
/**
* Get a group.
* @param {int} groupID
*/
async function getGroup(groupID){
const res = await sql`
SELECT * FROM Groups WHERE GroupID = ${groupID}
`;
if (res.length === 0){
return -1;
}
return res[0];
}
async function getUserGroups(userID){
let res = await getAllUserGroups(userID);
//console.log(res);
res = res.map(entry => getGroup(entry.groupid));
res = await Promise.all(res);
return res;
}
/**
* Get all tasks across all groups, sorted by due date.
* @param {*} userID
*/
async function getAllTasks(userID){
// First let's query for all the groups we are in.
let res = await getAllUserGroups(userID);
// Now let's find the tasks under every group.
let transform = res.map(entry => entry.groupid);
// This query does WHERE GroupID IN [ array of group ids ... ],
// The equivalent SQL syntax may be WHERE GroupID IN ('elem1', 'elem2', etc..)
// except that this library lets me do this dynamically
// Otherwise, with a different SQL library we just need to append elements to
// the query string in this format, so it's not so different anyways.
let tasks = await sql`
SELECT * FROM Tasks WHERE GroupID IN ${sql(transform)}
ORDER BY DueDate ASC, Priority ASC;
`;
return tasks;
}
/**
* Get attachment data from the DB
* (including binary file data).
* @param {*} attachmentID
*/
async function getAttachment(attachmentID, special = false){
const res = await sql`
SELECT * FROM Attachments WHERE AttachmentID = ${attachmentID}
`;
if (res.length === 0){
return -1;
}
const fpath = res[0].filepath;
// Read file data.
if ((!fs.existsSync(fpath)) && special){
return -1;
}
if ((!fs.existsSync(fpath))){
// No file exist but entry is in table...
await sql`
DELETE FROM Attachments WHERE AttachmentID = ${attachmentID};
`;
return -1;
}
const rd = util.promisify(fs.readFile);
try {
const hexData = await rd(fpath, 'hex');
// Let's return this data as a package.
return {
hexData: hexData,
fileName: res[0].filename,
lastModified: res[0].modifieddate,
dateAdded: res[0].dateadded
};
}
catch(e){
c.error(`Error reading attachment ${fpath}`);
c.error(e);
return -1;
}
}
/**
* Get the details of a specific user (manually also encode the profile picture info).
* sessionToken is needed to ensure scope privileges.
* @param {int} userID
* @param {string} sessionToken
*/
async function getUser(userID, sessionToken){
let res;
// Are we fetching ourself? If so, we can get every column.
if ((await verifySessionToken(sessionToken)) === userID){
res = await sql`
SELECT UserID, Username, Email, PhoneNumber, Admin, PfpAttachmentID
FROM Users WHERE UserID = ${userID};
`
}
else{
// We are fetching other user, so limit the scope.
res = await sql`
SELECT UserID, Username, PfpAttachmentID FROM Users WHERE
UserID = ${userID};
`
}
// Now we need to resolve the pfp situation.
const pfpData = await getAttachment(res[0].pfpattachmentid);
let b = res[0];
delete b.pfpattachmentid;
b.pfp = pfpData;
return b;
}
async function getFilters(groupID){
const filters = await sql`
SELECT * FROM TaskViews WHERE VaultID = ${groupID} ORDER BY FilterName;
`;
return filters;
}
/**
* Basicaly fs.writeFileSync wrapper.
* @param {string} file extension
* @param {*} data binary data or string
* @returns {string} random file name as needed.
*/
function writeAttachment(ext, data){
let rndFilename = nanoid() + `.${ext}`;
let fullPath = path.resolve(`attachments/${rndFilename}`);
fs.writeFile(fullPath, data, () => {});
return fullPath;
}
/**
* Deletes an attachment from Attachments table.
* @param {int} attachmentid
* @returns
*/
async function deleteAttachment(attachmentid){
try {
await sql`
DELETE From Attachments WHERE
AttachmentID = ${attachmentid};
`;
return true;
}
catch(e){
c.error(e);
return false;
}
}
app.use('/guide', express.static('guide'));
///// WEB APIs /////
// Format: route: (req, res) => ()
let webApiListeners = {
'/' : async (req, res) => {
if (!devMode){
res.setHeader('content-type', 'text/html');
res.send(htmlmin);
}
else{
res.sendFile(path.resolve('public/index.html'));
}
},
'/bundle.js' : async (req, res) => {
if (!devMode){
res.setHeader('content-type', 'text/javascript');
res.send(bundlejs);
}
else{
res.sendFile(path.resolve('public/bundle.js'))
}
},
'/main.js' : async (req, res) => {
if (!devMode){
res.setHeader('content-type', 'text/javascript');
res.send(mainjs);
}
else{
res.sendFile(path.resolve('public/main.js'))
}
},
'/sw.js' : async(req, res) => {
if (!devMode){
res.setHeader('content-type', 'text/javascript');
res.send(swjs);
}
else{
res.sendFile(path.resolve('public/sw.js'));
}
},
'/manifest.json' : async(req, res) => {
res.sendFile(path.resolve('manifest.json'));
},
'/favicon.ico' : async (req, res) => {
res.sendFile(path.resolve('favicon.ico'));
},
'/api/:request' : async (req, res) => {
const p = req.params;
try {
res.sendError = () => {
res.send(str({
status: 'ERROR'
}));
}
res.sendOK = () => {
res.send(str({
status: 'OK'
}));
}
res.sendInvalid = () => {
res.send(str({
status: 'INVALID'
}));
}
const request = JSON.parse(p.request);
const endpoint = request[0];
const token = request[1];
const uid = await verifySessionToken(token); // Should be the UserID from session token if valid, except for login endpoint.
if (endpoint === 'login'){
// Params
const username = request[1];
const password = request[2];
// Let's try it against the known DB entries.
const d = await sql`SELECT PasswordHash, PasswordSalt, UserID from Users where Username = ${username}`;
if (d.length <= 0){
res.sendInvalid();
return;
}
else{
const realpwd = d[0].passwordhash;
const realsalt = d[0].passwordsalt;
// Check password hash.
const attemptedHash = (await generatePasswordHash(password, realsalt)).hash;
if (attemptedHash === realpwd){
// Let's generate a user session token and hand it to them.
const sessionToken = nanoid();
const exp = Date.now() + 1.577e+10;
await sql`
INSERT INTO UserSessionToken(Token, IssuedDate, ExpireDate, UserID) VALUES
(${sessionToken}, ${Date.now()}, ${exp}, ${d[0].userid});
`;
//console.log(await sql`SELECT * FROM UserSessionToken;`);
res.send(str({
status: 'OK',
token: sessionToken,
expires: exp
}));
}
else{
res.sendInvalid();
}
}
}
else if (endpoint === 'getClientPackageUpdate'){
// Update all general information for the app client.
// This includes tasks, groups, profile picture, attachments, etc.
// This is a very expensive API call, but easier to implement.
if (uid != -1){
const tasks = await getAllTasks(uid);
const selfUser = await getUser(uid, token);
let bigGroups = await sql`
SELECT * FROM UserGroups INNER JOIN Groups ON
Groups.GroupID = UserGroups.GroupID
WHERE UserGroups.UserID = ${uid};
`;
for (let i = 0; i < bigGroups.length; i++){
bigGroups[i].tags = await sql`
SELECT * FROM Tags WHERE GroupID = ${bigGroups[i].groupid} ORDER BY TagName;
`;
bigGroups[i].filters = await getFilters(bigGroups[i].groupid);
bigGroups[i].users = await sql`
SELECT UserID FROM UserGroups WHERE GroupID = ${bigGroups[i].groupid} ORDER BY UserID;
`;
let u = bigGroups[i].users;
for (let j = 0; j < u.length; j++){
u[j] = await getUser(u[j].userid, token);
}
}
res.send(str({
status: 'OK',
me: selfUser,
tasks: tasks,
groups: bigGroups
}));
}
else{
// Invalid API session key response.
res.sendInvalid();
}
}
else if (endpoint === 'createNewTag'){
if (uid != -1){
let groupId = request[2], tagName = request[3], tagColor = request[4];
try {
await sql`
INSERT INTO Tags (TagName, TagColor, GroupID) VALUES
(${tagName}, ${tagColor}, ${groupId});
`;
res.sendOK();
}
catch(e){
c.error(e);
res.sendError();
}
}
else{
// Invalid API session key response.
res.sendInvalid();
}
}
else if (endpoint === 'updateTag'){
if (uid != -1){
let tagId = request[2], tagName = request[3], tagColor = request[4];
try {
await sql`
UPDATE Tags
SET TagName = ${tagName}, TagColor = ${tagColor}
WHERE TagID = ${tagId};
`;
res.sendOK();
}
catch(e) {
c.error(e);
res.sendError();
}
}
else{
// Invalid API session key response.
res.sendInvalid();
}
}
else if (endpoint === 'deleteTag'){
if (uid != -1){
let tagId = request[2], deleteAll = request[3];
if (deleteAll === true){
try {
await sql`
DELETE FROM Tags;
`;
res.sendOK();
}
catch(e){
c.error(e);
res.sendError();
}
}
else{
try {
await sql`
DELETE FROM Tags WHERE TagID = ${tagId}
`;
res.sendOK();
}
catch(e){
c.error(e);
res.sendError();
}
}
}
else{
// Invalid API session key response.
res.sendInvalid();
}
}
else if (endpoint === 'fetchTasksWithView'){
if (uid != -1){
try {
let groupid = request[2], filterid = request[3];
// First we fetch from the TaskView table the entry we want.
const res1 = (await sql`
SELECT * FROM TaskViews WHERE TaskViewID = ${filterid}
`)[0];
// Create SQL syntax maps which we will interpolate with the query later.
let sortByMap = {
'duedate': 'Tasks.DueDate ASC',
'priority': 'Tasks.Priority ASC',
'title': 'Tasks.TaskName'
};
let groupByMap = {
'day' : 'DATEPART(day, DueDate), DATEPART(day, CreatedDate)',
'month': 'DATEPART(month, DueDate), DATEPART(day, CreatedDate)',
'week': 'DATEPART(week, DueDate), DATEPART(week, CreatedDate)',
'year': 'DATEPART(year, DueDate), DATEPART(year, CreatedDate)'
};
if (typeof res1 == 'undefined'){
res.sendError();
return;
}
//console.log(res1);
let sortBy = sortByMap[res1.sortby], groupBy = groupByMap[res1.groupby];
const res2 = await sql`
SELECT * FROM Tasks INNER JOIN TagsTables ON TagsTables.TaskID = Tasks.TaskID
WHERE Tasks.GroupID = ${groupid}
GROUP BY TagsTables.TagID, TagsTables.TaskID, Tasks.TaskID, ${groupBy}
ORDER BY ${sortBy};
`;