-
Notifications
You must be signed in to change notification settings - Fork 0
/
mojo-api-template.pl
677 lines (586 loc) · 19.7 KB
/
mojo-api-template.pl
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
#!/usr/bin/env perl
# vim: set foldmethod=marker:
#
use strict;
use warnings;
# config section
#
my $app_title="API Gateway";
my $ldap_auth_realm="Active Directory login";
my $token_lib="/tmp/alerttest/tokens";
## Mail specific
#my $smtpserver = 'mail.mydomain.tld';
#my $smtpport = 25;
#my $alert_spool="/tmp/alerttest/spool";
#my $done_alerts="/tmp/alerttest/done";
# the variables $authuser and $authpass can be used to
# perform an LDAP bind with the web users credentials.
my $ldap_host = 'ad-ldap.mydomain.tld';
my $ldap_basedn = 'DC=mydomain,DC=tld';
my $ldap_binddn = '$authuser\@mydomain.tld';
my $ldap_bindpw = '$authpass';
my $ldap_filter = '(&(objectClass=organizationalPerson)(cn=%s))';
# static bind user
my $ldap_binduser='[email protected]';
my $ldap_bindpasswd='#s3krit?';
#
my $db_dsn = 'foobar';
my $db_user= 'sys';
my $db_passwd = '#Geh3im?';
# end config
use POSIX;
use Proc::Simple;
use Mojolicious::Lite;
use Mojo::Log;
use Mojo::JSON;
use Mojo::JSON qw(decode_json encode_json from_json);
use Mojo::JSON::Pointer;
use Mojo::Util qw(url_unescape);
#use Mojolicious::Plugin::Authentication;
use Mojolicious::Plugin::BasicAuthPlus;
use Mojolicious::Command::routes;
## Mail specific
#use Email::Sender::Simple qw(sendmail);
#use Email::Sender::Transport::SMTP();
#use Email::Simple();
#use Email::Simple::Creator();
use DateTime;
use Apache::Htpasswd;
#use Net::LDAP;
use DBI;
# only used for debugging
use Data::Dumper::Simple;
plugin 'basic_auth_plus';
# {{{ functions
#
sub authenticate_user {
my $c= shift;
my $log = Mojo::Log->new;
#warn Dumper($c->session);
$log->info("attempting login.");
if (not defined $c->req->url->to_abs->userinfo) {
$log->info("no user info in request. sending auth header.");
$c->res->headers->www_authenticate("Basic realm=\"$ldap_auth_realm\"");
$c->render('text' => "Access denied.", status => '401');
return undef;
} else {
$log->info("auth header found.");
my $auth= $c->req->url->to_abs->userinfo;
my ($authuser, $authpass) = split ':', $auth;
$log->info("attempting LDAP auth with user: $authuser.");
my $auth_ok = $c->basic_auth(
$ldap_auth_realm => {
host => $ldap_host,
basedn => $ldap_basedn,
binddn => eval qq("$ldap_binddn"),
bindpw => eval qq("$ldap_bindpw"),
filter => $ldap_filter,
tls_verify => 'none',
logging => 1
}
);
if (not $auth_ok) {
$log->info("LDAP auth failed. sending auth header again.");
$c->res->headers->www_authenticate("Basic realm=\"$ldap_auth_realm\"");
$c->render('text' => "Access denied.", status => '401');
return undef;
} else {
$log->info("LDAP auth succeeded.");
return 1;
}
}
$log->warn("execution should not reach here!");
return undef;
}
sub authenticate_token {
my ($username, $token_name, $pass)= @_;
#warn Dumper($token_name);
my $password_file="$token_lib/$username.htpasswd";
my $vault = new Apache::Htpasswd( { passwdFile => $password_file, ReadOnly => 1 } );
return $vault->htCheckPassword($token_name, $pass);
}
sub list_tokens {
my ($username)= shift;
my $password_file="$token_lib/$username.htpasswd";
unless(-e $password_file) {
open my $fc, ">", $password_file;
close $fc;
}
open my $in, "<:encoding(utf8)", $password_file or die "$password_file: $!";
my @usernames= map { (split /:/, $_, 2)[0]; } grep(!/^#/, <$in>);
close $in;
warn Dumper(@usernames);
return \@usernames;
}
sub add_token {
my ($username, $token_name, $pass)= @_;
my $password_file="$token_lib/$username.htpasswd";
my $vault = new Apache::Htpasswd( { passwdFile => $password_file, ReadOnly => 0 } );
# try to overwrite first
my $result= $vault->htpasswd($token_name, $pass, {'overwrite' => 1});
if (not $result) {
warn Dumper($result);
# just create the token
return $vault->htpasswd($token_name, $pass);
}
return $result;
}
sub remove_token {
my ($username, $token_name)= @_;
my $password_file="$token_lib/$username.htpasswd";
if (not -w $password_file) {
return undef;
}
my $vault = new Apache::Htpasswd( { passwdFile => $password_file, ReadOnly => 0 } );
$vault->htDelete($token_name);
return 1;
}
#sub trigger_myself {
# while (1){
# sleep(5);
# }
#}
sub remove_single_key {
my $var= shift;
if (ref($var) eq "HASH") {
if (keys(%$var) == 1) {
($var)= values(%$var);
return remove_single_key($var);
} else {
while ((my $key, my $value)= each(%$var)) {
$var->{$key}= remove_single_key($value);
}
return $var;
}
} elsif (ref($var) eq "ARRAY") {
if (scalar(@$var) == 1) {
$var= @$var[0];
return remove_single_key($var);
} else {
foreach my $value (@$var) {
$value= remove_single_key($value);
}
return $var;
}
} else {
return $var;
}
}
sub get_all_routes {
my @arr;
my $root= shift;
for my $route (@{$root->children}) {
push @arr, route_full_path($route);
}
return @arr;
}
sub route_full_path {
my $route= shift;
my $path='';
my @arr;
my %elem;
if (! $route->inline) {
$elem{'path'}= $route->pattern->unparsed // '/';
$elem{'scheme'}= $route->via;
$elem{'description'}= ${$route->pattern->defaults}{route_description};
push @arr, \%elem;
}
for my $route_sub (@{$route->children}) {
push @arr, route_full_path($route_sub);
}
return @arr;
}
# }}} end functions
#app->secrets(['']);
# background process to periodically work queued alerts (and possibly other stuff)
#
#my $wakemeup= Proc::Simple->new();
#$wakemeup->start( \&trigger_myself );
#$wakemeup->kill_on_destroy(1);
#$wakemeup->signal_on_destroy("SIGKILL");
# {{{ mojolicious routes
#
get '/' => { route_description => 'redirects to /help',
app_title => $app_title
} => sub {
my $c = shift;
$c->stash( app_title => $app_title);
$c->redirect_to('/help');
};
get '/help' => { route_description => 'Help page (you are probably looking at it).',
template => 'help',
app_title => $app_title
} => sub {
my $c = shift;
my $base_url= $c->req->url->to_abs->scheme . "://" . $c->req->url->to_abs->host . ":" . $c->req->url->to_abs->port;
my @arr= get_all_routes ($c->app->routes);
$c->stash( app_routes => \@arr,
app_base_url => $base_url
);
};
get '/login' => { route_description => 'Lets a (human) Active Directory user log in via HTTP Basic Authentication.',
app_title => $app_title
} => sub {
my $c = shift;
my $log = Mojo::Log->new;
if (authenticate_user($c)) {
my ($authuser, undef) = split ':', $c->req->url->to_abs->userinfo;
$c->session->{username}= $authuser;
my $previous_page= ( defined $c->session->{redirecting_page} and not $c->session->{redirecting_page} eq '/login' )
? $c->session->{redirecting_page}
: '/';
$log->info("redirecting to $previous_page");
$c->redirect_to($previous_page);
return 1;
}
};
#{ template => 'login' };
get '/logout' => { route_description => 'Logs out a (human) Active Directory user.',
app_title => $app_title
} => sub {
my $c= shift;
# Expire and in turn clear session automatically
$c->session(expires => 1);
$c->redirect_to('/');
};
# authentication with a session.
# stateful; should only be used whith human interaction.
#
group {
under sub {
my $c= shift;
my $log = Mojo::Log->new;
$c->stash( app_title => $app_title);
$c->stash( app_base_url => $c->req->url->to_abs);
if (not defined $c->session->{username} or $c->session->{username} eq '') {
$log->info("no session(yet).");
$log->info("redirecting to /login");
$c->session->{redirecting_page}= '/dashboard';
$c->redirect_to('/login');
#$c->render('text' => "Access denied.", status => '401');
return undef;
} else {
my $username= $c->session->{username};
$log->info("session user found: $username");
warn Dumper($c->session->{username});
return 1;
}
};
get '/dashboard' => { route_description => 'Manage tokens (requires AD login)',
app_title => $app_title
} => sub {
my $c= shift;
$c->stash('username' => $c->session->{username});
my $username= $c->session->{username};
my $tokens= list_tokens($username);
$c->stash('tokens' => list_tokens($username));
$c->render();
};
};
# stateless authentication with real world user credentials
# usually only used to obtain tokens
#
group {
under sub {
my $c = shift;
my $log = Mojo::Log->new;
if (authenticate_user($c)) {
my ($authuser, undef) = split ':', $c->req->url->to_abs->userinfo;
$c->session->{username}= $authuser;
return 1;
} else {
return undef;
}
};
get '/tokens' => { route_description => 'List Tokens (requires AD login)',
app_title => $app_title
} => sub {
my $c= shift;
my $username= $c->session->{username};
my $tokens= list_tokens($username);
$c->stash('tokens' => list_tokens($username));
$c->render(json => {"tokens" => [@$tokens]});
};
put '/tokens/#username/#token' => { route_description => 'Add token to username\'s authentication-namespace (requires AD login)',
app_title => $app_title
} => sub {
my $c= shift;
my ($session_username, undef)= split /:/, $c->req->url->to_abs->userinfo;
my $url_username= $c->param('username');
if (not $session_username eq $url_username) {
$c->render('text' => "Access denied.", status => '401');
return;
}
my $url_token= $c->param('token');
my $json= $c->req->json;
warn Dumper($json);
my $pass= $json->{'password'};
warn Dumper($pass);
if (not defined $pass or $pass eq '') {
$c->render('json' => { "reason" => "data required." }, status => '403');
return;
}
if (add_token($url_username, $url_token, $pass)) {
$c->render('text' => '', status => '204');
return 1;
} else {
$c->render(text => "It's not you, it's us.", status => '500');
return;
}
};
del '/tokens/#username/#token' => { route_description => 'Remove token from username\'s authentication-namespace (requires AD login)',
app_title => $app_title
} => sub {
my $c= shift;
my ($session_username, undef)= split /:/, $c->req->url->to_abs->userinfo;
my $url_username= $c->param('username');
if (not $session_username eq $url_username) {
$c->render('text' => "Access denied.", status => '401');
return;
}
my $url_token= $c->param('token');
if (remove_token($url_username, $url_token)) {
$c->render('text' => '', status => '204');
return 1;
} else {
$c->render(text => "It's not you, it's us.", status => '500');
return;
}
};
};
# API PAYLOAD: token authenticated api endpoint.
# not wrapped in a group because there is just one route.
#
any ['GET'] => '/project-name/API/v1.0/endpoint1' => { route_description => 'REST API endpoint: [description] Requires token authentication.',
app_title => $app_title
} => sub {
# Log to STDERR
my $log = Mojo::Log->new;
my $c = shift;
# get JSON string from GET or POST request
#
#my $json;
#if ($c->req->method eq 'GET') {
# $json= decode_json(url_unescape($c->req->query_params->to_string));
#} else {
# $json= $c->req->json;
#}
my $username= $c->req->headers->header('x-auth-namespace');
# authentication / atuhorization
#
my $auth_ok;
my $token_name;
# allow from localhost
my $client_ip= $c->tx->remote_address;
my $my_ip= $c->tx->local_address;
if ($client_ip eq $my_ip) {
$token_name="localhost";
$auth_ok= 1;
} else {
$auth_ok= $c->basic_auth('token authentication' => sub {
&authenticate_token($username, @_)
}
);
if ($auth_ok) {
($token_name)= split /:/, $c->req->url->to_abs->userinfo;
}
}
my @db_users;
if ($auth_ok) {
$log->info("logged in as $username/$token_name");
# PAYLOAD code goes here.
#
my $dbh= DBI->connect("dbi:ODBC:$db_dsn", $db_user, $db_passwd, { AutoCommit => 0 });
my $statement = 'SELECT * FROM EXA_ALL_USERS';
my $sth = $dbh->prepare($statement);
my $rv = $sth->execute;
while (my $row= $sth->fetchrow_hashref) {
warn Dumper($row);
push (@db_users, $row->{'USER_NAME'});
}
#
} else {
$c->render('text' => "Access denied.", status => '401');
return 0;
}
# auth end
## trigger background thread
#my $bg_alive= $wakemeup->poll();
warn Dumper(@db_users);
my $answer= encode_json(\@db_users);
my $success= 1;
if ($success) {
$c->render(text => $answer);
} else
{
$c->render(text => $answer, status => '500');
}
};
# }}} end mojolicious routes
app->start;
# wrong place; see: https://stackoverflow.com/questions/22871601/how-do-i-properly-shut-down-a-mojoliciouslite-server?rq=1
#$wakemeup->kill('SIGKILL');
__DATA__
@@ layouts/mylayout.html.ep
<!DOCTYPE html>
<html>
<head><title><%= $app_title %></title></head>
<body>
<script src="vue.js"></script>
<%= content %>
</body>
</html>
@@ index.html.ep
% layout 'mylayout';
<h1><%= $app_title %></h1>
@@ help.html.ep
% layout 'mylayout';
<h1><%= $app_title %></h1>
<h2>URLs</h2>
<table>
<th>Scheme</th><th>URL</th><th>Route Description</th>
<% foreach my $el (@$app_routes) { %>
<tr>
<td><%= join(', ', @{$el->{'scheme'}}) %></td>
<td><code><%= $app_base_url %><%= $el->{'path'} %></code></td>
<td><%= $el->{'description'} %></td>
<tr>
<% } %>
</table>
<h2>
CURL example
</h2>
Set the HTTP header X-AUTH-NAMESPACE to the AD username whose token you are authenticating with.
<p />
<code>
curl -su "tokenname:tokenpass" -H "X-AUTH-NAMESPACE: humanusername" -X GET 'https://myhost.tld:3443/project-name/API/v1.0/endpoint1'
</code>
<p />
<h2>Copyright Notice</h2>
</div>
@@ dashboard.html.ep
% layout 'mylayout';
<h1><%= $app_title %></h1>
<!--
<ul>
% foreach my $token (@$tokens) {
<li><%= $token %></li>
% }
</ul>
-->
<div id='gateway-app'></div>
%= javascript begin
var app= new Vue({
el: '#gateway-app',
data : {
message: 'hello Vue',
tokens: [],
addingToken: false,
newtoken: {
name: '',
password: ''
},
token: {
name: '',
password: ''
},
input_password: [],
editing_password: []
},
methods: {
getTokens() {
tokens= []
fetch("/tokens")
.then(response => response.json())
.then((data) => {
this.tokens= data.tokens.reduce( function(result, token) {
result.push({ "name" : token, "password" : '' })
return result
}, [])
})
},
deleteToken(token) {
fetch("/tokens/<%= $username %>/" + token.name, {method: "DELETE"})
.then(() => {
this.getTokens()
console.log("deleted.")
})
},
saveToken(token) {
if (token.name==='' || token.password==='') {
console.log('neither token.name nor token.password may be empty')
}
fetch("/tokens/<%= $username %>/" + token.name, {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify((({ password}) => ({ password }))(token)),
})
.then(() => {
this.getTokens()
this.addingToken= false
console.log("saved.")
})
console.log("saved: " + token.name + " with pass: " + token.password)
console.log(JSON.stringify((({ password}) => ({ password }))(token)))
token.name=''
token.password=''
},
addToken() {
this.addingToken= true
},
showAddTokenButton(token) {
if ((token.name === '') && (token.password === '')) {
this.addingToken= false
}
},
editPassword(token, i) {
if (token.password !== '') {
this.editing_password[i]=true
} else {
this.editing_password[i]=false
}
console.log(i)
},
savePassword(token, i) {
this.saveToken(token)
this.editPassword(token, i)
console.log('saving password: ' + i)
}
},
directives: {
focus: {
// directive definition
inserted: function (el) {
el.focus()
}
}
},
mounted() {
this.getTokens()
},
template: `
<div>
<h2>Tokens for <%= $username %></h2>
<table>
<th>token</th><th>password</th><th></th>
<tr v-for="token, i in tokens">
<td style="min-width:12em">{{ token.name }}</td>
<td style="min-width:12em"><input v-model="token.password" v-on:input="editPassword(token, i)" type='password' placeholder='*********'></td>
<td v-if="editing_password[i]!==true"><button v-on:click="deleteToken(token)">x</button></td>
<td v-else><button v-on:click="savePassword(token, i)">save</button></td>
</tr>
<tr v-if="addingToken===false"><td><button v-on:click="addToken()">+</button></td></tr>
<tr v-else>
<td><input style="min-width:12em" v-model="newtoken.name" v-focus v-on:blur="showAddTokenButton(newtoken)" v-on:focus="addToken()" placeholder='token name'></td>
<td><input style="min-width:12em" v-model="newtoken.password" v-on:blur="showAddTokenButton(newtoken)" v-on:focus="addToken()" type='password' placeholder='password'></td>
<td><button v-on:click="saveToken(newtoken)" v-on:blur="showAddTokenButton(newtoken)">save</button></td>
</tr>
</table>
</ul>
</div>
`
}
)
% end