forked from geneontology/noctua
-
Notifications
You must be signed in to change notification settings - Fork 0
/
barista.js
1418 lines (1197 loc) · 37.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
////
//// 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 --self http://localhost:3400
////
// 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 cors = require('cors');
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');
///
/// 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);
}
// 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.
var barista_debug = argv['d'] || argv['debug'] || 0;
if( barista_debug ){ barista_debug = parseInt(barista_debug); }
ll('Barista debug level: ' + barista_debug);
///
/// 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 a a rolling time
// window which is searched.
// {day1: {SET2}, day2: {SET2}}
var Sessioner = function(auth_list){
var self = this;
// Generate a new token.
function get_token(){
var token = bbop.core.randomness(20);
return token;
}
// Colors.
function get_color(){
var ucolor_list = ['red', 'green', 'purple', 'blue', 'brown', 'black'];
var rci = Math.floor(Math.random() * ucolor_list.length);
var color = ucolor_list[rci];
return color;
}
// Strings to md5.
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 = {};
//var uinf_by_email = {};
//var uinf_by_socket = {}; // will have to be built as we go
each(auth_list, function(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;
});
});
// At the end, all sessions are keyed by the referring token.
var sessions_by_token = {};
// This is tied to the session.
var email2token = {};
/*
* Failure is an unknown, unauthorized, or ill-formed user.
*/
self.authorize_by_email = function(email){
var ret = false;
// Our requirements are: email (by md5 proxy), uri, and
// "minerva-go" authorization (empty is fine).
var emd5 = str2md5(email);
var uinf = uinf_by_md5[emd5];
if( uinf ){
if( uinf['uri'] &&
uinf['authorizations'] &&
uinf['authorizations']['noctua-go'] &&
uinf['authorizations']['noctua-go']['allow-edit'] ){
ret = true;
}
}
return ret;
};
// Internal function to actually create the used session
// structure.
function _gel_session(email, token, nickname, uri){
// Create new session.
var emd5 = str2md5(email);
var color = get_color(); // random color
sessions_by_token[token] = {
'nickname': nickname,
'uri': uri,
'email': email,
'email-md5': emd5,
'token': token,
'color': color
};
email2token[email] = token;
// Clone for return.
var ret = clone(sessions_by_token[token]);
return ret;
}
/*
* Will not clobber 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_email = function(email){
var ret = null;
if( ! self.authorize_by_email(email) ){
// Cannot--likely bad info or unauthorized.
}else{
// Get available user information.
var emd5 = str2md5(email);
var uinf = uinf_by_md5[emd5];
var new_nick = uinf['nickname'] || '???';
var new_uri = uinf['uri'];
// Generate a new token.
var new_token = get_token();
// Gel and clone for return.
return _gel_session(email, new_token, new_nick, new_uri);
}
return ret;
};
/*
* Add a bogus session for testing--dangerous!
*/
self.create_bogus_session = function(email, token, nickname, uri){
return _gel_session(email, token, nickname, uri);
};
/*
* Cloned object or null.
*/
self.get_session_by_email = function(email){
var token = email2token[email];
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));
});
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_email = function(email){
var ret = null;
var token = email2token[email];
if( token ){
delete sessions_by_token[token];
delete email2token[email];
ret = true;
}
return ret;
};
/*
* True or false.
*/
self.delete_session_by_token = function(token){
var ret = false;
if( sessions_by_token[token] ){
var email = sessions_by_token[token]['email'];
delete email2token[email];
delete sessions_by_token[token];
ret = true;
}
return ret;
};
};
///
/// 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_session(fname){
var auth_list = yaml.load(fname);
return new Sessioner(auth_list);
}
var sessioner = setup_session(user_fname);
// BUG/TODO/DEBUG: create an always user so I don't go crazy when
// reloading Barista during experiments..
// Will need to go at some point, or be more subtle.
function create_bogus_session(email, token, name, uri){
sessioner.create_bogus_session(email, token, name, uri);
}
create_bogus_session('[email protected]', '123', 'kltm', 'GOC:kltm');
// Bring in metadata that will be used for identifying
// application protections. Spin-up app manager.
var sconf = yaml.load('./startup.yaml');
var app_defs = sconf['APP_DEFINITIONS'].value;
if( ! app_defs || us.isEmpty(app_defs) ){
_die();
}
var app_guard = new AppGuard(sconf['APP_DEFINITIONS'].value);
// Start the model cubby.
var cubby = new ModelCubby();
///
/// Main.
///
var BaristaLauncher = function(){
var self = this;
// Monitor some stats.
var monitor_messages = 0;
var monitor_calls = 0;
///
/// Setup a REPL system first--we'll be running the app out of
/// here.
///
// Wee helper.
function rlog(context, out){
context.log(out);
ll(out);
}
// Optional REPL setup.
if( barista_repl_port){
//var pmt = 'barista@'+socket.remoteAddress+':'+socket.remotePort +'> ';
vantage.delimiter('barista@' + ':');
// Not my problem, not my use case--try and get rid of it.
var vnt_cmd = vantage.find('vantage');
if( vnt_cmd ){
vnt_cmd.hidden();
vnt_cmd.remove();
}
// Refresh.
var rld_cmd = vantage.command('refresh [filename]');
rld_cmd.description("Refresh/reload users.yaml file for the Sessioner.");
rld_cmd.action(function(args, cb){
var fname = args.filename;
var new_sessioner = null;
try {
new_sessioner = setup_session(fname);
}catch(e){
rlog(this, 'Failed to load: ' + fname);
}
if( new_sessioner ){
sessioner = new_sessioner;
rlog(this, '(Re)loaded: ' + fname);
}
cb();
});
// Setup bogus session.
var bog_cmd = vantage.command('bogus [email] [token] [name] [uri]');
bog_cmd.description("Create a temporary bogus session; use with caution as this bad data can be saved.");
bog_cmd.action(function(args, cb){
var email = args.email;
var token = args.token;
var name = args.name || '???';
var uri = args.uri;
if( ! email || ! token || ! name || ! uri ){
rlog(this, 'Cannot create bogus session with given info.' );
}else{
sessioner.create_bogus_session(email, token, name, uri);
rlog(this, 'Created bogus session with given info.' );
}
cb();
});
var get_cmd = vantage.command('list');
get_cmd.description("List all current sessions.");
get_cmd.action(function(args, cb){
var all_sess = sessioner.get_sessions();
rlog(this, all_sess);
cb();
});
var delt_cmd = vantage.command('delete token [token]');
delt_cmd.description("Delete a session by token.");
delt_cmd.action(function(args, cb){
var token = args.token;
if( token ){
var tf = sessioner.delete_session_by_token(token);
rlog(this, 'Deleted session by token: ' + tf);
}
cb();
});
var dele_cmd = vantage.command('delete email [email]');
dele_cmd.description("Delete a session by email address.");
dele_cmd.action(function(args, cb){
var email = args.email;
if( email ){
var tf = sessioner.delete_session_by_email(email);
rlog(this, 'Deleted session by email: ' + tf);
}
cb();
});
// // Veeery basic auth, just to keep the riff-raff out.
// // BUG: Although in the docs, this does not seem to
// // yet be supported...
// vantage.auth("basic", {
// "users": [
// {user: "kltm", pass:"123"}
// ],
// "retry": 3,
// "retryTime": 500,
// "deny": 1,
// "unlockTime": 3000
// });
// Can only be invoked after "listen", so we're down here.
// NOTE/TODO: May want to add configurable firewall stuff later.
// https://github.com/dthree/vantage/blob/master/examples/server/server.js
vantage.listen(barista_repl_port);
vantage.firewall.policy('REJECT');
vantage.firewall.accept(
['127', '0', '0', '1'].join('.')); // here
vantage.firewall.accept(
['192', '168', '0', '0'].join('.'), 16); // home/local
vantage.firewall.accept(
['131', '243', '0', '0'].join('.'), 16); // lbl-bbop
}
///
/// Response helper.
///
function _standard_response(res, code, type, body){
res.setHeader('Content-Type', type);
res.setHeader('Content-Length', body.length);
res.end(body);
return res;
}
///
/// Cache and template rendering.
///
var ppaths = ['static', 'deploy', 'deploy/js', 'css', 'templates'];
var pup_tent = require('pup-tent')(ppaths);
pup_tent.use_cache_p(false);
// Ready the common libs (the actually mapping is taken care of
// later on).
pup_tent.set_common('css_libs', [
'/bootstrap.min.css',
'/jquery-ui-1.10.3.custom.min.css',
'/bbop.css',
'/amigo.css']);
pup_tent.set_common('js_libs', [
'/jquery.js',
'/bootstrap.min.js',
'/jquery-ui-1.10.3.custom.min.js']);
// //'/commonjs-runtime.js']);
// '/bbop.js',
// '/bbopx.js',
// '/amigo2.js']);
// Spin up the main messenging server.
var express = require('express');
var body_parser = require('body-parser');
var messaging_app = express();
messaging_app.use(body_parser.json());
messaging_app.use(body_parser.urlencoded({ extended: true }));
//
//messaging_app.use(express.logger());
//messaging_app.use(express.static(__dirname));
messaging_app.use(express.json());
messaging_app.use(express.urlencoded());
messaging_app.use(express.cookieParser());
messaging_app.use(cors());
messaging_app.use(express.session({secret: 'notverysecret'}));
// Must match client browser's address bar.
var persona_opts = {
audience: publoc,
// Internal function to run if remote login was susseccful or
// a session remains open.
verifyResponse: function(err, req, res, email){
ll('user has authenticated through persona: ' + email);
// First, we need to establish a session. Check if this
// email address already has a session associated with
// it. If so, don't bother creating a new one.
var sess = sessioner.get_session_by_email(email);
if( sess ){
ll('recovered session:');
ll(sess);
}else{
// Not already there, so let's see if we can create
// one from scratch.
sess = sessioner.create_session_by_email(email);
if( sess ){
// Create new user session.
ll('created new session:');
ll(sess);
}else{
// Cannot create, so some kind of authorization
// issue.
ll('login fail; unknown/unauthorized user: ' + email);
res.json({status: "failure",
email: email,
reason:"unknown/unauthorized (check users.json)"});
return; // WARNING: out-of-flow return
}
}
ll('session success (' + sess.email + '): ' + sess.token);
// Adjust this client/server session.
req.session.authorized = true;
// Pass back the interesting bits to the
res.json({status: "okay",
email: sess.email,
nickname: sess.nickname,
uri: sess.uri,
token: sess.token,
color: sess.color});
return; // return success
},
// Code to run when the user has or is logged out.
logoutResponse: function(err, req, res) {
// Destroy as much of the session information as we can.
var did_something_p = false;
if( req && req.session ){
// Looks still authorized?
if( req.session.authorized ){
// Adjust this client/server session.
req.session.authorized = null;
ll('logout: nulled authorization');
did_something_p = true;
}
// Recoverable email.
if( req.session.email ){
var sess = sessioner.get_session_by_email(email);
var email = req.session.email;
var token = sess.token;
// Remove from internal session system.
sessioner.delete_session_by_email(email);
ll('logout: Barista delete ('+ email +'): '+ token);
did_something_p = true;
}
}
if( ! did_something_p ){
ll('logout: nothing to do');
}
// We did what we could, get out of here.
ll('logout: success');
res.json({status: "okay"});
}
};
require("express-persona")(messaging_app, persona_opts);
// Server creation and socket.io addition.
var messaging_server = require('http').createServer(messaging_app);
var sio = require('socket.io').listen(messaging_server);
// Run app server through vantage to get vantage goodies.
messaging_server.listen(runport);
///
/// Cached static routes.
///
// Routes for all static cache items.
each(pup_tent.cached_list(),
function(thing){
var ctype = null;
if( js_re.test(thing) ){
ctype = 'text/javascript';
}else if( css_re.test(thing) ){
ctype = 'text/css';
}else if( html_re.test(thing) ){
ctype = 'text/html';
}
// This will skip cached templates.
if( ctype !== null ){
messaging_app.get('/' + thing,
function(req, res) {
res.setHeader('Content-Type', ctype);
res.send(pup_tent.get(thing) );
});
}
});
///
/// High-level status overview and hearbeat
///
// General use--no need for a&a.
messaging_app.get('/status', function(req, res) {
ll('process heartbeat request');
var monitor_sessions = sessioner.get_sessions().length;
var ret_obj = {
'okay': true,
'name': 'Barista',
'date': (new Date()).toJSON(),
'location': runloc,
'public': publoc,
'offerings': [
{
'name': 'sessions',
'value': monitor_sessions
},
{
'name': 'calls',
'calls': monitor_calls
},
{
'name': 'messages',
'messages': monitor_messages
}
]
};
var fin = JSON.stringify(ret_obj);
_standard_response(res, 200, 'application/json', fin);
});
///
/// Authentication and Authorization.
///
var SESS_NO_TOKEN = -1;
var SESS_BAD_TOKEN = -2;
var SESS_GOOD = 1;
// Check to see if we have access to the good stuff. Tri-state.
function _session_status(req){
var ret = null;
var sess = null;
if( req.query && req.query['barista_token'] ){
// Capture token.
var barista_token = req.query['barista_token'];
// Try and retrieve by the barista token.
sess = sessioner.get_session_by_token(barista_token);
if( sess ){
ret = SESS_GOOD;
ll('barista session token: ' + barista_token);
}else{
ret = SESS_BAD_TOKEN;
ll('non-session (old/bad?) token, ignore: ' + barista_token);
}
}else{
ret = SESS_NO_TOKEN;
ll('no token');
}
return ret;
}
// Gross overview of current users.
messaging_app.get('/user_info', function(req, res) {
// Check to see if we have access to the good stuff.
var show_all_p = false;
var sess_stat = _session_status(req);
if( sess_stat === SESS_GOOD ){
show_all_p = true;
}
// Gather all session info.
var sessions = sessioner.get_sessions();
// Variables, render, and output.
var tmpl_args = {
'show_all_p': show_all_p,
'barista_sessions': sessions,
'title': notw + ': Status'
};
var out = pup_tent.render('barista_status.tmpl',
tmpl_args,
'barista_base.tmpl');
_standard_response(res, 200, 'text/html', out);
});
// REST service that
messaging_app.get('/user_info_by_token/:token', function(req, res) {
// Do we have permissions to make the call?
var token = req.route.params['token'] || null;
var sess = sessioner.get_session_by_token(token);
var ret_obj = {};
// Gather session info.
if( sess && token ){
ret_obj = sessioner.get_session_by_token(token);
}
//
var fin = JSON.stringify(ret_obj);
ll('got user info for:' + fin['uri']);
_standard_response(res, 200, 'application/json', fin);
});
messaging_app.get('/session', function(req, res) {
// Get return argument (originating URL) if there.
var ret = null;
if( req.query && req.query['return'] ){
ret = req.query['return'];
}
var tmpl_args = {
'pup_tent_js_variables': [
{'name': 'global_barista_return', 'value': ret }
],
'pup_tent_js_libraries': [
'https://login.persona.org/include.js',
'/BaristaSession.js'
],
'title': notw + ': Session Manager',
'return': ret
};
var out = pup_tent.render('barista_session.tmpl',
tmpl_args,
'barista_base.tmpl');
_standard_response(res, 200, 'text/html', out);
});
///
/// API proxy.
///
var http_proxy = require('http-proxy');
var api_proxy = http_proxy.createProxyServer({});
// GET version.
messaging_app.get("/api/:namespace/:call/:subcall?", function(req, res){
// TODO: Request logging hooks could be placed in here.
//ll('pre api req: ' + req.url);
monitor_calls = monitor_calls +1;
// Try and get a session out for use. The important thing we
// need here is the uri to pass back to the API if session
// and possible.
var uuri = null;
var has_token_p = false;
var has_sess_p = false;
if( req && req['query'] && req['query']['token'] ){
// Best attempt at extracting a UID.
has_token_p = true;
var btok = req['query']['token'];
var sess = sessioner.get_session_by_token(btok);
if( sess ){
ll('call using session');
ll(sess);
uuri = sess.uri;
has_sess_p = true;