forked from geneontology/noctua
-
Notifications
You must be signed in to change notification settings - Fork 1
/
barista.js
2656 lines (2258 loc) · 73.2 KB
/
barista.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
////
//// Communications, translation, and authorization and authentication
//// server for Minerva and Noctua clients.
////
//// If I spin the server out into a different project, what's added
//// above the MME laucher/base and messenger client code is:
////
//// barista.js
//// static/messenger.html
//// node_modules/socket.io/
////
//// : node barista.js --debug 0 --users /tmp/users.yaml --groups /tmp/groups.yaml --public http://localhost:3400 --self http://localhost:3400 --context minerva_local --repl 7887
////
// Required shareable Node libs.
var mustache = require('mustache');
var fs = require('fs');
var yaml = require('yamljs');
var url = require('url');
var us = require('underscore');
var querystring = require('querystring');
var crypto = require('crypto');
var path = require('path');
var url = require('url');
var vantage = require('vantage')();
// Required add-on libs.
var bbop = require('bbop');
//var bbopx = require('bbopx');
var amigo = require('amigo2');
var bar_response = require('bbop-response-barista');
// We will require our own http client for proxying POST requests with
// modifications.
var http = require('http');
///
/// Helpers.
///
function ll(arg1){
console.log('barista [' + (new Date()).toJSON() + ']: ', arg1);
}
function _die(message){
console.error('BARISTA [' + (new Date()).toJSON() + ']: ' + message);
process.exit(-1);
}
// Aliases.
var each = bbop.core.each;
var what_is = bbop.core.what_is;
var is_defined = bbop.core.is_defined;
var clone = bbop.core.clone;
///
/// REs to compile once.
///
// Recognize jQuery JSONP and extract payload.
var jsonp_re = /^jQuery[\d\_]+\((.*)\)$/;
// Cached static routes.
var js_re = /\.js$/;
var css_re = /\.css$/;
var html_re = /\.html$/;
///
/// CLI arguments and runtime environment.
///
var notw = 'Barista';
// CLI handling.
var argv = require('minimist')(process.argv.slice(2));
// // Where the world thinks Barista is.
// var publoc = argv['p'] || argv['public'] || 'http://localhost:3400';
// ll('Barista location (public/persona): ' + publoc);
// Where Barista thinks it is in the world.
var runloc = argv['s'] || argv['self'] || 'http://localhost:3400';
ll('Barista location (self): ' + runloc);
var u = url.parse(runloc);
var runport = u.port || 80; // be expicit about ports
// Pull in and keyify the contributor information.
var user_fname = argv['u'] || argv['users'];
if( ! user_fname ){
_die('Option (u|users) is required.');
// Make sure extant, etc.
var fstats = fs.statSync(user_fname);
if( ! fstats.isFile() ){
_die('Option (u|users) is not a file: ' + user_fname);
}
}else{
ll('Will pull user info from: ' + user_fname);
}
// Pull in and keyify the group information.
var group_fname = argv['g'] || argv['groups'];
if( ! group_fname ){
_die('Option (g|groups) is required.');
// Make sure extant, etc.
var gstats = fs.statSync(group_fname);
if( ! gstats.isFile() ){
_die('Option (g|groups) is not a file: ' + group_fname);
}
}else{
ll('Will pull group info from: ' + group_fname);
}
// See if we want to use the (for now) optional barista context.
var barista_context = argv['c'] || argv['context'] || 'go';
if( barista_context ){
ll('Barista operate as in context: "' + barista_context + '"');
}else{
ll('Barista will try to operate without context.');
}
// Try and see if we run the optional repl port.
var barista_repl_port = null;
var barista_repl_port_raw = argv['r'] || argv['repl'] || null;
if( barista_repl_port_raw ){
var raw_port = parseInt(barista_repl_port_raw);
if( raw_port && isNaN(raw_port) === false ){
barista_repl_port = raw_port;
ll('Barista REPL will listen (locally) at: ' + barista_repl_port);
}else{
ll('Unable to parse Bariata REPL: ' + barista_repl_port_raw);
}
}else{
ll('Barista will not run REPL.');
}
// Debug level barista_debug
var barista_debug = argv['d'] || argv['debug'] || 0;
if( barista_debug ){ barista_debug = parseInt(barista_debug); }
ll('Barista debug level: ' + barista_debug);
if (barista_debug > 0) {
// Execute this before require('socket.io')
// Alternatively, set DEBUG='socket.io:*' via the shell environment.
process.env['DEBUG'] = process.env['DEBUG'] + ' xsocket.io:*';
}
// CLI handling.
var argv = require('minimist')(process.argv.slice(2));
var secloc = argv['x'] || argv['secrets'];
if( ! secloc ){
secloc = './secrets';
ll('Secrets location defaulting to: ' + secloc);
}
// Make sure secloc extant, etc.
var fstats = null;
try {
fstats = fs.statSync(secloc);
}catch(e){
_die('Option secrets location does not exist: ' + secloc);
}
if( ! fstats.isDirectory() ){
_die('Option (x|secrets) is not a directory: ' + secloc);
}else{
ll('Will use secrets directory at: ' + secloc);
}
// Define bogus users.
// TODO: Put out into private file on filesystem; still report on startup.
var rand_user_token = bbop.core.randomness(4);
ll('Anonymous editor token: ' + rand_user_token);
var bogus_users = [
{
email: 'spam@genkisugi.net',
token: '123',
nickname: 'kltm (editor)',
uri: 'GOC:kltm',
'user-type': 'allow-edit'
},
{
email: 'spam@genkisugi.net',
token: '000',
nickname: 'kltm (admin)',
uri: 'GOC:kltm',
'user-type': 'allow-admin'
},
// Create a random bogus user for this barista run.
{
email: 'anonymous@localhost',
token: rand_user_token,
nickname: 'anonymous',
uri: 'TEMP:anonymous',
'user-type': 'allow-edit'
}
];
///
/// ModelCubby: per-model message caching management.
///
var ModelCubby = function(){
var self = this;
// All data here.
var cubby = {};
/*
* Function: dropoff
*
* returns true if new, false if update
*
* Parameters:
* model - model id
* namespace - namespace
* key - key
* value - value
*
* Returns:
* boolean
*/
self.dropoff = function(model, namespace, key, value){
var ret = null;
// Ensure existence of entities.
if( typeof(cubby[model]) === 'undefined' ){
cubby[model] = {};
}
if( typeof(cubby[model][namespace]) === 'undefined' ){
cubby[model][namespace] = {};
}
// Decide the return type.
if( typeof(cubby[model][namespace][key]) === 'undefined' ){
ret = true;
}else{
ret = false;
}
// Add to data bundle.
cubby[model][namespace][key] = value;
//ll('cubby dropoff: '+ key + ', ', value);
return ret;
};
/*
* returns hash for specified namespace
*/
self.pickup = function(model, namespace){
var ret = {};
// Give non-empty answer only if defined.
//ll('data: ', cubby);
if( typeof(cubby[model]) !== 'undefined' &&
typeof(cubby[model][namespace]) !== 'undefined' ){
ret = cubby[model][namespace];
}
return ret;
};
/*
* number: count of models known to cubby
*/
self.model_count = function(){
var ret = Object.keys(cubby).length;
return ret;
};
/*
* number: count of namespaces in a model known to cubby
*/
self.namespace_count = function(model){
var ret = 0;
if( typeof(cubby[model]) !== 'undefined' ){
ret = Object.keys(cubby[model]).length;
}
return ret;
};
/*
* number: count of keys in a namespaces in a model known to cubby
*/
self.key_count = function(model, namespace){
var ret = 0;
if( typeof(cubby[model]) !== 'undefined' &&
typeof(cubby[model][namespace]) !== 'undefined' ){
ret = Object.keys(cubby[model][namespace]).length;
}
return ret;
};
};
///
/// Backend application authorization monitor.
///
var AppGuard = function(app_list){
var self = this;
// Assemble easy-to-access information for all of the apps behind
// Barista.
var app_by_namespace = {};
each(app_list,
function(a){
var aid = a['id'];
app_by_namespace[aid] = {
"target": a['target'],
"public": a['public']
};
each(a['public'],
function(p){
app_by_namespace[aid]['public'][p] = true;
});
});
/*
* true or false.
*/
self.has_app = function(namespace){
var ret = false;
if( app_by_namespace[namespace] ){
ret = true;
}
return ret;
};
/*
* string or null.
*/
self.app_target = function(namespace){
var ret = null;
if( app_by_namespace[namespace] ){
ret = app_by_namespace[namespace]['target'];
}
return ret;
};
/*
* true or false.
*/
self.is_public = function(namespace, path){
var ret = false;
if( self.has_app(namespace) ){
if( app_by_namespace[namespace]['public'][path] ){
ret = true;
}
}
return ret;
};
};
///
/// User information/sessions/login.
///
// BUG/TODO: Currently, Barista tokens do not expire. Need to
// implement either: a new token every response or rolling time window
// which is searched.
// {day1: {SET2}, day2: {SET2}}
var Sessioner = function(auth_list, group_list){
var self = this;
// NOTE: Order is important here--the later privs override earlier
// ones.
var known_user_types = [
'allow-edit', // can edit models
'allow-admin' // has powers
];
var ucolor_list = [
'red', 'green', 'purple', 'blue', 'brown', 'black', 'orange'
];
// Hashify the contents of the group listing for later lookup.
var group_info = {};
us.each(group_list, function(group){
if( us.isString(group['id']) && us.isString(group['label']) ){
group_info[group['id']] = group;
}
});
// Generate a new token.
function get_token(){
var token = bbop.core.randomness(20);
return token;
}
// Colors.
function get_color(){
var rci = Math.floor(Math.random() * ucolor_list.length);
var color = ucolor_list[rci];
return color;
}
// Strings to md5.
// NOTE/TODO: Legacy after Persona switch?
function str2md5(str){
var shasum = crypto.createHash('md5');
shasum.update(str);
var ret = shasum.digest('hex');
return ret;
}
// User information is statically stored by various keys. To
// become a sessions, it is aggregated over in sessions_by_token.
var uinf_by_md5 = {}; // NOTE/TODO: Legacy after Persona switch?
var uinf_by_uri = {};
var uinf_by_account = {
// second-level provider hashes will go here
};
//var uinf_by_socket = {}; // will have to be built as we go
each(auth_list, function(auth_line){
var a = us.clone(auth_line);
// While we're here, cycle through and toss out any unknown
// groups. Let's start with nuking all the groups in the
// clone, then working back.
a['groups'] = [];
if( us.isArray(auth_line['groups']) ){
us.each(auth_line['groups'], function(group_id){
if( group_info[group_id] ){
a['groups'].push(group_info[group_id]);
}else{
console.log('Skipping unknown group in users: ' + group_id +
' for ' + a['uri']);
}
});
}
// Also, let's at least ensure that "accounts" is at least
// defined as a hash.
if( ! us.isObject(a['accounts']) ){
a['accounts'] = {};
}
// If available, add in the different accounts.
us.each(a['accounts'], function(account_id, account_provider){
if( us.isString(account_id) && us.isString(account_provider) ){
// Ensure second-level place to put accounts.
if( ! uinf_by_account[account_provider] ){
uinf_by_account[account_provider] = {};
}
// Add second-level user information to provider/id
// combo.
uinf_by_account[account_provider][account_id] = a;
}
});
// There are a list of valid emails, so hash for them all.
var valid_em5_list = a['email-md5'];
each(valid_em5_list, function(em5){
uinf_by_md5[em5] = a;
});
// Just the URI.
uinf_by_uri[a['uri']] = a;
//console.log(a);
});
// At the end, all sessions are keyed by the referring token.
var sessions_by_token = {};
// Maps that we need to manage tied to the session.
var email2token = {}; // NOTE/TODO: Legacy after Persona switch?
var uri2token = {};
/*
* Failure is an unknown, unauthorized, or ill-formed user. If no
* user_type is listed, assume the lowest ranked one for the
* attempt.
* NOTE/TODO: Legacy after Persona switch?
*/
self.authorize_by_email = function(email, user_type){
var ret = false;
// If no user_type is listed, assume the lowest ranked one for
// the attempt.
if( ! us.isString(user_type) ){
user_type = known_user_types[0];
}
// Our requirements are: email (by md5 proxy), uri, and
// "noctua/go" authorization (empty is fine).
var emd5 = str2md5(email);
var uinf = uinf_by_md5[emd5];
if( uinf ){
// Check the user credentials against what we had in the
// users' file for our specific context.
if( uinf['uri'] &&
uinf['authorizations'] &&
uinf['authorizations']['noctua'] &&
uinf['authorizations']['noctua'][barista_context] &&
uinf['authorizations']['noctua'][barista_context][user_type] ){
ret = true;
// Legacy checking.
// TODO: Remove this and just leave the templated
// context-sensitive checking above.
}else if( uinf['uri'] &&
uinf['authorizations'] &&
uinf['authorizations']['noctua-go'] &&
uinf['authorizations']['noctua-go'][user_type] ){
ret = true;
}
}
return ret;
};
/*
* Failure is an unknown, unauthorized, or ill-formed user. If no
* user_type is listed, assume the lowest ranked one for the
* attempt.
*/
self.authorize_by_uri = function(uri, user_type){
var ret = false;
// If no user_type is listed, assume the lowest ranked one for
// the attempt.
if( ! us.isString(user_type) ){
user_type = known_user_types[0];
}
// Our requirements are: uri and "noctua/go" authorization
// (empty is fine).
var uinf = uinf_by_uri[uri];
if( uinf ){
// Check the user credentials against what we had in the
// users' file for our specific context.
if( uinf['uri'] &&
uinf['authorizations'] &&
uinf['authorizations']['noctua'] &&
uinf['authorizations']['noctua'][barista_context] &&
uinf['authorizations']['noctua'][barista_context][user_type] ){
ret = true;
// Legacy checking.
// TODO: Remove this and just leave the templated
// context-sensitive checking above.
}else if( uinf['uri'] &&
uinf['authorizations'] &&
uinf['authorizations']['noctua-go'] &&
uinf['authorizations']['noctua-go'][user_type] ){
ret = true;
}
}
return ret;
};
// Internal function to actually create the used session
// structure.
// NOTE/TODO: Can safely remove email stuff after Persona switch?
function _gel_session(token, uri, user_type,
nickname, groups, accounts, email){
// token and uri are super critical.
if( ! us.isString(token) ){
throw new Error('bad user token');
}
if( ! us.isString(uri) ){
throw new Error('bad user uri');
}
// Double check user type.
if( ! us.contains(known_user_types, user_type) ){
throw new Error('unknown user type: ' + user_type);
}
// Well, name is unimportant technically if we have the uri.
console.log(nickname);
if( ! us.isString(nickname) ){
nickname = '???';
}
// Groups and accounts, while not required, will be empty.
var sess_groups = [];
if( us.isArray(groups) ){
sess_groups = groups;
}
var sess_accounts = {};
if( us.isObject(accounts) ){
sess_accounts = accounts;
}
// Email/md5 is now optional? Moving to a post-Persona
// universe.
var emd5 = null;
if( email ){
emd5 = str2md5(email);
}else{
email = null;
}
// Color is random.
var color = get_color();
// Create new session.
sessions_by_token[token] = {
'token': token,
'uri': uri,
'user-type': user_type, // this will be the highest rank available
'color': color,
'nickname': nickname,
'groups': sess_groups,
'accounts': sess_accounts,
'email': email,
'email-md5': emd5
};
email2token[email] = token;
uri2token[uri] = token;
// Clone for return.
var ret = clone(sessions_by_token[token]);
return ret;
}
/*
* Will not clobber or repeat if a session exists--just return what's there.
* Cloned object or null.
*/
// NOTE/TODO: Legacy after Persona switch?
// TODO: Session lifespan: every time a new session is created,
// clear out old sessions.
self.create_session_by_email = function(email){
var ret = null;
// First, just return a current session if there is one--don't
// create a new one.
if( email && email2token[email] &&
sessions_by_token[email2token[email]] ){
ret = clone( sessions_by_token[email2token[email]]);
}else{
// Cycle through to see what kind of user we have.
var user_type = null;
us.each(known_user_types, function(try_user_type){
if( self.authorize_by_email(email, try_user_type) ){
user_type = try_user_type;
}
});
if( ! user_type ){
// Cannot--likely bad info or unauthorized.
}else{
// Get available user information.
var emd5 = str2md5(email);
var uinf = uinf_by_md5[emd5];
var new_uri = uinf['uri'];
var new_nick = uinf['nickname'] || '???';
var new_groups = uinf['groups'] || [];
var new_accounts = uinf['accounts'] || {};
// Generate a new token.
var new_token = get_token();
// Gel and clone for return.
return _gel_session(new_token, new_uri, user_type,
new_nick, new_groups, new_accounts,
email);
}
}
return ret;
};
/*
* Will not clobber or repeat if a session exists--just return what's there.
* Cloned object or null.
*/
// TODO: Session lifespan: every time a new session is created,
// clear out old sessions.
self.create_session_by_uri = function(uri){
var ret = null;
// First, just return a current session if there is one--don't
// create a new one.
if( uri && uri2token[uri] && sessions_by_token[uri2token[uri]] ){
ret = clone( sessions_by_token[uri2token[uri]]);
}else{
// Cycle through to see what kind of user we have.
var user_type = null;
us.each(known_user_types, function(try_user_type){
if( self.authorize_by_uri(uri, try_user_type) ){
user_type = try_user_type;
}
});
if( ! user_type ){
// Cannot--likely bad info or unauthorized.
}else{
// Get available user information.
var uinf = uinf_by_uri[uri];
var new_uri = uinf['uri'];
var new_nick = uinf['nickname'] || '???';
var new_email = uinf['email'] || null;
var new_groups = uinf['groups'] || [];
var new_accounts = uinf['accounts'] || {};
// Generate a new token.
var new_token = get_token();
// Gel and clone for return.
return _gel_session(new_token, new_uri, user_type,
new_nick, new_groups, new_accounts,
new_email);
}
}
return ret;
};
/*
* Will not clobber or repeat if a session exists--just return what's there.
* Cloned object or null.
*/
// TODO: Session lifespan: every time a new session is created,
// clear out old sessions.
self.create_session_by_provider = function(provider_name, user_id){
// First, try and recover URI, which we will then use to delegate to
// a more full function.
var try_uri = null;
if( uinf_by_account[provider_name] &&
uinf_by_account[provider_name][user_id] ){
var sess = uinf_by_account[provider_name][user_id];
if( sess && sess['uri'] ){
try_uri = sess['uri'];
}
}
return self.create_session_by_uri(try_uri);
};
/*
* Add a bogus session for testing--dangerous!
*/
self.create_bogus_session = function(token, uri, user_type,
nickname, groups, accounts, email){
return _gel_session(token, uri, user_type,
nickname, groups, accounts, email);
};
/*
* Cloned object or null.
* NOTE/TODO: Legacy after Persona switch?
*/
self.get_session_by_email = function(email){
var token = email2token[email];
var ret = self.get_session_by_token(token);
return ret;
};
/*
* Cloned object or null.
*/
self.get_session_by_uri = function(uri){
var token = uri2token[uri];
var ret = self.get_session_by_token(token);
return ret;
};
/*
* Cloned objects or empty list.
*/
self.get_sessions = function(){
var ret = [];
each(sessions_by_token,
function(token, session){
ret.push(clone(session));
console.log(session);
});
return ret;
};
/*
* Cloned object or null.
*/
self.get_session_by_token = function(token){
var ret = null;
if( token ){
var sess = sessions_by_token[token];
if( sess ){
ret = clone(sess);
}
}
return ret;
};
/*
* True or false.
*/
self.delete_session_by_token = function(token){
var ret = false;
if( sessions_by_token[token] ){
// Email deletion.
// NOTE/TODO: Legacy after Persona switch?
var email = sessions_by_token[token]['email'];
delete email2token[email];
// URI deletion.
var uri = sessions_by_token[token]['uri'];
delete uri2token[uri];
// Session deletion.
delete sessions_by_token[token];
ret = true;
}
return ret;
};
/*
* True or false.
* NOTE/TODO: Legacy after Persona switch?
*/
self.delete_session_by_email = function(email){
var token = email2token[email];
return self.delete_session_by_token(token);
};
/*
* True or false.
*/
self.delete_session_by_uri = function(uri){
var token = uri2token[uri];
return self.delete_session_by_token(token);
};
};
///
/// Session/authorization handling.
///
// Bring in metadata that will be used for identifying user. Spin-up
// session manager. Written as separate function to make the REPL easier
function _setup_sessioner(fname, gname){
var auth_list = yaml.load(fname);
var group_list = yaml.load(gname);
var new_sessioner = new Sessioner(auth_list, group_list);
// Bring on the listed bogus user sessions.
us.each(bogus_users, function(bu){
new_sessioner.create_bogus_session(
bu['token'],
bu['uri'],
bu['user-type'],
bu['nickname'],
[],
{},
bu['email']);
});
return new_sessioner;
}
var sessioner = _setup_sessioner(user_fname, group_fname);
///
/// Passport and strategy setup.
///
var passport = require('passport');
passport.serializeUser(function(user, done){
console.log('passport serializeUser: ', user);
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
console.log('passport deserializeUser: ', id);
done(null, {'id': id});
// else done(err, null)
});
// Scan secloc for secrets at "<provider>.yaml". "local" is special,
// actually defining usernames and passwords keyed to user IDs.
var use_provider_local_p = false;
var use_provider_github_p = false;
var use_provider_google_plus_p = false;
var use_provider_orcid_p = false;
us.each(['local', 'github', 'google-plus', 'orcid'], function(provider){
var provider_path = secloc + '/' + provider + '.yaml';
var prov_stats = null;
try {
prov_stats = fs.statSync(provider_path);
}catch(e){
ll('Will not use provider: ' + provider);
}
if( prov_stats ){
ll('Will search for (' + provider + ') secrets at: ' + secloc);
if( ! prov_stats.isFile() ){
ll('Unable to read ' + provider +
' provider file at: ' + provider_path);
}else if( provider === 'local' ){
// Squeeze whatever we can out of the secrets files.
var local_secrets = {};
var local_secrets_list = yaml.load(provider_path);
us.each( local_secrets_list, function(local_secret){
if( us.isString(local_secret['uri']) &&
us.isString(local_secret['username']) &&
us.isString(local_secret['password']) ){
local_secrets[local_secret['username']] = local_secret;
}
});
// Local password strategy.
var LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy({
passReqToCallback: true//,
//session: false
}, function(req, username, password, done) {
console.log("Start local auth...");
//console.log("Have req", req);
if( ! local_secrets[username] ){
console.log("Incorrect username: " + username);
return done(null, false, { message: 'Incorrect username.' });
}else if( password !== local_secrets[username]['password'] ){
console.log("Incorrect password: " + password);
return done(null, false, { message: 'Incorrect password.' });
}else{
console.log("Authenticated with URI: " +
local_secrets[username]['uri']);
return done(null, {
"uri": local_secrets[username]['uri'],
"provider_id": 'local',
"user_id": local_secrets[username]['uri']
});
}
}));
// We're go.
use_provider_local_p = true;
}else if( provider === 'github' ){
// TODO.
// Pick-up secrets file and check structure.
var github_secrets = yaml.load(provider_path);
console.log('secrets for ' + provider, github_secrets);
if( github_secrets['clientID'] &&
github_secrets['clientSecret'] &&
github_secrets['callbackURL'] ){
// Pass.
}else{
throw new Error(provider + ' not structured correctly!');
}
var GitHubStrategy = require('passport-github').Strategy;
passport.use(new GitHubStrategy({
passReqToCallback: true,
session: false,
clientID: github_secrets['clientID'],
clientSecret: github_secrets['clientSecret'],
callbackURL: github_secrets['callbackURL']
}, function(req, accessToken, refreshToken, profile, done) {
console.log("Start GitHub auth...");
//console.log(provider + ' callback profile: ', profile);