-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathapi.js
1652 lines (1506 loc) · 52.7 KB
/
api.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
/**
* vim:set sw=2 ts=2 sts=2 ft=javascript expandtab:
*
* # API Module
*
* ## License
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
* ## Description
*
* This module holds all public functions, used for the API of mypads.
* Please refer to binded function when no details are given.
*/
var rFS = require('fs').readFileSync;
// External dependencies
var ld = require('lodash');
var passport = require('passport');
var jwt = require('jsonwebtoken');
var testMode = false;
var express;
try {
// Normal case : when installed as a plugin
express = require('ep_etherpad-lite/node_modules/express');
}
catch (e) {
// Testing case : we need to mock the express dependency
testMode = true;
express = require('express');
}
var settings;
try {
// Normal case : when installed as a plugin
settings = require('ep_etherpad-lite/node/utils/Settings');
}
catch (e) {
// Testing case : we need to mock the express dependency
if (process.env.TEST_LDAP) {
settings = {
'ep_mypads': {
'ldap': {
'url': 'ldap://rroemhild-test-openldap',
'bindDN': 'cn=admin,dc=planetexpress,dc=com',
'bindCredentials': 'GoodNewsEveryone',
'searchBase': 'ou=people,dc=planetexpress,dc=com',
'searchFilter': '(uid={{username}})',
'properties': {
'login': 'uid',
'email': 'mail',
'firstname': 'givenName',
'lastname': 'sn'
},
'defaultLang': 'fr'
}
}
};
} else {
settings = {};
}
}
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var decode = require('js-base64').Base64.decode;
// Local dependencies
var conf = require('./configuration.js');
var mail = require('./mail.js');
var user = require('./model/user.js');
var userCache = require('./model/user-cache.js');
var group = require('./model/group.js');
var pad = require('./model/pad.js');
var auth = require('./auth.js');
var perm = require('./perm.js');
var common = require('./model/common.js');
module.exports = (function () {
'use strict';
var api = {};
api.initialRoute = '/mypads/api/';
var authAPI;
var configurationAPI;
var userAPI;
var groupAPI;
var padAPI;
var cacheAPI;
var statsAPI;
/**
* `init` is the first function that takes an Express app as argument.
* It initializes authentication, permissions and also all API requirements,
* particularly mypads routes.
*
* It needs to be fast to finish *before* YAJSML plugin (which takes over all
* requests otherwise and refuse anything apart GET and HEAD HTTP methods.
* That's why api.init is used without any callback and is called before
* storage initialization.
*/
api.init = function (app, callback) {
// Use this for .JSON storage
app.use(bodyParser.json());
app.use(cookieParser());
app.use('/mypads', express.static(__dirname + '/static'));
if (testMode) {
// Only allow functional testing in testing mode
app.use('/mypads/functest', express.static(__dirname + '/spec/frontend'));
}
var rFSOpts = { encoding: 'utf8' };
api.l10n = {
mail: {
de: JSON.parse(rFS(__dirname + '/templates/mail_de.json', rFSOpts)),
en: JSON.parse(rFS(__dirname + '/templates/mail_en.json', rFSOpts)),
es: JSON.parse(rFS(__dirname + '/templates/mail_es.json', rFSOpts)),
fr: JSON.parse(rFS(__dirname + '/templates/mail_fr.json', rFSOpts)),
it: JSON.parse(rFS(__dirname + '/templates/mail_it.json', rFSOpts)),
}
};
auth.init(app);
authAPI(app);
configurationAPI(app);
userAPI(app);
groupAPI(app);
padAPI(app);
cacheAPI(app);
statsAPI(app);
perm.init(app);
/**
* `index.html` is a simple lodash template
*/
var idxTpl = ld.template(rFS(__dirname + '/templates/index.html', rFSOpts));
var idxHandle = function (req, res) {
var mypadsURL = req.protocol + '://' + req.header('host') + req.path;
return res.send(idxTpl({
HTMLExtraHead: conf.get('HTMLExtraHead'),
hideHelpBlocks: conf.get('hideHelpBlocks'),
mypadsURL: mypadsURL
}));
};
app.get('/mypads/index.html', idxHandle);
app.get('/mypads/', idxHandle);
callback(null);
};
/**
* ## Internal functions helpers
*
* These functions are not private like with closures, for testing purposes,
* but they are expected be used only internally by other MyPads functions.
*/
var fn = {};
/**
* `get` internal takes a mandatory `module` argument to call its `get` method.
* It will use `req.params.key` to get the database record and returns an
* according response. By the way, an optional `cond`ition can be passed. It
* is a function that takes the result of the module.get and *true* or
* *false*. If *false*, an error will be returned.
*/
fn.get = function (module, req, res, next, cond) {
try {
module.get(req.params.key, function (err, val) {
if (err) {
return res.status(404).send({
error: err.message,
key: req.params.key
});
}
if (cond && !cond(val)) {
if (conf.get('allPadsPublicsAuthentifiedOnly')) {
return fn.denied(res, 'BACKEND.ERROR.AUTHENTICATION.MUST_BE');
} else {
return fn.denied(res, 'BACKEND.ERROR.AUTHENTICATION.DENIED_RECORD');
}
} else {
return res.send({ key: req.params.key, value: val });
}
});
}
catch (e) {
res.status(400).send({ error: e.message });
}
};
/**
* `set` internal takes :
*
* - a `setFn` bounded function targetted the original `set` from the module
* used in the case of this public API
* - `key` and `value` that has been given to the `setFn` function
* - `req` and `res` express request and response
*/
fn.set = function (setFn, key, value, req, res) {
try {
setFn(function (err, data) {
if (err) { return res.status(400).send({ error: err.message }); }
res.send({ success: true, key: key || data._id, value: data || value });
});
}
catch (e) {
res.status(400).send({ error: e.message });
}
};
/**
* `del` internal takes four arguments :
*
* - `delFn` bounded function targetted the original `del` method from the
* module used
* - classical `req` and `res` express parameters, with mandatory
* *req.params.key*.
*/
fn.del = function (delFn, req, res) {
var key = req.params.key;
delFn(key, function (err) {
if (err) { return res.status(404).send({ error: err.message }); }
res.send({ success: true, key: key });
});
};
/**
* `denied` is an internal helper that just takes `res` express response and
* an `errorCode` string. It returns an unothorized status.
*/
fn.denied = function (res, errCode) {
return res
.status(401)
.send({ error: errCode });
};
/**
* `mailMessage` is an internal helper that computed email templates. It takes
* the `tpl` key of the template and the `data` needed. Optionally, a
* `lang`uage can be defined.
* It returns the computed template.
*/
fn.mailMessage = function (tpl, data, lang) {
lang = lang || conf.get('defaultLanguage');
tpl = ld.template(api.l10n.mail[lang][tpl]);
return tpl(data);
};
/**
* `ensureAuthenticated` internal is an Express middleware takes `req`,
* `res` and `next`. It returns error or lets the next middleware go.
* It relies on `passport.authenticate` with default strategy : *jwt*.
*/
fn.ensureAuthenticated = passport.authenticate('jwt', { session: false });
/**
* `isAdmin` internal is a function that checks if current connnected user is
* an Etherpad instance admin or not. It returns a boolean.
*/
fn.isAdmin = function (req) {
var token = req.query.auth_token || req.body.auth_token;
if (!token) { return false; }
try {
var jwt_payload = jwt.verify(token, auth.secret);
var admin = auth.adminTokens[jwt_payload.login];
return (admin && (admin.key === jwt_payload.key));
}
catch (e) { return false; }
};
/**
* `ensureAdmin` internal is an Express middleware that takes classic `req`,
* `res` and `next`. It returns an error if the connected user is not
* an Etherpad instance admin.
*/
fn.ensureAdmin = function (req, res, next) {
if (!fn.isAdmin(req)) {
return fn.denied(res, 'BACKEND.ERROR.AUTHENTICATION.ADMIN');
} else {
return next();
}
};
/**
* `ensureAdminOrSelf` internal Express middleware takes the classic `req`,
* `res` and `next`. It returns an error if the connected user tries to manage
* users other than himself and he is not an Etherpad logged admin.
*/
fn.ensureAdminOrSelf = function (req, res, next) {
var isAdmin = fn.isAdmin(req);
var token = (req.body.auth_token || req.query.auth_token);
var login = req.params.key;
var u = auth.fn.getUser(token);
var isSelf = (u && login === u.login);
if (isSelf) { req.mypadsLogin = u.login; }
if (!isAdmin && !isSelf) {
return fn.denied(res, 'BACKEND.ERROR.AUTHENTICATION.DENIED');
} else {
return next();
}
};
/**
* ## Authentication API
*/
authAPI = function (app) {
var authRoute = api.initialRoute + 'auth';
/**
* POST method : check, method returning success or error if given *login*
* and *password* do not match to what is stored into database
*
* Sample URL:
* http://etherpad.ndd/mypads/api/auth/check
*/
app.post(authRoute + '/check', fn.ensureAuthenticated,
function (req, res) {
auth.fn.localFn(req.body.login, req.body.password, function (err, u) {
if (err) { return res.status(400).send({ error: err.message }); }
if (!u) {
var emsg = 'BACKEND.ERROR.AUTHENTICATION.PASSWORD_INCORRECT';
return res.status(400).send({ error: emsg });
}
res.status(200).send({ success: true });
});
}
);
/**
* GET method : login/cas, method redirecting to home if auth
* is a success, plus fixes a `login` session.
* Only used with CAS authentication
*
* Sample URL:
* http://etherpad.ndd/mypads/api/auth/login/cas
*/
app.post(authRoute + '/login/cas', function (req, res) {
auth.fn.casAuth(req, res, function(err, infos) {
if (err) { return res.status(400).send({ error: err.message }); }
// JWTFn false arg = non-admin authentication
auth.fn.JWTFn(req, infos, false, function (err, u, info) {
if (err) { return res.status(400).send({ error: err.message }); }
if (!u) { return res.status(400).send({ error: info.message }); }
if (u.active) {
var token = {
login: u.login,
key: auth.tokens[u.login].key
};
return res.status(200).send({
success: true,
user: ld.omit(u, 'password'),
token: jwt.sign(token, auth.secret)
});
} else {
var msg = 'BACKEND.ERROR.AUTHENTICATION.ACTIVATION_NEEDED';
return fn.denied(res, msg);
}
});
});
});
/**
* POST method : login, method returning user object minus password if auth
* is a success, plus fixes a `login` session.
*
* Sample URL:
* http://etherpad.ndd/mypads/api/auth/login
*/
app.post(authRoute + '/login', function (req, res) {
var eplAuthorToken;
if (typeof(req.body.login) !== 'undefined' && typeof(req.cookies['token-'+req.body.login]) !== 'undefined') {
eplAuthorToken = req.cookies['token-'+req.body.login];
} else if (typeof(req.cookies.token) !== 'undefined') {
eplAuthorToken = req.cookies.token;
}
auth.fn.JWTFn(req, req.body, false, function (err, u, info) {
if (err) { return res.status(400).send({ error: err.message }); }
if (!u) { return res.status(400).send({ error: info.message }); }
if (u.active) {
var token = {
login: u.login,
key: auth.tokens[u.login].key
};
if (!u.eplAuthorToken && typeof(eplAuthorToken) !== 'undefined') {
u.eplAuthorToken = eplAuthorToken;
var uToUpdate = ld.cloneDeep(u);
uToUpdate.password = req.body.password;
user.set(uToUpdate, function (err) {
if (err) { return res.status(400).send({ error: err.message }); }
return res.status(200).send({
success: true,
user: ld.omit(u, 'password'),
token: jwt.sign(token, auth.secret)
});
});
} else {
return res.status(200).send({
success: true,
user: ld.omit(u, 'password'),
token: jwt.sign(token, auth.secret)
});
}
} else {
var msg = 'BACKEND.ERROR.AUTHENTICATION.ACTIVATION_NEEDED';
return fn.denied(res, msg);
}
});
});
/**
* GET method : logout, method that destroy current cached token
*
* Sample URL:
* http://etherpad.ndd/mypads/api/auth/logout
*/
app.get(authRoute + '/logout', fn.ensureAuthenticated, function (req, res) {
delete auth.tokens[req.mypadsLogin];
res.status(200).send({ success: true });
});
/**
* POST method : admin login, method that checks credentials and create
* admin token in case of success
*
* Sample URL:
* http://etherpad.ndd/mypads/api/auth/admin/login
*/
app.post(authRoute + '/admin/login', function (req, res) {
auth.fn.JWTFn(req, req.body, true, function (err, u, info) {
if (err) { return res.status(400).send({ error: err.message }); }
if (!u) { return res.status(400).send({ error: info.message }); }
var token = {
login: u.login,
key: auth.adminTokens[u.login].key
};
return res.status(200).send({
success: true,
token: jwt.sign(token, auth.secret)
});
});
});
/**
* GET method : admin logout, method that destroy current admin token
*
* Sample URL:
* http://etherpad.ndd/mypads/api/auth/admin/logout
*/
app.get(authRoute + '/admin/logout', fn.ensureAdmin, function (req, res) {
delete auth.adminTokens[req.mypadsLogin];
return res.status(200).send({ success: true });
});
};
/**
* ## Configuration API
*/
configurationAPI = function (app) {
var confRoute = api.initialRoute + 'configuration';
/**
* GET method : get all configuration plus user info if logged, else config
* public fields.
*
* Sample URL:
* http://etherpad.ndd/mypads/api/configuration
*/
app.get(confRoute, function (req, res) {
var u = auth.fn.getUser(req.query.auth_token);
var isAdmin = fn.isAdmin(req);
var action = (isAdmin === true) ? 'all' : 'public';
var value = conf[action]();
var resp = { value: value };
resp.auth = isAdmin || !!u;
if (u) { resp.user = u; }
/* Fix IE11 stupid habit of caching AJAX calls
* See http://www.dashbay.com/2011/05/internet-explorer-caches-ajax/
* and https://framagit.org/framasoft/Etherpad/ep_mypads/issues/220
*/
res.set('Expires', '-1');
res.send(resp);
});
/**
* GET method : `configuration.get` key
* Reserved to Etherpad administrators
*
* Sample URL:
* http://etherpad.ndd/mypads/api/configuration/something
*/
app.get(confRoute + '/:key', fn.ensureAdmin, function (req, res) {
var value = conf.get(req.params.key);
if (ld.isUndefined(value)) {
return res.status(404).send({
error: 'BACKEND.ERROR.CONFIGURATION.KEY_NOT_FOUND',
key: req.params.key
});
}
/* Fix IE11 stupid habit of caching AJAX calls
* See http://www.dashbay.com/2011/05/internet-explorer-caches-ajax/
* and https://framagit.org/framasoft/Etherpad/ep_mypads/issues/220
*/
res.set('Expires', '-1');
res.send({ key: req.params.key, value: value });
});
/**
* POST/PUT methods : `configuration.set` key and value on initial
* Reserved to Etherpad administrators
*
* Sample URL for POST:
* http://etherpad.ndd/mypads/api/configuration
* for PUT
* http://etherpad.ndd/mypads/api/configuration/something
*/
var _set = function (req, res) {
var key = (req.method === 'POST') ? req.body.key : req.params.key;
var value = req.body.value;
var setFn = ld.partial(conf.set, key, value);
fn.set(setFn, key, value, req, res);
};
app.post(confRoute, fn.ensureAdmin, _set);
app.put(confRoute + '/:key', fn.ensureAdmin, _set);
/**
* DELETE method : `configuration.del` key
* Reserved to Etherpad administrators
*
* Sample URL:
* http://etherpad.ndd/mypads/api/configuration/something
*/
app.delete(confRoute + '/:key', fn.ensureAdmin,
ld.partial(fn.del, conf.del));
/**
* GET method
*
* Return the value of useFirstLastNameInPads configuration setting
*
* Sample URL:
* http://etherpad.ndd/mypads/api/configuration/public/usefirstlastname
*/
app.get(confRoute + '/public/usefirstlastname', function (req, res) {
return res.send({ success: true, usefirstlastname: conf.get('useFirstLastNameInPads') });
});
/**
* GET method
*
* Return the value of allPadsPublicsAuthentifiedOnly configuration setting
* + given pad's group if allPadsPublicsAuthentifiedOnly is true
*
* Sample URL:
* http://etherpad.ndd/mypads/api/configuration/public/allpadspublicsauthentifiedonly
*/
app.get(confRoute + '/public/allpadspublicsauthentifiedonly', function (req, res) {
var confValue = conf.get('allPadsPublicsAuthentifiedOnly');
var data = {
success: true,
allpadspublicsauthentifiedonly: confValue
};
/* Fix IE11 stupid habit of caching AJAX calls
* See http://www.dashbay.com/2011/05/internet-explorer-caches-ajax/
* and https://framagit.org/framasoft/Etherpad/ep_mypads/issues/220
*/
res.set('Expires', '-1');
if (confValue) {
pad.get(req.query.pid, function (err, p) {
if (err) {
return res.send({ success: false, error: err });
}
data.group = p.group;
return res.send(data);
});
} else {
return res.send(data);
}
});
};
/**
* ## User API
*
* Most methods need `fn.ensureAdminOrSelf`
*/
userAPI = function (app) {
var userRoute = api.initialRoute + 'user';
var allUsersRoute = api.initialRoute + 'all-users';
var searchUsersRoute = api.initialRoute + 'search-users';
var userlistRoute = api.initialRoute + 'userlist';
/**
* GET method : `user.userlist` with crud fixed to *get* and current login.
* Returns user userlists
* ensureAuthenticated needed
*
* Sample URL:
* http://etherpad.ndd/mypads/api/userlist
*/
app.get(userlistRoute, fn.ensureAuthenticated,
function (req, res) {
var opts = { crud: 'get', login: req.mypadsLogin };
user.userlist(opts, function (err, u) {
if (err) { return res.status(400).send({ error: err.message }); }
/* Fix IE11 stupid habit of caching AJAX calls
* See http://www.dashbay.com/2011/05/internet-explorer-caches-ajax/
* and https://framagit.org/framasoft/Etherpad/ep_mypads/issues/220
*/
res.set('Expires', '-1');
res.send({ value: u.userlists });
});
}
);
/**
* POST method : `user.userlist` creation with crud fixed to *add*, current
* login and userlist parameters, name and optionnally user logins
* ensureAuthenticated needed
*
* Sample URL :
* http://etherpad.ndd/mypads/api/userlist
*/
app.post(userlistRoute, fn.ensureAuthenticated,
function (req, res) {
try {
var users = { absent: [], present: [] };
var lm = req.body.loginsOrEmails;
if (lm) { users = userCache.fn.getIdsFromLoginsOrEmails(lm); }
var opts = {
crud: 'add',
login: req.mypadsLogin,
name: req.body.name
};
if (users.uids) { opts.uids = users.uids; }
user.userlist(opts, function (err, u) {
if (err) { return res.status(400).send({ error: err.message }); }
return res.send({
success: true,
value: u.userlists,
present: users.present,
absent: users.absent
});
});
}
catch (e) { return res.status(400).send({ error: e.message }); }
}
);
/**
* PUT method : `user.userlist` update with crud fixed to *set*, current
* login, mandatory `ulistid` via request parameter and userlist arguments,
* `name` or user `logins`
* ensureAuthenticated needed
*
* Sample URL :
* http://etherpad.ndd/mypads/api/userlist/xxx
*/
app.put(userlistRoute + '/:key', fn.ensureAuthenticated,
function (req, res) {
try {
var users = { absent: [], present: [] };
var lm = req.body.loginsOrEmails;
if (lm) { users = userCache.fn.getIdsFromLoginsOrEmails(lm); }
var opts = {
crud: 'set',
login: req.mypadsLogin,
ulistid: req.params.key,
name: req.body.name
};
if (users.uids) { opts.uids = users.uids; }
user.userlist(opts, function (err, u) {
if (err) { return res.status(400).send({ error: err.message }); }
return res.send({
success: true,
value: u.userlists,
present: users.present,
absent: users.absent
});
});
}
catch (e) { return res.status(400).send({ error: e.message }); }
}
);
/**
* DELETE method : `user.userlist` removal with crud fixed to *del*, current
* login, mandatory `ulistid` via request parameter
* ensureAuthenticated needed
*
* Sample URL :
* http://etherpad.ndd/mypads/api/userlist/xxx
*/
app.delete(userlistRoute + '/:key', fn.ensureAuthenticated,
function (req, res) {
try {
var opts = {
crud: 'del',
login: req.mypadsLogin,
ulistid: req.params.key
};
user.userlist(opts, function (err, u) {
if (err) { return res.status(400).send({ error: err.message }); }
res.send({ success: true, value: u.userlists });
});
}
catch (e) { return res.status(400).send({ error: e.message }); }
}
);
/**
* GET method : `user.get` login (key)
*
* Sample URL:
* http://etherpad.ndd/mypads/api/user/someone
*/
app.get(userRoute + '/:key', fn.ensureAdminOrSelf,
ld.partial(fn.get, user));
/**
* GET method : get all users from cache
*
* exemple: {
* usersCount: 1,
* users: {
* foo: {
* email: [email protected],
* firstname: Foo,
* lastname: Bar
* }
* }
* }
*
* Sample URL:
* http://etherpad.ndd/mypads/api/all-users
*/
app.get(allUsersRoute, fn.ensureAdmin,
function (req, res) {
var emails = ld.reduce(userCache.emails, function (result, n, key) {
result[n] = key;
return result;
}, {});
var users = ld.reduce(userCache.logins, function (result, n, key) {
result[key] = {
email: emails[n],
firstname: userCache.firstname[n],
lastname: userCache.lastname[n]
};
return result;
}, {});
res.send({ users: users, usersCount: ld.size(users) });
}
);
/**
* GET method : search users from their firstname, lastname, login or email
*
* exemple: {
* usersCount: 1,
* users: {
* foo: {
* email: [email protected],
* firstname: Foo,
* lastname: Bar
* }
* }
* }
*
* Sample URL:
* http://etherpad.ndd/mypads/api/search-users/parker
*/
app.get(searchUsersRoute + '/:key', fn.ensureAdmin,
function (req, res) {
var users = userCache.fn.searchUserInfos(req.params.key);
res.send({ users: users, usersCount: ld.size(users) });
}
);
// `set` for POST and PUT, see below
var _set = function (req, res) {
var key;
var value = req.body;
var stop;
if (req.method === 'POST' && !fn.isAdmin(req)) {
if (conf.isNotInternalAuth() || !conf.get('openRegistration')) {
stop = true;
res.status(400).send({ error: 'BACKEND.ERROR.AUTHENTICATION.NO_REGISTRATION' });
} else {
key = req.body.login;
if (conf.get('checkMails')) {
var token = mail.genToken({ login: key, action: 'accountconfirm' });
var url = conf.get('rootUrl') +
'/mypads/index.html?/accountconfirm/' + token;
console.log(url);
var lang = (function () {
if (ld.includes(ld.keys(conf.cache.languages), req.body.lang)) {
return req.body.lang;
} else {
return conf.get('defaultLanguage');
}
})();
var subject = fn.mailMessage('ACCOUNT_CONFIRMATION_SUBJECT', {
title: conf.get('title') });
var message = fn.mailMessage('ACCOUNT_CONFIRMATION', {
login: key,
title: conf.get('title'),
url: url,
duration: conf.get('tokenDuration')
}, lang);
mail.send(req.body.email, subject, message, function (err) {
if (err) {
stop = true;
return res.status(501).send({ error: err });
}
}, lang);
}
}
} else {
key = req.params.key;
value.login = req.body.login || key;
value._id = userCache.logins[key];
}
// Update needed session values
if (!stop) {
var u = auth.fn.getUser(req.body.auth_token);
if (u && !fn.isAdmin(req)) {
auth.tokens[u.login].color = req.body.color || u.color;
if (!ld.isUndefined(req.body.useLoginAndColorInPads)) {
auth.tokens[u.login].useLoginAndColorInPads = req.body.useLoginAndColorInPads;
}
}
if (fn.isAdmin(req) && req.method !== 'POST') {
delete value.auth_token;
delete value.passwordConfirm;
user.get(value.login, function (err, u) {
if (err) { return res.status(400).send({ error: err.message }); }
if (value.password) {
common.hashPassword(null, value.password, function (err, pass) {
if (err) { return res.status(400).send({ error: err }); }
value.password = pass;
ld.assign(u, value);
var setFn = ld.partial(user.fn.set, u);
fn.set(setFn, key, u, req, res);
});
} else {
ld.assign(u, value);
var setFn = ld.partial(user.fn.set, u);
fn.set(setFn, key, u, req, res);
}
});
} else {
var setFn = ld.partial(user.set, value);
fn.set(setFn, key, value, req, res);
}
}
};
/**
* POST method : `user.set` with user value for user creation
* Only method without permission verification
*
* Sample URL:
* http://etherpad.ndd/mypads/api/user
*/
app.post(userRoute, _set);
/**
* PUT method : `user.set` with user key/login plus value for existing user
*
* Sample URL:
* http://etherpad.ndd/mypads/api/user/someone
*/
app.put(userRoute + '/:key', fn.ensureAdminOrSelf, _set);
/**
* DELETE method : `user.del` with user key/login
* Destroy session if self account removal
*
* Sample URL:
* http://etherpad.ndd/mypads/api/user/someone
*/
app.delete(userRoute + '/:key', fn.ensureAdminOrSelf, function (req, res) {
var isSelf = (req.params.key === req.mypadsLogin);
if (isSelf) { delete auth.tokens[req.mypadsLogin]; }
fn.del(user.del, req, res);
});
/**
* POST method : `user.mark` with user session login, bookmark type and key
* Only need ensureAuthenticated because use own login for marking
*
* Sample URL:
* http://etherpad.ndd/mypads/api/usermark
*/
app.post(userRoute + 'mark', fn.ensureAuthenticated,
function (req, res) {
try {
user.mark(req.mypadsLogin, req.body.type, req.body.key,
function (err) {
if (err) { return res.status(404).send({ error: err.message }); }
res.send({ success: true });
}
);
}
catch (e) { res.status(400).send({ error: e.message }); }
}
);
/**
* POST method : special password recovery with mail sending.
* Need to have the email address into the body
*
* Sample URL:
* http://etherpad.ndd/mypads/api/passrecover
*/
app.post(api.initialRoute + 'passrecover', function (req, res) {
var email = req.body.email;
var err;
if (conf.isNotInternalAuth()) {
err = 'BACKEND.ERROR.AUTHENTICATION.NO_RECOVER';
return res.status(400).send({ error: err });
}
if (!ld.isEmail(email)) {
err = 'BACKEND.ERROR.TYPE.MAIL';
return res.status(400).send({ error: err });
}
if (!userCache.emails[email]) {
err = 'BACKEND.ERROR.USER.NOT_FOUND';
return res.status(404).send({ error: err });
}
if (conf.get('rootUrl').length === 0) {
err = 'BACKEND.ERROR.CONFIGURATION.ROOTURL_NOT_CONFIGURED';
return res.status(501).send({ error: err });
}
user.get(email, function (err, u) {
if (err) { return res.status(400).send({ error: err }); }
var token = mail.genToken({ login: u.login, action: 'passrecover' });
console.log(conf.get('rootUrl') + '/mypads/index.html?/passrecover/' +
token);
var subject = fn.mailMessage('PASSRECOVER_SUBJECT', {
title: conf.get('title') }, u.lang);
var message = fn.mailMessage('PASSRECOVER', {
login: u.login,
title: conf.get('title'),
url: conf.get('rootUrl') + '/mypads/index.html?/passrecover/' + token,