-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhooks.js
2492 lines (2288 loc) · 115 KB
/
hooks.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
var err = require("ep_etherpad-lite/node_modules/async-stacktrace");
var express = require('express');
var eejs = require('ep_etherpad-lite/node/eejs');
var padManager = require('ep_etherpad-lite/node/db/PadManager');
var db = require('ep_etherpad-lite/node/db/DB').db;
var groupManager = require('ep_etherpad-lite/node/db/GroupManager');
var Changeset = require('ep_etherpad-lite/static/js/Changeset');
var mysql = require('mysql');
var email = require('emailjs');
var settings = require('ep_etherpad-lite/node/utils/Settings');
var authorManager = require('ep_etherpad-lite/node/db/AuthorManager');
var sessionManager = require('ep_etherpad-lite/node/db/SessionManager');
var formidable = require("formidable");
var crypto = require('crypto');
var eMailAuth = require(__dirname + '/email.json');
var pkg = require('./package.json');
var DEBUG_ENABLED = false;
/*
* Common Utility Functions
*/
var log = function (type, message) {
if (typeof message == 'string') {
if (type == 'error') {
console.error(pkg.name + ': ' + message);
} else if (type == 'debug') {
if (DEBUG_ENABLED) {
console.log('(debug) ' + pkg.name + ': ' + message);
}
} else {
console.log(pkg.name + ': ' + message);
}
}
else console.log(message);
};
var mySqlErrorHandler = function (err) {
log('debug', 'mySqlErrorHandler');
// TODO: Review error handling
var msg;
if ('fileName' in err && lineNumber in err) {
msg = 'MySQLError in ' + err.fileName + ' line ' + err.lineNumber + ': ';
} else {
msg = 'MySQLError: ';
}
if (err.fatal) {
msg += '(FATAL) ';
}
msg += err.message;
log('error', msg);
};
var connectFkt = function (err) {
if (err) {
log('error', "failed connecting to database");
} else {
log('info', "connected");
}
};
var encryptPassword = function (password, salt, cb) {
var encrypted = crypto.createHmac('sha256', salt).update(password).digest('hex');
cb(encrypted);
};
var USER_EXISTS = 'User already Exists';
var PASSWORD_WRONG = 'Passwords do not agree';
var NO_VALID_MAIL = 'No valid E-Mail';
var PW_EMPTY = 'Password is empty';
var dbAuth = settings.dbSettings;
var dbAuthParams = {
host: dbAuth.host,
user: dbAuth.user,
password: dbAuth.password,
database: dbAuth.database,
insecureAuth: true,
stringifyObjects: true
};
function getRandomNum(lbound, ubound) {
return (Math.floor(Math.random() * (ubound - lbound)) + lbound);
}
function getRandomChar(number, lower, upper, other, extra) {
var numberChars = '0123456789';
var lowerChars = 'abcdefghijklmnopqrstuvwxyz';
var upperChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var otherChars = '`~!@#$%^&*()-_=+[{]}\\|;:\'",<.>/? ';
var charSet = extra;
if (number == true)
charSet += numberChars;
if (lower == true)
charSet += lowerChars;
if (upper == true)
charSet += upperChars;
if (other == true)
charSet += otherChars;
return charSet.charAt(getRandomNum(0, charSet.length));
}
function createSalt(cb) {
var mylength = 10;
var myextraChars = '';
var myfirstNumber = true;
var myfirstLower = true;
var myfirstUpper = true;
var myfirstOther = false;
var mylatterNumber = true;
var mylatterLower = true;
var mylatterUpper = true;
var mylatterOther = false;
var rc = "";
if (mylength > 0) {
rc += getRandomChar(myfirstNumber, myfirstLower, myfirstUpper, myfirstOther, myextraChars);
}
for (var idx = 1; idx < mylength; ++idx) {
rc += getRandomChar(mylatterNumber, mylatterLower, mylatterUpper, mylatterOther, myextraChars);
}
cb(rc);
}
function getPassword(cb) {
var mylength = 40;
var myextraChars = '';
var myfirstNumber = true;
var myfirstLower = true;
var myfirstUpper = true;
var myfirstOther = false;
var mylatterNumber = true;
var mylatterLower = true;
var mylatterUpper = true;
var mylatterOther = false;
var rc = "";
if (mylength > 0) {
rc += getRandomChar(myfirstNumber, myfirstLower, myfirstUpper, myfirstOther, myextraChars);
}
for (var idx = 1; idx < mylength; ++idx) {
rc += getRandomChar(mylatterNumber, mylatterLower, mylatterUpper, mylatterOther, myextraChars);
}
cb(rc);
}
var connection = mysql.createConnection(dbAuthParams);
var connection2 = mysql.createConnection(dbAuthParams);
connection.connect(connectFkt);
connection2.connect(connectFkt);
var userAuthenticated = function (req, cb) {
log('debug', 'userAuthenticated');
if (req.session.username && req.session.password && req.session.userId && req.session.email) {
cb(true);
} else {
cb(false);
}
};
var userAuthentication = function (username, password, cb) {
log('debug', 'userAuthentication');
var userSql = "Select * from User where User.name = ?";
var sent = false;
var userFound = false;
var considered = false;
var active = true;
var queryUser = connection.query(userSql, [username]);
queryUser.on('error', mySqlErrorHandler);
queryUser.on('result', function (foundUser) {
userFound = true;
encryptPassword(password, foundUser.salt, function (encrypted) {
if (foundUser.pwd == encrypted && foundUser.considered && foundUser.active) {
sent = true;
cb(true, foundUser, null, considered);
} else if (!foundUser.active) {
active = false;
}
else {
considered = foundUser.considered;
}
});
});
queryUser.on('end', function () {
if (!sent) {
cb(false, null, userFound, considered, active);
}
});
};
function existValueInDatabase(sql, params, cb) {
log('debug', 'existValueInDatabase');
connection.query(sql, params, function (err, found) {
if (err) {
log('error', 'existValueInDatabase error, sql: ' + sql);
cb(false);
} else if (!found || found.length == 0) {
cb(false);
} else {
cb(true);
}
});
}
function getOneValueSql(sql, params, cb) {
log('debug', 'getOneValueSql');
var qry = connection.query(sql, params, function (err, found) {
if (err) {
log('error', 'getOneValueSql error, sql: ' + sql);
cb(false);
} else if (!found || found.length == 0) {
cb(false, null);
} else {
cb(true, found);
}
});
qry.on('error', mySqlErrorHandler)
}
function updateSql(sqlUpdate, params, cb) {
log('debug', 'updateSql');
var updateQuery = connection.query(sqlUpdate, params);
updateQuery.on('error', mySqlErrorHandler);
updateQuery.on('end', function () {
cb(true);
});
}
function getAllSql(sql, params, cb) {
log('debug', 'getAllSql');
var allInstances = [];
var queryInstances = connection.query(sql, params);
queryInstances.on('error', mySqlErrorHandler);
queryInstances.on('result', function (foundInstance) {
connection.pause();
allInstances.push(foundInstance);
connection.resume();
});
queryInstances.on('end', function () {
cb(allInstances);
});
}
function getUser(userId, cb) {
log('debug', 'getUser');
var sql = "Select * from User where userID = ?";
getOneValueSql(sql, [userId], cb);
}
/* ckubu: added
We distinguish between "normal" and "admin" users. Therefor
a field "isAdmin" was added to table "User"
ALTER TABLE User ADD COLUMN isAdmin int(1) NOT NULL DEFAULT 0 AFTER active;
*/
function isAdmin(userId,cb) {
log('debug', 'isAdmin');
var sql = "Select isAdmin from User where userID = ? and isAdmin = 1";
getOneValueSql(sql, [userId], cb);
}
function getGroup(groupId, cb) {
log('debug', 'getGroup');
var sql = "Select * from Groups where groupID = ?";
getOneValueSql(sql, [groupId], cb);
}
function getUserGroup(groupId, userId, cb) {
log('debug', 'getUserGroup');
var sql = "Select * from UserGroup where groupID = ? and userID = ?";
getOneValueSql(sql, [groupId, userId], cb);
}
function getEtherpadGroupFromNormalGroup(id, cb) {
log('debug', 'getEtherpadGroupFromNormalGroup');
var getMapperSql = "Select * from store where store.key = ?";
var getMapperQuery = connection2.query(getMapperSql, ["mapper2group:" + id]);
getMapperQuery.on('error', mySqlErrorHandler);
getMapperQuery.on('end', function () {
log('debug', 'getEtherpadGroupFromNormalGroup getMapperQuery end');
});
getMapperQuery.on('result', function (mapper) {
log('debug', 'getEtherpadGroupFromNormalGroup getMapperQuery result');
cb(mapper.value.replace(/"/g, ''));
});
}
function getPadsOfGroup(id, padname, cb) {
log('debug', 'getPadsOfGroup');
var allPads = [];
var allSql = "Select * from GroupPads where GroupPads.GroupID = ? and GroupPads.PadName like ?";
var queryPads = connection.query(allSql, [id, "%" + padname + "%"]);
queryPads.on('error', mySqlErrorHandler);
queryPads.on('result', function (foundPads) {
log('debug', 'getPadsOfGroup result');
connection.pause();
var pad = {};
pad.name = foundPads.PadName;
pad.starred = foundPads.starred;
/* ckubu added:
Add OwnerID to array "pad" for use in template "group.ejs" to allow
also padowneris to delete their pads..
*/
pad.ownerid = foundPads.UserID
log('debug', 'padname ' + pad.name);
if (pad.name != "") {
getEtherpadGroupFromNormalGroup(id, function (group) {
log('debug', 'getEtherpadGroupFromNormalGroup cb');
padManager.getPad(group + "$" + pad.name, null, function (err, origPad) {
if (err) log('error', err);
if(origPad) {
pad.isProtected = origPad.isPasswordProtected();
origPad.getLastEdit(function (err, lastEdit) {
pad.lastedit = converterPad(lastEdit);
db.get("title:"+group+"$"+pad.name, function(err, value){
if(value) pad.safeName = value;
allPads.push(pad);
connection.resume();
});
});
} else {
connection.resume();
}
});
});
} else {
connection.resume();
}
});
queryPads.on('end', function () {
cb(allPads);
});
}
var converter = function (UNIX_timestamp) {
var a = new Date(UNIX_timestamp);
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = (( a.getHours() < 10) ? "0" : "") + a.getHours();
var min = ((a.getMinutes() < 10) ? "0" : "") + a.getMinutes();
var sec = ((a.getSeconds() < 10) ? "0" : "") + a.getSeconds();
return date + '. ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec;
};
var converterPad = function (UNIX_timestamp) {
var a = new Date(UNIX_timestamp);
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = (( a.getHours() < 10) ? "0" : "") + a.getHours();
var min = ((a.getMinutes() < 10) ? "0" : "") + a.getMinutes();
return date + '. ' + month + ' ' + year + ' ' + hour + ':' + min + ' Uhr';
};
function addUserToEtherpad(userName, cb) {
log('debug', 'addUserToEtherpad');
authorManager.createAuthorIfNotExistsFor(userName, null, function (err, author) {
if (err) {
log('error', 'something went wrong while creating author');
cb();
} else {
cb(author);
}
});
}
function addPadToEtherpad(padName, groupId, cb) {
log('debug', 'addPadToEtherpad');
getEtherpadGroupFromNormalGroup(groupId, function (group) {
groupManager.createGroupPad(group, padName, function (err) {
if (err) {
log('error', 'something went wrong while adding a group pad');
cb()
} else {
cb();
}
});
});
}
function deleteGroupFromEtherpad(id, cb) {
getEtherpadGroupFromNormalGroup(id, function (group) {
groupManager.deleteGroup(group, function (err) {
if (err) {
log('error', 'Something went wrong while deleting group from etherpad');
cb();
} else {
var sql = "DELETE FROM store where store.key = ?";
var updateQuery = connection2.query(sql, ["mapper2group:" + id]);
updateQuery.on('error', mySqlErrorHandler);
updateQuery.on('end', function () {
cb();
});
}
});
});
}
var deletePadFromEtherpad = function (name, groupid, cb) {
getEtherpadGroupFromNormalGroup(groupid, function (group) {
padManager.removePad(group + "$" + name);
cb();
});
};
function sendError(error, res) {
var data = {};
data.success = false;
data.error = error;
log('error', error);
res.send(data);
}
exports.expressCreateServer = function (hook_name, args, cb) {
function notRegisteredUpdate(userid, groupid, email) {
var userGroupSql = "INSERT INTO UserGroup VALUES(?, ?, 2)";
updateSql(userGroupSql, [userid, groupid], function (success) {
if (success) {
var deleteNotRegisteredSql = "DELETE FROM NotRegisteredUsersGroups where groupID = ? and email = ?";
updateSql(deleteNotRegisteredSql, [groupid, email], function (success) {
});
}
});
}
function checkInvitations(email, userid, cb) {
var userNotRegisteredSql = "select * from NotRegisteredUsersGroups where email = ?";
var notRegistereds = [];
var queryInstances = connection2.query(userNotRegisteredSql, [email]);
queryInstances.on('error', mySqlErrorHandler);
queryInstances.on('result', function (foundInstance) {
connection2.pause();
notRegistereds.push(foundInstance);
connection2.resume();
});
queryInstances.on('end', function () {
if (notRegistereds.length < 1) {
cb();
}
for (var i = 0; i < notRegistereds.length; i++) {
notRegisteredUpdate(userid, notRegistereds[i].groupID, email);
if ((i + 1) == notRegistereds.length)
cb();
}
});
}
var registerUser = function (user, cb) {
if (user.password != user.passwordrepeat) {
cb(false, PASSWORD_WRONG);
return false; // break execution early
}
var Ergebnis = user.email.toString().match(/[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+.[a-zA-Z]{2,4}/);
if (Ergebnis == null) {
cb(false, NO_VALID_MAIL);
return false; // break execution early
}
if (user.password == "") {
cb(false, PW_EMPTY);
return false; // break execution early
}
var existUser = "SELECT * from User where User.name = ?";
var retValue = existValueInDatabase(existUser, [user.email], function (exists) {
if (exists) {
cb(false, USER_EXISTS);
} else {
getPassword(function (consString) {
var msg = eMailAuth.registrationtext;
msg = msg.replace(/<url>/, user.location + "confirm/" + consString);
var message = {
text: msg,
from: eMailAuth.registrationfrom,
to: user.email + " <" + user.email + ">",
subject: eMailAuth.registrationsubject
};
var nodemailer = require('nodemailer');
var transport = nodemailer.createTransport("sendmail");
if (eMailAuth.smtp == "false")
transport.sendMail(message);
else {
emailserver.send(message, function (err) {
if (err) {
log('error', err);
}
});
}
createSalt(function (salt) {
encryptPassword(user.password, salt, function (encrypted) {
var addUserSql = "INSERT INTO User VALUES(null, ?,?, 0, 0, ?,?,?,1,0)";
var addUserQuery = connection.query(addUserSql, [user.email, encrypted, user.fullname, consString, salt]);
addUserQuery.on('error', mySqlErrorHandler);
addUserQuery.on('result', function (newUser) {
connection.pause();
checkInvitations(user.email, newUser.insertId, function () {
addUserToEtherpad(newUser.insertId, function () {
connection.resume();
});
});
});
addUserQuery.on('end', function () {
cb(true, null);
});
});
});
});
}
return exists;
});
return retValue; // return status of function call
};
var emailserver = email.server.connect({
user: eMailAuth.user,
password: eMailAuth.password,
host: eMailAuth.host,
port: eMailAuth.port,
ssl: eMailAuth.ssl
});
args.app.get('/index.html', function (req, res) {
userAuthenticated(req, function (authenticated) {
if (authenticated) {
res.redirect('home.html'); // ../home.html
} else {
var render_args = {
errors: [],
username: req.session.username
};
res.send(eejs
.require("ep_frontend_community/templates/index.ejs",
render_args));
}
});
});
args.app.get('/help.html', function (req, res) {
userAuthenticated(req, function (authenticated) {
if (authenticated) {
getUser(req.session.userId, function (found, currUser) {
var render_args;
if (currUser && currUser.length > 0) {
render_args = {
errors: [],
/* ckubu: added
support variable isadmin to frontend
*/
isadmin: currUser[0].isAdmin,
username: currUser[0].FullName
};
res.send(eejs
.require("ep_frontend_community/templates/help.ejs",
render_args));
} else {
render_args = {
errors: [],
/* ckubu: added
support variable isadmin to frontend
*/
isadmin: 0,
username: ""
};
res.send(eejs
.require("ep_frontend_community/templates/help.ejs",
render_args));
}
});
} else {
res.redirect("../index.html");
}
});
});
args.app.get('/home.html', function (req, res) {
userAuthenticated(req, function (authenticated) {
if (authenticated) {
var sql = "Select Groups.* from Groups inner join UserGroup on(UserGroup.groupID = Groups.groupID) where UserGroup.userID = ?";
getAllSql(sql, [req.session.userId], function (groups) {
getUser(req.session.userId, function (found, currUser) {
var render_args;
if (currUser) {
render_args = {
errors: [],
username: currUser[0].FullName,
/* ckubu: added
support variable isadmin to frontend
*/
isadmin: currUser[0].isAdmin,
groups: groups
};
res.send(eejs
.require("ep_frontend_community/templates/home.ejs",
render_args));
} else {
render_args = {
errors: [],
username: " ",
/* ckubu: added
support variable isadmin to frontend
*/
isadmin: 0,
groups: groups
};
res.send(eejs
.require("ep_frontend_community/templates/home.ejs",
render_args));
}
});
});
} else {
res.redirect("../index.html");
}
});
});
args.app.get('/pads.html', function (req, res) {
userAuthenticated(req, function (authenticated) {
if (authenticated) {
getUser(req.session.userId, function (found, currUser) {
if (currUser) {
var render_args = {
errors: [],
/* ckubu: added
support variable isadmin to frontend
*/
isadmin: currUser[0].isAdmin,
username: currUser[0].FullName
};
res.send(eejs
.require("ep_frontend_community/templates/pads.ejs",
render_args));
}
});
} else {
res.redirect("../index.html");
}
});
});
args.app.get('/group.html/:groupid', function (req, res) {
log('debug', req.path);
userAuthenticated(req, function (authenticated) {
log('debug', req.path + 'userAuthenticated CB');
if (authenticated) {
log('debug', req.path + 'Authenticated');
getPadsOfGroup(req.params.groupid, '', function (pads) {
log('debug', req.path + 'getPadsOfGroup CB');
getUser(req.session.userId, function (found, currUser) {
log('debug', req.path + 'getUser CB');
getGroup(req.params.groupid, function (found, currGroup) {
log('debug', req.path + 'getGroup CB');
getUserGroup(req.params.groupid, req.session.userId, function (found, currUserGroup) {
log('debug', req.path + 'getUserGroup CB');
var render_args;
if (!currUserGroup) {
render_args = {
errors: [],
/* ckubu
A System Pad Administrators has all groups in his grouplist, even
if he is not member of that group. So i changed the message to
a bit plain message
*/
//msg: "This group does not exist! Perhaps someone has deleted the group."
msg: "You are not in that group, so you can't see the group pads."
};
res.send(eejs
.require("ep_frontend_community/templates/msgtemplate.ejs",
render_args));
return;
}
var isown = currUserGroup[0].Role == 1;
if (currGroup && currUser && currUserGroup) {
render_args = {
errors: [],
id: currGroup[0].name,
groupid: currGroup[0].groupID,
/* ckubu added
Add userid for use in template "group.ejs" to allow
padowners to delete their pads..
*/
userid: req.session.userId,
username: currUser[0].FullName,
/* ckubu: added
support variable isadmin to frontend
*/
isadmin: currUser[0].isAdmin,
isowner: isown,
pads: pads,
starredPads: pads.filter(function(p) {return p.starred == 1;})
};
res.send(eejs.require("ep_frontend_community/templates/group.ejs", render_args));
} else {
render_args = {
errors: [],
msg: "This group does not exist! Perhabs anyone has deleted the group."
};
res.send(eejs.require("ep_frontend_community/templates/msgtemplate.ejs",
render_args));
}
});
});
});
});
} else {
res.redirect("../../index.html");
}
});
});
args.app.get('/groups.html', function (req, res) {
userAuthenticated(req, function (authenticated) {
if (authenticated) {
getUser(req.session.userId, function (found, currUser) {
/* ckubu changed:
System Administrators should see all Groups
*/
if ( currUser[0].isAdmin ) {
sql = "Select 1 as Role, groupID, name from Groups";
} else {
sql = "Select * from Groups inner join UserGroup on(UserGroup.groupID = Groups.groupID) where UserGroup.userID = ?";
}
getAllSql(sql, [req.session.userId], function (groups) {
for ( var i = 1 ; i < groups.length; i++ ) {
var groupMember = "SELECT * FROM UserGroup WHERE userID = " + req.session.userId + " AND groupID = ?";
existValueInDatabase(groupMember, [groups[i-1].groupID], function (exists) {
if (exists) {
groups[i-1].isMember = 1;
} else {
groups[i-1].isMember = 0;
}
});
}
var render_args = {
errors: [],
username: currUser[0].FullName,
/* ckubu: added
support variable isadmin to frontend
*/
isadmin: currUser[0].isAdmin,
groups: groups
};
res.send(eejs.require("ep_frontend_community/templates/groups.ejs", render_args));
});
});
} else {
res.redirect("../index.html");
}
});
});
/* ckubu
Add new User
*/
args.app.post('/addNewUser', function (req, res) {
new formidable.IncomingForm().parse(req, function (err, fields) {
userAuthenticated(req, function (authenticated) {
if (authenticated) {
var ret_object = {};
isAdmin([req.session.userId], function (isAdmin) {
if (isAdmin) {
var filter ;
/* validate email address */
if ( fields.userEmail.length < 1 ) {
log('debug', 'User Email not given');
log('debug', 'user email: ' + fields.userEmail);
ret_object.success = false;
ret_object.error = 'User Email not given.';
ret_object.field = 'userEmail';
res.send(ret_object);
return false;
}
filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(fields.userEmail)) {
log('debug', 'Email Address is not valid.');
log('debug', 'user email: ' + fields.userEmail);
ret_object.success = false;
ret_object.error = 'Email Address is not valid.';
ret_object.field = 'userEmail';
res.send(ret_object);
return false;
}
/* validate username */
if ( fields.userName.length < 1 ) {
log('debug', 'User Name not given.');
log('debug', 'user email: ' + fields.userName);
ret_object.success = false;
ret_object.error = 'User Name not given.';
ret_object.field = 'userName';
res.send(ret_object);
return false;
}
filter = /^[\w ]+$/;
if ( !filter.test(fields.userName)) {
log('debug', 'User Name must contain only letters, numbers, underscores and blanks.');
log('debug', 'User Name: ' + fields.userName);
ret_object.success = false;
ret_object.error = 'User Name must contain only letters, numbers, underscores and blanks.';
ret_object.field = 'userName';
res.send(ret_object);
return false;
}
/* validate password */
if ( fields.userPassword_1.length < 1 ) {
log('debug', 'Password must not be empty.');
ret_object.success = false;
ret_object.error = 'Password must not be empty.';
ret_object.field = 'userPassword_1';
res.send(ret_object);
return false;
}
if ( fields.userPassword_2 < 1 || fields.userPassword_1 != fields.userPassword_2 ) {
log('debug', 'Password entries does not matc.');
ret_object.success = false;
ret_object.error = 'Password entries does not matc.';
ret_object.field = 'userPassword_1';
res.send(ret_object);
return false;
}
var existUser = "SELECT * FROM User WHERE User.name = ?";
existValueInDatabase(existUser, [fields.userEmail], function (exists) {
if (exists) {
log('debug', 'User is already registered.');
log('debug', 'user email: ' + fields.userEmail);
ret_object.success = false;
ret_object.error = 'User is already registered';
ret_object.field = 'userEmail';
res.send(ret_object);
return false;
} else {
if ( fields.isAdmin ) {
log('info', 'User ' + fields.userEmail + ' becomes Pad Admin');
}
getPassword(function (consString) {
/*
We dont't want to sent information message here, mainly
because we had also to sent the pasword in an unencrypted email,
and sending witout account data makes no sense..
So we had to make that account ready for user, means without
registration confirmation needed (considered = 1 see below)
*/
/*
var msg = eMailAuth.registrationtext;
msg = msg.replace(/<url>/, fields.location + "confirm/" + consString);
var message = {
text: msg,
from: eMailAuth.registrationfrom,
to: fields.userEmail + " <" + fields.userEmail + ">",
subject: eMailAuth.registrationsubject
};
var nodemailer = require('nodemailer');
var transport = nodemailer.createTransport("sendmail");
if (eMailAuth.smtp == "false")
transport.sendMail(message);
else {
emailserver.send(message, function (err) {
if (err) {
log('error', err);
}
});
}
*/
createSalt(function (salt) {
encryptPassword(fields.userPassword_1, salt, function (encrypted) {
/* set "considered = 1", see above */
var addUserSql = "INSERT INTO User VALUES(null, ?,?, 1, 0, ?,?,?,1,?)";
var addUserQuery = connection.query(addUserSql, [fields.userEmail, encrypted, fields.userName, consString, salt,fields.isAdmin]);
addUserQuery.on('error', mySqlErrorHandler);
addUserQuery.on('result', function (newUser) {
connection.pause();
checkInvitations(fields.userEmail, newUser.insertId, function () {
addUserToEtherpad(newUser.insertId, function () {
connection.resume();
});
});
});
addUserQuery.on('end', function () {
cb(true, null);
});
});
});
});
}
/* tell we were sucessfully.. */
ret_object.success = true;
ret_object.isAdmin = true;
ret_object.msg = 'User ' + fields.userEmail + ' successfuly added';
res.send(ret_object);
});
} else {
log('error', 'User ' + fields.userEmail + ' has triggert "addNewUser", but user is NOT an admin!!');
ret_object.isAdmin = false;
ret_object.msg = 'User ' + fields.userEmail + ' is not an admin!!';
res.send(ret_object);
}
});
} else {
res.send("You are not logged in!!");
}
});
});
});
/* ckubu
Modify User
*/
args.app.post('/modifyUser', function (req, res) {
new formidable.IncomingForm().parse(req, function (err, fields) {
userAuthenticated(req, function (authenticated) {
if (authenticated) {
isAdmin([req.session.userId], function (isAdmin) {
if (isAdmin) {
var filter ;
var ret_object = {};
/* validate email address */
if ( fields.userEmail.length < 1 ) {
log('debug', 'User Email not given');
log('debug', 'user email: ' + fields.userEmail);
ret_object.success = false;
ret_object.error = 'User Email not given';
ret_object.field = 'modifyUserEmail';
res.send(ret_object);
return false;
}
/*
filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(fields.userEmail)) {
log('debug', 'user email: ' + fields.userEmail);
log('debug', 'Email Address is not valid.');
ret_object.success = false;
ret_object.error = 'Email Address is not valid.';
ret_object.field = 'modifyUserEmail';
res.send(ret_object);
return false;
}
*/
if ( (fields.userPassword_1.length > 0 || fields.userPassword_2 > 0)
&& fields.userPassword_1 != fields.userPassword_2) {
log('debug', 'Password entries does not match');
ret_object.success = false;
ret_object.error = 'Password entries does not match';
ret_object.field = 'modyfyUserPassword_1';
res.send(ret_object);
return false;
}