-
Notifications
You must be signed in to change notification settings - Fork 85
/
routes.js
1295 lines (1118 loc) · 38.8 KB
/
routes.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
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
/*
* Contains (and imports) all route definitions here for the FlyLaTeX application
*/
var mongoose = require("mongoose")
, Schema = mongoose.Schema
, ObjectId = Schema.ObjectId
, app = require("./app")
, io = require("socket.io").listen(app)
, configs = require("./configs")
, temp = require("temp")
, fs = require("fs-extra")
, util = require("util")
, path = require("path")
, exec = require("child_process").exec
, http = require("http")
// flylatex directory
, flylatexdir = __dirname;
io.set('log level', 1); // reduce logging
// connect to the flydb app database
mongoose.connect(configs.db.url);
// import the models
require("./models")();
var User = mongoose.model("User")
, Document = mongoose.model("Document")
, DocPrivilege = mongoose.model("DocPrivilege")
, Message = mongoose.model("Message");
// laod helpers
var helpers = require("./routes_lib/helpers.js");
// import some route definitions
exports.index = require("./routes_lib/index.js").index;
exports.logOutUser = require("./routes_lib/logout.js").logOutUser;
exports.displaySignUpForm = require("./routes_lib/displaysignup.js")
.displaySignUpForm;
exports.addNewDocument = require("./routes_lib/addnewdocument.js")
.addNewDocument;
// maximum number of documents a user can have
var MAX_DOCS = ( configs.docs.MAX_NUM_PER_USER > 0 ?
configs.docs.MAX_NUM_PER_USER : 20 );
// messageTypes
var MESSAGE_TYPES = {
'requestAccess': 0
, 'shareAccess': 1
};
// currently opened documents -> map of docId : [username]
var openDocuments = {};
/*
* About rendering:
* the object to pass to the template being rendered has to have:
* ===== title ======
* ===== shortTitle ======
* Optionally can have:
* * fileSpecificScript
* * fileSpecificStyle
* * currentUser
* * isLoggedIn (should always go together with currentUser)
* * tagLine
* * currentDoc
* * userDocuments - this is an abstraction of the real Document model.
So it contains different attributes.
contains: id, name, readAccess, writeAccess, canShare
* * errors
* * infos
*/
/*
* preIndex -
* load currentUser's data before loading page
* if user's not registered, just go to next
* @param req -> request object
* @param res -> response object
* @param next -> next (middleware) function (in callchain) to execute
*/
exports.preIndex = function(req, res, next) {
if ((req.body.username == undefined
&& req.body.password == undefined) ||
(req.body.username.length == 0
&& req.body.password.length == 0)) {
// user's chilling, makes no attempt to log in
next();
} else if (req.session.currentUser && req.session.isLoggedIn) {
// user's already logged in, so go on
next();
} else if (req.body.username && req.body.username.length > 0
&& req.body.password && req.body.password.length > 0) {
// user's not logged in, but wants to log in
User.findOne({"_id": req.body.username}, function(err, user) {
if (err) {
req.session.currentUser = null;
req.session.isLoggedIn = false;
next();
return;
}
if (!user || typeof user.authenticate != "function") {
req.flash("error", "There's no user called '"
+ req.body.username + "' in our database");
res.redirect('back');
return;
} else if (!user.authenticate(req.body.password)) {
req.flash('error', "Password does not match Username entered");
res.redirect('back');
return;
} else {
var loadedUser = helpers.loadUser(user);
for (var key in loadedUser) {
req.session[key] = loadedUser[key];
}
next();
}
});
} else {
if (!(req.body.username && req.body.password)) {
req.flash('error', "Enter both a username and password");
res.redirect('back');
return;
}
}
};
/*
* processSignUpData ->
* processes the sign up data posted from the sign
* up form and logs the user into fly latex
* , redirecting him to his home page.
* @param req -> request object
* @param res -> response object
*/
exports.processSignUpData = function(req, res) {
var errors = {}; // key-value pair -> error Type : error Message
var isError = false;
var newUser = req.body.newUser;
if (newUser.userName.length == 0) {
errors["userNameToken"] = "Enter a username";
}
if (!(newUser.password.length > 4 // password has to be at least 5 chars
&& /\d+/.test(newUser.password))) { // password has to have at least one digit
errors["passwordInvalid"] = "Password must be at least 5 chars "
+ "and must contain at least one digit";
isError = true;
}
if (newUser.password != newUser.confirmPassword) {
errors["passwordNoMatch"] = "Passwords don't match";
isError = true;
}
if (!(/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/
.test(newUser.email))) {
errors["emailInvalid"] = "Enter a valid email address";
isError = true;
}
if (!(newUser.firstName.length > 0
&& newUser.lastName.length > 0)) {
errors["namesInvalid"] = "Enter a first Name and a Last Name";
isError = true;
}
// optional params
if (newUser.githubId.length == 0) {
delete newUser["githubId"];
}
if (newUser.twitterId.length == 0) {
delete newUser["twitterId"];
}
if (!isError) {
// there's no error. Save the new user
// only if someone else doesn't have his username
User.find({_id : newUser.userName}, function(err, users) {
if (users.length > 0) {
errors["userNameTaken"] = "The username '" +
newUser.userName + "' is already taken";
isError = true;
helpers.displayErrorsForSignUp(res, errors);
} else {
// save the user
var newFlyUser = new User();
for (var key in newUser) {
newFlyUser[key] = newUser[key];
}
newFlyUser.documentsPriv = [];
newFlyUser.save(function(err) {
if (err) {
console.log("==============Error in saving user======");
console.log(newFlyUser);
console.log("======================================");
}
});
var loadedUser = helpers.loadUser(newFlyUser);
for (key in loadedUser) {
req.session[key] = loadedUser[key];
}
// redirect to home page with user logged in
res.redirect("home");
}
});
} else {
helpers.displayErrorsForSignUp(res, errors);
}
};
/*
* createDoc ->
* creates a new document for the current user.
* error if user not logged in.
* @note
* this function is called asynchronous and should
* sennd back a json response
* and not redirect or reload page.
*
* @param req -> request object
* @param res -> response object
*/
exports.createDoc = function(req, res) {
// prepare response object
var response = {infos:[]
, errors: []
, code:200
, newDocument: {id:null
, name:null
, readAccess: true
, writeAccess: true
, canShare: true}
};
var docName = req.body.docName;
if (!(docName.length && docName.length > 0)) {
response.errors.push("Error in creating document with no title or name");
res.json(response);
return;
} else if (!(req.session.isLoggedIn && req.session.currentUser)) {
response.errors.push("You're not not logged in. Please log in!");
res.json(response);
return;
}
// verify that this new document doesn't have the same name as the old ones
var found = false;
for (var i = 0; i < req.session.userDocuments.length; i++) {
if (req.session.userDocuments[i].name == docName) {
found = true;
break;
}
}
if (found) {
response.errors.push("Error in creating document that shares"
+ " its name with an already existing document you have.");
res.json(response);
return;
} else {
if (req.session.userDocuments.length >= MAX_DOCS) {
response.errors.push("You can't have more than " + MAX_DOCS + " documents. "
+ "Delete some documents to create space. "
+ "Or contact the Administrator.");
res.json(response);
return;
} else {
var newDoc = helpers.createNewDocument(req.body.docName
, req.session.currentUser);
// by default, document privilege for the
// current user is 6 (full access)
var docPriv = new DocPrivilege();
docPriv._id = newDoc._id;
docPriv.name = newDoc.name;
// new user document to send off to front end for display
var newUserDocument = {};
User.findOne({"_id": req.session.currentUser}, function(err, user) {
if (err || !user) {
response.errors.push("Couldn't find you. Weird.");
res.json(response);
return;
}
// add to user's documentsPriv
user.documentsPriv.push(docPriv);
// save the document
user.save();
// add to the user's session data
newUserDocument.id = docPriv._id;
newUserDocument.name = docPriv.name;
// user creating document should have full access to document
// R,W,X (and so can share the document with anyone)
newUserDocument.readAccess = true;
newUserDocument.writeAccess = true;
newUserDocument.canShare = true;
req.session.userDocuments.push(newUserDocument);
response.newDocument = newUserDocument;
// inform user of new document creation
response.infos.push("Just created the new Document '"
+ req.body.docName + "'. Hooray!");
res.json(response);
});
}
}
};
/**
* deleteDoc -
* delete the document from the user's list of documents
* both in the session data and on the database (his/her docPrivileges)
* then delete the document from the Documents collection.
*
* @note
* this method is called asynchronously and should not redirect the user
* or reload the page under any circumstances.
* @param req -> request object
* @param res -> response object
*/
exports.deleteDoc = function(req, res) {
// response to send back to user after successful deletion (or error)
var response = {errors:[], infos:[], code:200};
// get document id,name for document to delete
var docId = req.body.docId
, docName;
if (!(req.session.currentUser && req.session.isLoggedIn)) {
response.errors.push("Weird. Seems like you're not logged in.");
res.json(response);
return;
}
// remove the document from Users collections
User.findOne({_id: req.session.currentUser}, function(err, user) {
if (err || !user) {
response.errors.push("Had problems processing your deletion. Try again.");
res.json(response);
return;
}
for (var i = 0; i < user.documentsPriv.length; i++) {
if (user.documentsPriv[i]._id.equals(docId)) {
docName = user.documentsPriv[i].name;
user.documentsPriv.splice(i, 1);
break;
}
}
// save a document
user.save();
// change session object to reflect new change in user's documents
for (i = 0; i < req.session.userDocuments.length; i++) {
if (String(req.session.userDocuments[i].id) == String(docId)) {
req.session.userDocuments.splice(i,1);
}
}
var removeDocs = function(err, docs) {
if (docs.length == 0) {
// no other user has this document
Document.findOne({_id:docId}).remove(function(err) {
if (err) {
console.log("Error while deleting document with _id "
+ docId + " completely from the database");
}
res.json(response);
});
} else {
// then remove the current userName from the the list of users
// with share (full) access, if there
Document.findOne({_id: docId}, function(err, doc) {
if (!err) {
var found = false
, i; // loop variable
for (i = 0; i < doc.usersWithShareAccess.length; i++) {
if (doc.usersWithShareAccess[i]
== req.session.currentUser) {
found = true;
break;
}
}
if (found) {
doc.usersWithShareAccess.splice(i, 1);
// save the document
doc.save();
if (response.errors.length == 0 && docName.length > 0) {
response.infos.push("Successfully deleted the document '"
+ docName + "'");
res.json(response);
}
}
}
});
}
};
// remove the document from Documents collections
// if no other user has it
User.find({"documentsPriv._id":docId}, removeDocs);
});
};
/**
* shareAccess -> share access to a document
* @param req -> request object
* @param res -> response object
*/
exports.shareAccess = function(req, res) {
var response = {errors:[], infos:[], code: 200};
// get share options
var options = req.body.options;
var priv = ((options.withReadAccess == "true" ? 4 : 0) +
(options.withWriteAccess == "true" ? 2 : 0));
if (!(req.session.currentUser && req.session.isLoggedIn)) {
response.errors.push("You are not logged in. So you can't share access");
}
if (priv == 0) {
response.errors.push("You can't try to share no privilege Dude/Dudette");
}
if (!(options.docId
&& options.docName
&& options.userToShare)) {
response.errors.push("Options passed in are incomplete");
}
if (priv < 4) {
response.errors.push("You should share at least 'Read' privilege");
}
User.findOne({_id: options.userToShare}, function(err, user) {
if (err) {
console.log("An error occured");
}
if (!user) {
response.errors.push("The user you want to send a message to doesn't exist");
}
if (response.errors.length > 0) {
// if any errors
res.json(response);
} else {
// if no errors found yet
// make the message to send
var newMessage = new Message();
newMessage.messageType = MESSAGE_TYPES.shareAccess;
newMessage.fromUser = req.session.currentUser;
newMessage.toUser = options.userToShare;
newMessage.documentId = options.docId;
newMessage.documentName = options.docName;
newMessage.access = priv;
// save the message to the messages collection
newMessage.save();
var withReadAccess = (options.withReadAccess == 'true')
, withWriteAccess = (options.withWriteAccess == 'true');
// send success message
response.infos.push("You just invited '"+options.userToShare+"' to have "+
(withReadAccess ? "Read" +
((!withWriteAccess)
? " ": ", ") :"") +
(withWriteAccess ? "Write" : " ")+
" Access to '" + options.docName + "'");
// emit message to recipient if online
io.sockets.volatile.emit("newMessage", JSON.stringify(newMessage));
// send response back to the client
res.json(response);
}
});
};
/**
* ajaxAutoComplete ->
* returns json of auto-complete results based on the purpose
*
* @param req -> request object
* @param res -> response object
*/
exports.ajaxAutoComplete = function(req, res) {
var purpose = req.query.purpose
, word = req.query.word;
switch (purpose) {
case "usernames":
// get word user has typed so far
var typed = req.query.word
, data = {code:200, results:[]};
// query the users collection for usernames
User.find({_id: new RegExp(typed)}, function(err, users) {
if (!err) {
users.forEach(
function(item, index) {
if (item.userName != req.session.currentUser) {
data.results.push(item.userName);
}
});
}
res.json(data);
});
break;
default:
console.log("It's either you're trying to mess with me or I messed up.");
};
};
/**
* requestAccess -> request access to a document
* @param req -> request object
* @param res -> response object
*/
exports.requestAccess = function(req, res) {
var response = {errors:[], infos:[], code: 200};
// get request access options
var options = req.body.options;
var priv = ((options.withReadAccess == "true" ? 4 : 0) +
(options.withWriteAccess == "true" ? 2 : 0));
// try to return error messages if any errors found
if (!(req.session.currentUser && req.session.isLoggedIn)) {
response.errors.push("You are not logged in. So you can't share access");
}
if (priv == 0) {
response.errors.push("You can't try to request for no privilege");
}
if (!(options.docId
&& options.docName)) {
response.errors.push("Options passed in are incomplete");
}
if (priv < 4) {
response.errors.push("You should request for at least read access to a document ");
}
if (response.errors.length > 0) {
res.json(response);
return;
}
// first find the users that have share access (6:R,W) to the document
Document.findOne({_id: options.docId}, function(err, doc) {
if (err) {
console.log("An error occured while trying to request access for "
+ req.session.currentUser);
} else {
if (doc.usersWithShareAccess.length > 0) {
var newMessage, i;
for (i = 0; i < doc.usersWithShareAccess.length; i++) {
newMessage = new Message();
newMessage.messageType = MESSAGE_TYPES.requestAccess;
newMessage.fromUser = req.session.currentUser;
newMessage.toUser = doc.usersWithShareAccess[i];
newMessage.documentId = options.docId;
newMessage.documentName = options.docName;
newMessage.access = priv;
// save the message in the messages collection
newMessage.save();
// alert users that are logged in about message
io.sockets.volatile.emit("newMessage", JSON.stringify(newMessage));
}
response.infos.push("Sent a 'Request More Privileges' message"
+ " to all the users who have share access"
+ " to the document '" + options.docName + "'");
res.json(response);
} else {
response.errors.push("No user currently has Share Access "
+ "to that document");
// send response back
res.json(response);
}
}
});
};
/**
* getMessages ->
* get the messages for the current user
* @param req -> request object
* @param res -> response object
*
* @jsonreturn returns a list of user's messages
* each message object is of the form
* {messageType:, fromUser:, toUser:, documentId:, documentName:,access:}
*/
exports.getMessages = function(req, res) {
var response = {errors:[], infos:[], messages:[]};
// try to find messages for the current user
Message.find({toUser : req.session.currentUser}, function(err, messages) {
if (err) {
response.errors.push("Error while retrieving messages. Try again later.");
res.json(response);
} else if (messages.length == 0) {
response.infos.push("You have no messages!");
res.json(response);
} else {
// get the messages
messages.forEach(function(item, index) {
var priv = item.access;
// set privileges fromUser is requesting
item.readAccess = false;
item.writeAccess = false;
if (priv >= 4) {
item.readAccess = true;
priv -= 4;
}
if (priv >= 2) {
item.writeAccess = true;
priv -= 2;
}
response.messages.push(item);
});
// send back messages
res.json(response);
}
});
};
/**
* grantAccess ->
* grant another user access to some document
* @param req : request object
* @param res: response object
*/
exports.grantAccess = function(req, res) {
var response = {errors: [], infos:[]};
/**
* options passed in: userToGrant, documentId, documentName, access
*/
if (!(req.session.currentUser && req.session.isLoggedIn)) {
response.errors.push("You cannot grant access since you are not logged in.");
res.json(response);
return;
}
User.findOne({"_id" : req.body.userToGrant}, function(err, user) {
if (err || !user) {
response.errors.push("No user '" + req.body.userToGrant
+ "' exists or an error occured "
+ "while looking for this user");
res.json(response);
} else {
// make sure the user's granting at least read access
if (req.body.access < 4) {
response.errors.push("You should grant a user at least 'Read' privilge");
res.json(response);
return;
}
// first make sure that userToGrant doesn't already have some access
// to the document
var userHasDoc = false;
user.documentsPriv
.forEach(function(item, index) {
if (item._id.equals(req.body.documentId)) {
userHasDoc = true;
}
});
var priv = req.body.access
, readAccess = false
, writeAccess = false
, canShare = false;
// give user power to be able to share the document with other users
// if he/she has full access
if (priv == 6) {
canShare = true;
// give user R, W, X access
helpers.giveUserSharePower(req.body.userToGrant
, req.body.documentId);
}
// de-couple privileges here
if (priv >= 4) {
readAccess = true;
priv -= 4;
}
if (priv >= 2) {
writeAccess = true;
priv -= 2;
}
// create new user document
var newUserDocument = {
"id": req.body.documentId
, "name": req.body.documentName
, "readAccess" : readAccess
, "writeAccess" : writeAccess
, "canShare" : canShare
, "forUser" : req.body.userToGrant
};
if (userHasDoc) {
var upgrading = false;
// if userToShare already has the document, upgrade access if possible
for (var i = 0; i < user.documentsPriv.length; i++) {
if (user.documentsPriv[i]._id.equals(newUserDocument.id)
&& user.documentsPriv[i].access < req.body.access) {
upgrading = true;
// userToShare should reload his/her list of documents
response.reloadDocs = true;
user.documentsPriv[i].access = parseInt(req.body.access);
user.save(function(err) {
if (err) {
console.log("error occured while trying "
+ "to save user");
}
});
// send back message
response.infos.push("You just upgraded the privileges of '"
+ req.body.userToGrant + "' for the document '"
+ req.body.documentName + "'");
// notify userToShare you just upgraded his privileges
// on some document
io.sockets.volatile.emit("changedDocument"
, JSON.stringify(newUserDocument));
res.json(response);
break;
}
}
if (!upgrading) {
// send back duplicate message
response.infos.push("'" + req.body.userToGrant
+ "' already has higher or equal access"
+ " to the document '"
+ req.body.documentName + "'");
res.json(response);
}
} else {
// userToShare should definitely redisplay his list of documents
response.reloadDocs = true;
var newDocPriv = new DocPrivilege();
newDocPriv.access = parseInt(req.body.access);
newDocPriv.name = req.body.documentName;
newDocPriv._id = req.body.documentId;
for (i = 0; i < user.documentsPriv.length; i++) {
if (user.documentsPriv[i]._id.equals(newDocPriv._id)) {
user.documentsPriv.splice(i, 1);
break;
}
}
// save to user's list of document privileges
user.documentsPriv.push(newDocPriv);
user.save();
response.infos.push("You just granted '"+req.body.userToGrant+"' "+
(readAccess ? "Read" +
((!writeAccess)
? " ": ", ") :"")+
(writeAccess ? "Write" : " ") +
" Access to '"
+ req.body.documentName + "'");
// notify the user just granted access that his/her request
// has been granted immediately via socket.io
io.sockets.volatile.emit("changedDocument"
, JSON.stringify(newUserDocument));
// send response
res.json(response);
}
}
});
};
/**
* acceptAccess ->
* accept another user's offer to have
* access to a document
* @param req : request object
* @param res: response object
*/
exports.acceptAccess = function(req, res) {
var response = {errors:[], infos:[]
, newDocument:null
, reDisplay:false
, userDocuments: req.session.userDocuments};
/**
* options passed in: acceptFromUser, documentId, documentName, access
*/
if (!(req.session.currentUser && req.session.isLoggedIn)) {
response.errors.push("You cannot accept the invitation since you aren't logged in");
res.json(response);
return;
}
// make sure the privilege to accept is at least read privilege
if (parseInt(req.body.access) < 4) {
response.errors.push("You should accept at least 'Read' privilege");
res.json(response);
}
User.findOne({"_id":req.session.currentUser}, function(err, user) {
// first make sure the user doesn't already have some access to the document
// in that case, bump up the user's access
var userHasDoc = false;
req.session.userDocuments
.forEach(function(item, index) {
if (String(item.id) == String(req.body.documentId)) {
userHasDoc = true;
}
});
var priv = req.body.access
, readAccess = false
, writeAccess = false
, canShare = false;
if (priv == 6) {
canShare = true;
// give user share power
// a user can only get share access when he's given access of 6
// which corresponds to R, W
helpers.giveUserSharePower(req.session.currentUser
, req.body.documentId);
}
// de-couple privileges
if (priv >= 4) {
readAccess = true;
priv -= 4;
}
if (priv >= 2) {
writeAccess = true;
priv -= 2;
}
// new user document
var newUserDocument = {
"id": req.body.documentId
, "name": req.body.documentName
, "readAccess" : readAccess
, "writeAccess" : writeAccess
, "canShare" : canShare
};
if (userHasDoc) {
// if user already has the document, upgrade access if possible
var upgrading = false;
for (var i = 0; i < user.documentsPriv.length; i++) {
if (String(user.documentsPriv[i]._id) == String(newUserDocument.id)
&& user.documentsPriv[i].access < req.body.access) {
upgrading = true;
// user should redisplay list of documents
response.reDisplay = true;
user.documentsPriv[i].access = parseInt(req.body.access);
user.save();
// send back message
response.infos.push("You just upgraded your rights to the document '"
+ newUserDocument.name + "'");
break;
}
}
if (upgrading) {
for (i = 0; i < req.session.userDocuments.length; i++) {
if (String(req.session.userDocuments[i].id) == String(newUserDocument.id)) {
// upgrade all we've got
req.session.userDocuments[i] = newUserDocument;
}
}
res.json(response);
return;
}
// send back duplicate message
response.infos.push("You already have higher or equal access to the document '"
+ newUserDocument.name + "'");
res.json(response);
} else {
// user should redisplay list of documents
response.reDisplay = true;
// user doesn't already have access to document
var newDocPriv = new DocPrivilege();
newDocPriv.access = parseInt(req.body.access);
newDocPriv.name = req.body.documentName;
newDocPriv._id = req.body.documentId;
for (var i = 0; i < user.documentsPriv.length; i++) {
if (user.documentsPriv[i]._id.equals(newDocPriv._id)) {
user.documentsPriv.splice(i, 1);
break;
}
}
// save to user's list of document privileges
user.documentsPriv.push(newDocPriv);
user.save(); // save user
// add to my session if I don't have the document yet
req.session.userDocuments.push(newUserDocument);
// also send back so user can display in his/her DOM
response.newDocument = newUserDocument;
// send acceptance message to user
response.infos.push("You just accepted "+
(readAccess ? "Read" +
((!writeAccess)
? " ": ", ") :"")+
(writeAccess ? "Write" : " ") +
" Access to '" + req.body.documentName +
"' from user '" + req.body.acceptFromUser
+ "'");
res.json(response);
}
});
};
/**
* exports.reloadSession -
* reload the user's documents and send back the new documents
*
* @param req : request object
* @param res : result object
*/
exports.reloadSession = function(req, res) {
var response = {infos: [], errors: [], userDocuments: null};
if (!(req.session.currentUser && req.session.isLoggedIn)) {
response.errors.push("You are not logged in.");
res.json(response);
return;
} else if (req.session.currentUser == req.body.document.forUser) {
User.findOne({_id : req.session.currentUser}, function(err, user) {
// reload user
var loadedUser = helpers.loadUser(user);
for (var key in loadedUser) {
req.session[key] = loadedUser[key];
}
// load userDocuments
response.userDocuments = req.session.userDocuments;
res.json(response);