| 1 | # ************************************************************************* | ||
| 2 | # Copyright (c) 2014-2017, SUSE LLC | ||
| 3 | # | ||
| 4 | # All rights reserved. | ||
| 5 | # | ||
| 6 | # Redistribution and use in source and binary forms, with or without | ||
| 7 | # modification, are permitted provided that the following conditions are met: | ||
| 8 | # | ||
| 9 | # 1. Redistributions of source code must retain the above copyright notice, | ||
| 10 | # this list of conditions and the following disclaimer. | ||
| 11 | # | ||
| 12 | # 2. Redistributions in binary form must reproduce the above copyright | ||
| 13 | # notice, this list of conditions and the following disclaimer in the | ||
| 14 | # documentation and/or other materials provided with the distribution. | ||
| 15 | # | ||
| 16 | # 3. Neither the name of SUSE LLC nor the names of its contributors may be | ||
| 17 | # used to endorse or promote products derived from this software without | ||
| 18 | # specific prior written permission. | ||
| 19 | # | ||
| 20 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | ||
| 21 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | ||
| 22 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | ||
| 23 | # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE | ||
| 24 | # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR | ||
| 25 | # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF | ||
| 26 | # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS | ||
| 27 | # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN | ||
| 28 | # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) | ||
| 29 | # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE | ||
| 30 | # POSSIBILITY OF SUCH DAMAGE. | ||
| 31 | # ************************************************************************* | ||
| 32 | |||
| 33 | # ------------------------ | ||
| 34 | # This package defines how our web server handles the request-response | ||
| 35 | # cycle. All the "heavy lifting" is done by Web::Machine and Plack. | ||
| 36 | # ------------------------ | ||
| 37 | |||
| 38 | package App::MFILE::WWW::Resource; | ||
| 39 | |||
| 40 | use strict; | ||
| 41 | use warnings; | ||
| 42 | |||
| 43 | use App::CELL qw( $CELL $log $meta $site ); | ||
| 44 | use Data::Dumper; | ||
| 45 | use Encode qw( decode_utf8 encode_utf8 ); | ||
| 46 | use File::Temp qw( tempfile ); | ||
| 47 | use HTTP::Request::Common qw( GET PUT POST DELETE ); | ||
| 48 | use JSON; | ||
| 49 | use LWP::UserAgent; | ||
| 50 | use Params::Validate qw(:all); | ||
| 51 | use Try::Tiny; | ||
| 52 | |||
| 53 | # methods/attributes not defined in this module will be inherited from: | ||
| 54 | use parent 'Web::Machine::Resource'; | ||
| 55 | |||
| 56 | # user agent lookup table | ||
| 57 | our $ualt = {}; | ||
| 58 | |||
| 59 | |||
| 60 | |||
| 61 | =head1 NAME | ||
| 62 | |||
| 63 | App::MFILE::WWW::Resource - HTTP request/response cycle | ||
| 64 | |||
| 65 | |||
| 66 | |||
| 67 | |||
| 68 | =head1 SYNOPSIS | ||
| 69 | |||
| 70 | In PSGI file: | ||
| 71 | |||
| 72 | use Web::Machine; | ||
| 73 | |||
| 74 | Web::Machine->new( | ||
| 75 | resource => 'App::MFILE::WWW::Resource', | ||
| 76 | )->to_app; | ||
| 77 | |||
| 78 | |||
| 79 | |||
| 80 | |||
| 81 | =head1 DESCRIPTION | ||
| 82 | |||
| 83 | This is where we override the default versions of various methods defined by | ||
| 84 | L<Web::Machine::Resource>. | ||
| 85 | |||
| 86 | =cut | ||
| 87 | |||
| 88 | |||
| 89 | |||
| 90 | |||
| 91 | =head1 METHODS | ||
| 92 | |||
| 93 | |||
| 94 | =head2 context | ||
| 95 | |||
| 96 | This method is where we store data that needs to be shared among | ||
| 97 | routines in this module. | ||
| 98 | |||
| 99 | =cut | ||
| 100 | |||
| 101 | sub context { | ||
| 102 | my $self = shift; | ||
| 103 | $self->{'context'}; | ||
| 104 | } | ||
| 105 | |||
| 106 | |||
| 107 | =head2 remote_addr | ||
| 108 | |||
| 109 | =cut | ||
| 110 | |||
| 111 | sub remote_addr { | ||
| 112 | my $self = shift; | ||
| 113 | return $self->request->{'env'}->{'REMOTE_ADDR'}; | ||
| 114 | } | ||
| 115 | |||
| 116 | |||
| 117 | =head2 session | ||
| 118 | |||
| 119 | =cut | ||
| 120 | |||
| 121 | sub session { | ||
| 122 | my $self = shift; | ||
| 123 | if ( @_ ) { | ||
| 124 | $self->request->{'env'}->{'psgix.session'} = shift; | ||
| 125 | } | ||
| 126 | return $self->request->{'env'}->{'psgix.session'}; | ||
| 127 | } | ||
| 128 | |||
| 129 | |||
| 130 | =head2 session_id | ||
| 131 | |||
| 132 | =cut | ||
| 133 | |||
| 134 | sub session_id { | ||
| 135 | my $self = shift; | ||
| 136 | return $self->request->{'env'}->{'psgix.session.options'}->{'id'}; | ||
| 137 | } | ||
| 138 | |||
| 139 | |||
| 140 | =head2 service_available | ||
| 141 | |||
| 142 | This is the first method called on every incoming request. | ||
| 143 | |||
| 144 | =cut | ||
| 145 | |||
| 146 | sub service_available { | ||
| 147 | my $self = shift; | ||
| 148 | $log->debug( "Entering " . __PACKAGE__ . "::service_available()" ); | ||
| 149 | $log->info( "Incoming " . $self->request->method . " request for " . $self->request->path_info ); | ||
| 150 | $self->{'context'} = {}; | ||
| 151 | return 1; | ||
| 152 | } | ||
| 153 | |||
| 154 | |||
| 155 | =head2 content_types_provided | ||
| 156 | |||
| 157 | For GET requests, this is where we add our HTML body to the HTTP response. | ||
| 158 | |||
| 159 | =cut | ||
| 160 | |||
| 161 | sub content_types_provided { | ||
| 162 | [ { 'text/html' => '_render_response_html' }, ] | ||
| 163 | } | ||
| 164 | |||
| 165 | sub _render_response_html { | ||
| 166 | my ( $self ) = @_; | ||
| 167 | $log->debug( "Entering " . __PACKAGE__ . "::_render_response_html" ); | ||
| 168 | |||
| 169 | my $r = $self->request; | ||
| 170 | my $session = $r->{'env'}->{'psgix.session'}; | ||
| 171 | my $ce = $session->{'currentUser'}; | ||
| 172 | my $cepriv = $session->{'currentUserPriv'}; | ||
| 173 | my $entity; | ||
| 174 | if ( $r->path_info =~ m/test/i ) { | ||
| 175 | $log->debug( "Running unit tests" ); | ||
| 176 | $entity = $self->test_html(); | ||
| 177 | } else { | ||
| 178 | $log->debug( "Running the app" ); | ||
| 179 | $entity = $self->main_html( $ce, $cepriv ); | ||
| 180 | } | ||
| 181 | return $entity; | ||
| 182 | } | ||
| 183 | |||
| 184 | |||
| 185 | |||
| 186 | =head2 charsets_provided | ||
| 187 | |||
| 188 | This method causes L<Web::Machine> to encode the response body in UTF-8. | ||
| 189 | |||
| 190 | =cut | ||
| 191 | |||
| 192 | sub charsets_provided { | ||
| 193 | [ 'utf-8' ]; | ||
| 194 | } | ||
| 195 | |||
| 196 | |||
| 197 | |||
| 198 | =head2 default_charset | ||
| 199 | |||
| 200 | Really use UTF-8 all the time. | ||
| 201 | |||
| 202 | =cut | ||
| 203 | |||
| 204 | sub default_charset { | ||
| 205 | 'utf-8'; | ||
| 206 | } | ||
| 207 | |||
| 208 | |||
| 209 | |||
| 210 | =head2 allowed_methods | ||
| 211 | |||
| 212 | Determines which HTTP methods we recognize. | ||
| 213 | |||
| 214 | =cut | ||
| 215 | |||
| 216 | sub allowed_methods { | ||
| 217 | [ 'GET', 'POST', ]; | ||
| 218 | } | ||
| 219 | |||
| 220 | |||
| 221 | |||
| 222 | =head2 uri_too_long | ||
| 223 | |||
| 224 | Is the URI too long? | ||
| 225 | |||
| 226 | =cut | ||
| 227 | |||
| 228 | sub uri_too_long { | ||
| 229 | my ( $self, $uri ) = @_; | ||
| 230 | |||
| 231 | ( length $uri > $site->MFILE_URI_MAX_LENGTH ) | ||
| 232 | ? 1 | ||
| 233 | : 0; | ||
| 234 | } | ||
| 235 | |||
| 236 | |||
| 237 | =head2 is_authorized | ||
| 238 | |||
| 239 | Since all requests go through this function at a fairly early stage, we | ||
| 240 | leverage it to validate the session. | ||
| 241 | |||
| 242 | =cut | ||
| 243 | |||
| 244 | sub is_authorized { | ||
| 245 | my ( $self ) = @_; | ||
| 246 | |||
| 247 | $log->debug( "Entering " . __PACKAGE__ . "::is_authorized()" ); | ||
| 248 | |||
| 249 | my $r = $self->request; | ||
| 250 | my $session = $self->session; | ||
| 251 | my $remote_addr = $self->remote_addr; | ||
| 252 | my $ce; | ||
| 253 | |||
| 254 | #$log->debug( "Environment is " . Dumper( $r->{'env'} ) ); | ||
| 255 | $log->debug( "Session is " . Dumper( $session ) ); | ||
| 256 | |||
| 257 | # authorized session | ||
| 258 | if ( $ce = $session->{'currentUser'} and | ||
| 259 | $session->{'ip_addr'} and | ||
| 260 | $session->{'ip_addr'} eq $remote_addr and | ||
| 261 | _is_fresh( $session ) ) | ||
| 262 | { | ||
| 263 | $log->debug( "is_authorized: Authorized session, employee " . $ce->{'nick'} ); | ||
| 264 | $session->{'last_seen'} = time; | ||
| 265 | return 1; | ||
| 266 | } | ||
| 267 | |||
| 268 | # login attempt | ||
| 269 | if ( $r->method eq 'POST' and | ||
| 270 | $self->context->{'request_body'} and | ||
| 271 | $self->context->{'request_body'}->{'method'} and | ||
| 272 | $self->context->{'request_body'}->{'method'} =~ m/^LOGIN/i ) { | ||
| 273 | $log->debug( "is_authorized: Login attempt - pass it on" ); | ||
| 274 | return 1; | ||
| 275 | } | ||
| 276 | |||
| 277 | # bypass login dialog? | ||
| 278 | if ( $site->MFILE_WWW_BYPASS_LOGIN_DIALOG ) { | ||
| 279 | $log->warn( "Bypassing login dialog! Using default credentials" ); | ||
| 280 | # | ||
| 281 | # since the credentials are set in the configuration file, we only | ||
| 282 | # need to check them once - the result of this check is placed in | ||
| 283 | # META_LOGIN_BYPASS_STATE | ||
| 284 | # | ||
| 285 | if ( not defined $meta->META_LOGIN_BYPASS_STATE ) { | ||
| 286 | $meta->set('META_LOGIN_BYPASS_STATE', 0); | ||
| 287 | $session->{'ip_addr'} = $remote_addr; | ||
| 288 | $session->{'last_seen'} = time; | ||
| 289 | my $bypass_status = $self->validate_user_credentials( { | ||
| 290 | 'nam' => $site->MFILE_WWW_DEFAULT_LOGIN_CREDENTIALS->{'nam'}, | ||
| 291 | 'pwd' => $site->MFILE_WWW_DEFAULT_LOGIN_CREDENTIALS->{'pwd'}, | ||
| 292 | } ); | ||
| 293 | if ( $bypass_status->level() eq 'OK' ) { | ||
| 294 | $meta->set('META_LOGIN_BYPASS_STATE', 1); | ||
| 295 | } | ||
| 296 | } | ||
| 297 | return $meta->META_LOGIN_BYPASS_STATE; | ||
| 298 | } | ||
| 299 | |||
| 300 | # unauthorized session | ||
| 301 | $log->debug( "is_authorized fall-through: " . $r->method . " " . $self->request->path_info ); | ||
| 302 | return ( $r->method eq 'GET' ) ? 1 : 0; | ||
| 303 | } | ||
| 304 | |||
| 305 | |||
| 306 | =head2 _is_fresh | ||
| 307 | |||
| 308 | Takes a single argument, the PSGI session, which is assumed to contain a | ||
| 309 | C<last_seen> attribute containing the number of seconds since epoch when the | ||
| 310 | session was last seen. | ||
| 311 | |||
| 312 | =cut | ||
| 313 | |||
| 314 | sub _is_fresh { | ||
| 315 | my ( $session ) = validate_pos( @_, { type => HASHREF } ); | ||
| 316 | |||
| 317 | return 0 unless my $last_seen = $session->{'last_seen'}; | ||
| 318 | |||
| 319 | return ( time - $last_seen > $site->MFILE_WWW_SESSION_EXPIRATION_TIME ) | ||
| 320 | ? 0 | ||
| 321 | : 1; | ||
| 322 | } | ||
| 323 | |||
| 324 | |||
| 325 | =head2 known_content_type | ||
| 326 | |||
| 327 | Looks at the 'Content-Type' header of POST requests, and generates | ||
| 328 | a "415 Unsupported Media Type" response if it is anything other than | ||
| 329 | 'application/json'. | ||
| 330 | |||
| 331 | =cut | ||
| 332 | |||
| 333 | sub known_content_type { | ||
| 334 | my ( $self, $content_type ) = @_; | ||
| 335 | |||
| 336 | #$log->debug( "known_content_type: " . Dumper $content_type ); | ||
| 337 | # for GET requests, we don't care about the content | ||
| 338 | return 1 if $self->request->method eq 'GET'; | ||
| 339 | |||
| 340 | # some requests may not specify a Content-Type at all | ||
| 341 | return 0 if not defined $content_type; | ||
| 342 | |||
| 343 | # unfortunately, Web::Machine sometimes sends the content-type | ||
| 344 | # as a plain string, and other times as an | ||
| 345 | # HTTP::Headers::ActionPack::MediaType object | ||
| 346 | if ( ref( $content_type ) eq '' ) { | ||
| 347 | return ( $content_type =~ m/application\/json/ ) ? 1 : 0; | ||
| 348 | } | ||
| 349 | if ( ref( $content_type ) eq 'HTTP::Headers::ActionPack::MediaType' ) { | ||
| 350 | $log->debug( "Content type is a HTTP::Headers::ActionPack::MediaType object!" ); | ||
| 351 | return $content_type->match( 'application/json' ) ? 1 : 0; | ||
| 352 | } | ||
| 353 | return 0; | ||
| 354 | } | ||
| 355 | |||
| 356 | |||
| 357 | =head2 malformed_request | ||
| 358 | |||
| 359 | This test examines the request body. It can either be empty or contain | ||
| 360 | valid JSON; otherwise, a '400 Malformed Request' response is returned. | ||
| 361 | If it contains valid JSON, it is converted into a Perl hashref and | ||
| 362 | stored in the 'request_body' attribute of the context. | ||
| 363 | |||
| 364 | =cut | ||
| 365 | |||
| 366 | sub malformed_request { | ||
| 367 | my ( $self ) = @_; | ||
| 368 | |||
| 369 | # get the request body, which is UTF-8 ENCODED, so we decode it | ||
| 370 | # into a normal Perl scalar | ||
| 371 | my $body = decode_utf8( $self->request->content ); | ||
| 372 | |||
| 373 | return 0 if not defined $body or $body eq ''; | ||
| 374 | return 0 if defined $self->context and exists $self->context->{'request_body'}; | ||
| 375 | |||
| 376 | $log->debug( "malformed_request: incoming content body ->$body<-" ); | ||
| 377 | |||
| 378 | # there is a request body -- attempt to convert it | ||
| 379 | my $result = 0; | ||
| 380 | try { | ||
| 381 | $self->context->{'request_body'} = JSON->new->utf8(0)->decode( $body ); | ||
| 382 | } | ||
| 383 | catch { | ||
| 384 | $log->error( "Caught JSON error: $_" ); | ||
| 385 | $result = 1; | ||
| 386 | }; | ||
| 387 | |||
| 388 | if ( $result == 0 ) { | ||
| 389 | $log->debug( "malformed_request: body after JSON decode " . | ||
| 390 | ( ( $self->context->{'request_body'}->{'method'} eq 'LOGIN' ) | ||
| 391 | ? 'login/logout request' | ||
| 392 | : Dumper $self->context->{'request_body'} ) ); | ||
| 393 | } | ||
| 394 | |||
| 395 | return $result; | ||
| 396 | } | ||
| 397 | |||
| 398 | |||
| 399 | =head3 main_html | ||
| 400 | |||
| 401 | Takes the session object and returns HTML string to be displayed in the user's | ||
| 402 | browser. | ||
| 403 | |||
| 404 | FIXME: might be worth spinning this off into a separate module. | ||
| 405 | |||
| 406 | =cut | ||
| 407 | |||
| 408 | sub main_html { | ||
| 409 | my ( $self, $ce, $cepriv ) = @_; | ||
| 410 | $log->debug( "Entering " . __PACKAGE__ . "::main_html" ); | ||
| 411 | |||
| 412 | $cepriv = '' unless defined( $cepriv ); | ||
| 413 | $log->debug( "Entering " . __PACKAGE__ . "::main_html() with \$ce " . | ||
| 414 | Dumper($ce) . " and \$cepriv " . $cepriv ); | ||
| 415 | |||
| 416 | my $r = '<!DOCTYPE html>'; | ||
| 417 | $r .= '<html>'; | ||
| 418 | $r .= '<head>'; | ||
| 419 | $r .= '<meta charset="utf-8">'; | ||
| 420 | # $r .= '<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">'; | ||
| 421 | # $r .= '<meta http-equiv="Pragma" content="no-cache">'; | ||
| 422 | # $r .= '<meta http-equiv="Expires" content="0">'; | ||
| 423 | $r .= "<title>App::MFILE::WWW " . $meta->META_MFILE_APPVERSION . "</title>"; | ||
| 424 | $r .= '<link rel="stylesheet" type="text/css" href="/css/start.css" />'; | ||
| 425 | |||
| 426 | # Bring in RequireJS with testing == 0 (false) | ||
| 427 | $r .= $self->_require_js(0, $ce, $cepriv); | ||
| 428 | |||
| 429 | $r .= '</head>'; | ||
| 430 | $r .= '<body>'; | ||
| 431 | $r .= '<div id="myLoadProgress" class="loadProgress">Loading RequireJS...</div>'; | ||
| 432 | |||
| 433 | # Start the main app logic | ||
| 434 | $r .= '<script>require([\'main\']);</script>'; | ||
| 435 | |||
| 436 | $r .= '</body>'; | ||
| 437 | $r .= '</html>'; | ||
| 438 | return $r; | ||
| 439 | } | ||
| 440 | |||
| 441 | |||
| 442 | =head3 test_html | ||
| 443 | |||
| 444 | Generate html for running (core and app) unit tests. The following JS files are | ||
| 445 | run (in this order): | ||
| 446 | |||
| 447 | =over | ||
| 448 | |||
| 449 | =item test.js (in mfile-www core) | ||
| 450 | |||
| 451 | =item test.js (in app, e.g. dochazka-www) | ||
| 452 | |||
| 453 | =item test-go.js (in mfile-www core) | ||
| 454 | |||
| 455 | =back | ||
| 456 | |||
| 457 | =cut | ||
| 458 | |||
| 459 | sub test_html { | ||
| 460 | my ( $self ) = @_; | ||
| 461 | $log->debug( "Entering " . __PACKAGE__ . "::test_html" ); | ||
| 462 | |||
| 463 | my $r = ''; | ||
| 464 | |||
| 465 | $r = '<!DOCTYPE html>'; | ||
| 466 | $r .= '<html>'; | ||
| 467 | $r .= '<head>'; | ||
| 468 | $r .= '<meta charset="utf-8">'; | ||
| 469 | $r .= '<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">'; | ||
| 470 | $r .= '<meta http-equiv="Pragma" content="no-cache">'; | ||
| 471 | $r .= '<meta http-equiv="Expires" content="0">'; | ||
| 472 | $r .= "<title>App::MFILE::WWW " . $meta->META_MFILE_APPVERSION . " (Unit testing)</title>"; | ||
| 473 | $r .= '<link rel="stylesheet" type="text/css" href="/css/qunit.css" />'; | ||
| 474 | |||
| 475 | # Bring in RequireJS with testing == 1 (true) | ||
| 476 | $r .= $self->_require_js(1); | ||
| 477 | |||
| 478 | $r .= '</head><body>'; | ||
| 479 | $r .= '<div id="myLoadProgress" class="loadProgress">Loading RequireJS...</div>'; | ||
| 480 | $r .= '<div id="qunit"></div>'; | ||
| 481 | $r .= '<div id="qunit-fixture"></div>'; | ||
| 482 | |||
| 483 | # Run unit tests; see: | ||
| 484 | # - test.js (in mfile-www core) | ||
| 485 | # - app/test.js (in app; e.g. dochazka-www | ||
| 486 | # - test-go.js (in mfile-www core) | ||
| 487 | $r .= '<script>require([\'test\', \'app/test\', \'test-go\']);</script>'; | ||
| 488 | |||
| 489 | $r .= '</body></html>'; | ||
| 490 | return $r; | ||
| 491 | } | ||
| 492 | |||
| 493 | |||
| 494 | # HTML necessary for RequireJS | ||
| 495 | sub _require_js { | ||
| 496 | my ( $self, $testing, $ce, $cepriv ) = @_; | ||
| 497 | |||
| 498 | my $r = ''; | ||
| 499 | |||
| 500 | $r .= "<script src='" . $site->MFILE_WWW_JS_REQUIREJS . "'></script>"; | ||
| 501 | |||
| 502 | $r .= '<script>'; | ||
| 503 | |||
| 504 | # configure RequireJS | ||
| 505 | $r .= 'require.config({'; | ||
| 506 | |||
| 507 | # baseUrl is where we have all our JavaScript files | ||
| 508 | $r .= 'baseUrl: "' . $site->MFILE_WWW_REQUIREJS_BASEURL . '",'; | ||
| 509 | |||
| 510 | # map 'jquery' module to 'jquery-private.js' | ||
| 511 | # (of course, the real 'jquery.js' must be present in 'js/') | ||
| 512 | $r .= 'map: {'; | ||
| 513 | $r .= " '*': { 'jquery': 'jquery-private' },"; | ||
| 514 | $r .= " 'jquery-private': { 'jquery': 'jquery' }"; | ||
| 515 | $r .= '},'; | ||
| 516 | |||
| 517 | # callbacks for showing module loading progress | ||
| 518 | $r .= 'onNodeCreated: function(node, config, moduleName, url) {'; | ||
| 519 | $r .= " var t = document.getElementById('myLoadProgress'),"; | ||
| 520 | $r .= " m = '';"; | ||
| 521 | $r .= " m = 'module ' + moduleName + ' is about to be loaded';"; | ||
| 522 | $r .= " console.log(m);"; | ||
| 523 | $r .= " t.innerHTML = m;"; | ||
| 524 | $r .= " node.addEventListener('load', function() {"; | ||
| 525 | $r .= " m = 'module ' + moduleName + ' has been loaded';"; | ||
| 526 | $r .= " console.log(m);"; | ||
| 527 | $r .= " t.innerHTML = m;"; | ||
| 528 | $r .= ' });'; | ||
| 529 | $r .= " node.addEventListener('error', function() {"; | ||
| 530 | $r .= " m = 'module ' + moduleName + ' could not be loaded';"; | ||
| 531 | $r .= " console.log(m);"; | ||
| 532 | $r .= " t.innerHTML = m;"; | ||
| 533 | $r .= ' });'; | ||
| 534 | $r .= '},'; | ||
| 535 | |||
| 536 | # path config | ||
| 537 | $r .= 'paths: {'; | ||
| 538 | $r .= ' "app": "../' . $site->MFILE_APPNAME . '",'; # sibling to baseUrl | ||
| 539 | $r .= ' "QUnit": "qunit"'; # in baseUrl | ||
| 540 | $r .= '},'; | ||
| 541 | |||
| 542 | # QUnit needs some coaxing to work together with RequireJS | ||
| 543 | $r .= 'shim: {'; | ||
| 544 | $r .= ' "QUnit": {'; | ||
| 545 | $r .= ' exports: "QUnit",'; | ||
| 546 | $r .= ' init: function () {'; | ||
| 547 | $r .= ' QUnit.config.autoload = false;'; | ||
| 548 | $r .= ' QUnit.config.autostart = false;'; | ||
| 549 | $r .= ' }'; | ||
| 550 | $r .= ' }'; | ||
| 551 | $r .= '},'; | ||
| 552 | |||
| 553 | # default waitSeconds is just 7, which is too little for production | ||
| 554 | $r .= 'waitSeconds: 30'; | ||
| 555 | |||
| 556 | # end of require.config | ||
| 557 | $r .= "});"; | ||
| 558 | |||
| 559 | # initialize configuration parameters that we need on JavaScript side | ||
| 560 | $r .= 'requirejs.config({ config: {'; | ||
| 561 | $r .= '\'cf\': { '; | ||
| 562 | |||
| 563 | # appName, appVersion | ||
| 564 | $r .= 'appName: \'' . $site->MFILE_APPNAME . '\','; | ||
| 565 | $r .= 'appVersion: \'' . $meta->META_MFILE_APPVERSION . '\','; | ||
| 566 | |||
| 567 | # standaloneMode (boolean; false means "derived distro mode") | ||
| 568 | $r .= 'standaloneMode: \'' . ( $meta->META_WWW_STANDALONE_MODE ? 'true' : 'false' ) . '\','; | ||
| 569 | |||
| 570 | # currentUser | ||
| 571 | $r .= "currentUser: " . ( $ce ? to_json( $ce ) : 'null' ) . ','; | ||
| 572 | $r .= "currentUserPriv: " . ( $cepriv ? "\'$cepriv\'" : 'null' ) . ','; | ||
| 573 | |||
| 574 | # loginDialog | ||
| 575 | $r .= 'loginDialogChallengeText: \'' . $site->MFILE_WWW_LOGIN_DIALOG_CHALLENGE_TEXT . '\','; | ||
| 576 | $r .= 'loginDialogMaxLengthUsername: ' . $site->MFILE_WWW_LOGIN_DIALOG_MAXLENGTH_USERNAME . ','; | ||
| 577 | $r .= 'loginDialogMaxLengthPassword: ' . $site->MFILE_WWW_LOGIN_DIALOG_MAXLENGTH_PASSWORD . ','; | ||
| 578 | |||
| 579 | # session data | ||
| 580 | $r .= 'displaySessionData: ' . ( $site->MFILE_WWW_DISPLAY_SESSION_DATA ? 'true' : 'false' ) . ','; | ||
| 581 | if ( $site->MFILE_WWW_DISPLAY_SESSION_DATA ) { | ||
| 582 | $r .= 'sessionID: \'' . $self->session_id . '\','; | ||
| 583 | $r .= 'sessionLastSeen: \'' . ( exists $self->session->{'last_seen'} ? $self->session->{'last_seen'} : 'never' ) . '\','; | ||
| 584 | } | ||
| 585 | |||
| 586 | # REST server URI | ||
| 587 | if ( defined( $site->DOCHAZKA_WWW_BACKEND_URI ) ) { | ||
| 588 | $r .= 'restURI: \'' . $site->DOCHAZKA_WWW_BACKEND_URI . '\','; | ||
| 589 | } | ||
| 590 | |||
| 591 | # dummyParam in last position so we don't have to worry about comma/no comma | ||
| 592 | $r .= 'dummyParam: null,'; | ||
| 593 | |||
| 594 | # unit tests running? | ||
| 595 | $r .= "testing: " . ( $testing ? 'true' : 'false' ); | ||
| 596 | |||
| 597 | $r .= '} } });'; | ||
| 598 | $r .= '</script>'; | ||
| 599 | return $r; | ||
| 600 | } | ||
| 601 | |||
| 602 | |||
| 603 | =head2 login_status | ||
| 604 | |||
| 605 | Once the username and password are known (either from C<process_post> via the | ||
| 606 | login AJAX request generated by the login dialog, or from the site | ||
| 607 | configuration via the MFILE_WWW_BYPASS_LOGIN_DIALOG mechanism), the | ||
| 608 | C<validate_user_credentials> method is called. That method is implemented by | ||
| 609 | the derived application, so it can validate user credentials however it likes. | ||
| 610 | The C<validate_user_credentials> method is then expected to call this method - | ||
| 611 | C<login_status> - to generate a status object from the results of the user | ||
| 612 | credentials validation. | ||
| 613 | |||
| 614 | Now, C<App::MFILE::WWW> does expect the C<validate_user_credentials> method to | ||
| 615 | provide the results of user credentials validation in a peculiar format, | ||
| 616 | hinging on the argument C<$code>, where a value of 200 indicates successful | ||
| 617 | validation and any other value indicates a failure. | ||
| 618 | |||
| 619 | =cut | ||
| 620 | |||
| 621 | sub login_status { | ||
| 622 | my ( $self, $code, $message, $body_json ) = @_; | ||
| 623 | |||
| 624 | my $status; | ||
| 625 | |||
| 626 | if ( $code == 200 ) { | ||
| 627 | $self->session->{'ip_addr'} = $self->remote_addr; | ||
| 628 | my $cu = $body_json->{'payload'}->{'emp'}; | ||
| 629 | delete $cu->{'passhash'}; | ||
| 630 | delete $cu->{'salt'}; | ||
| 631 | $self->session->{'currentUser'} = $cu; | ||
| 632 | $self->session->{'currentUserPriv'} = $body_json->{'payload'}->{'priv'}; | ||
| 633 | $self->session->{'last_seen'} = time; | ||
| 634 | $log->debug( | ||
| 635 | "Login successful, currentUser is now " . | ||
| 636 | Dumper( $body_json->{'payload'}->{'emp'} ) . | ||
| 637 | " and privilege level is " . $body_json->{'payload'}->{'priv'} | ||
| 638 | ); | ||
| 639 | $status = $CELL->status_ok( 'MFILE_WWW_LOGIN_OK', payload => $body_json->{'payload'} ); | ||
| 640 | } else { | ||
| 641 | $self->session({}); | ||
| 642 | $log->debug( "Login unsuccessful, reset session" ); | ||
| 643 | $status = $CELL->status_not_ok( | ||
| 644 | 'MFILE_WWW_LOGIN_FAIL: %s', | ||
| 645 | args => [ $code ], | ||
| 646 | payload => { code => $code, message => $message }, | ||
| 647 | ); | ||
| 648 | } | ||
| 649 | $self->response->header( 'Content-Type' => 'application/json' ); | ||
| 650 | $self->response->body( to_json( $status->expurgate ) ); | ||
| 651 | return $status; | ||
| 652 | } | ||
| 653 | |||
| 654 | |||
| 655 | =head2 ua | ||
| 656 | |||
| 657 | Returns the LWP::UserAgent object obtained from the lookup table. | ||
| 658 | Creates it first if necessary. | ||
| 659 | |||
| 660 | =cut | ||
| 661 | |||
| 662 | sub ua { | ||
| 663 | my $self = shift; | ||
| 664 | $log->debug( "Entering " . __PACKAGE__ . "::ua()" ); | ||
| 665 | my $id = $self->session_id; | ||
| 666 | $log->debug( "ua: session_id is $id" ); | ||
| 667 | |||
| 668 | # already in lookup table | ||
| 669 | if ( exists $ualt->{$id} ) { | ||
| 670 | $log->debug( "Session $id already has a LWP::UserAgent object" ); | ||
| 671 | return $ualt->{$id}; | ||
| 672 | } | ||
| 673 | |||
| 674 | # not in lookup table yet | ||
| 675 | my $tf = ""; | ||
| 676 | ( undef, $tf ) = tempfile(); | ||
| 677 | $ualt->{$id} = LWP::UserAgent->new; | ||
| 678 | $ualt->{$id}->cookie_jar({ file => $tf }); | ||
| 679 | $log->info("New user agent created with cookies in $tf"); | ||
| 680 | return $ualt->{$id}; | ||
| 681 | } | ||
| 682 | |||
| 683 | |||
| 684 | =head2 rest_req | ||
| 685 | |||
| 686 | Algorithm: send request to REST server, get JSON response, decode it, return | ||
| 687 | it. | ||
| 688 | |||
| 689 | Takes a single _mandatory_ parameter: a LWP::UserAgent object | ||
| 690 | |||
| 691 | Optionally takes PARAMHASH: | ||
| 692 | |||
| 693 | server => [URI OF REST SERVER] default is 'http://0:5000' | ||
| 694 | method => [HTTP METHOD TO USE] default is 'GET' | ||
| 695 | nick => [NICK FOR BASIC AUTH] optional | ||
| 696 | password => [PASSWORD FOR BASIC AUTH] optional | ||
| 697 | path => [PATH OF REST RESOURCE] default is '/' | ||
| 698 | req_body => [HASHREF] optional | ||
| 699 | |||
| 700 | Returns HASHREF containing: | ||
| 701 | |||
| 702 | hr => HTTP::Response object (stripped of the body) | ||
| 703 | body => [BODY OF HTTP RESPONSE, IF ANY] | ||
| 704 | |||
| 705 | =cut | ||
| 706 | |||
| 707 | sub rest_req { | ||
| 708 | my $self = shift; | ||
| 709 | |||
| 710 | # process arguments | ||
| 711 | my $ua = $self->ua(); | ||
| 712 | die "Bad user agent object" unless ref( $ua ) eq 'LWP::UserAgent'; | ||
| 713 | my %ARGS = validate( @_, { | ||
| 714 | server => { type => SCALAR, default => 'http://localhost:5000' }, | ||
| 715 | method => { type => SCALAR, default => 'GET', regex => qr/^(GET|POST|PUT|DELETE)$/ }, | ||
| 716 | nick => { type => SCALAR, optional => 1 }, | ||
| 717 | password => { type => SCALAR, default => '' }, | ||
| 718 | path => { type => SCALAR, default => '/' }, | ||
| 719 | req_body => { type => HASHREF, optional => 1 }, | ||
| 720 | } ); | ||
| 721 | $ARGS{'path'} =~ s/^\/*/\//; | ||
| 722 | |||
| 723 | my $r; | ||
| 724 | { | ||
| 725 | no strict 'refs'; | ||
| 726 | $r = &{ $ARGS{'method'} }( $ARGS{'server'} . encode_utf8( $ARGS{'path'} ), | ||
| 727 | Accept => 'application/json' ); | ||
| 728 | } | ||
| 729 | |||
| 730 | if ( $ARGS{'nick'} ) { | ||
| 731 | $r->authorization_basic( $ARGS{'nick'}, $ARGS{'password'} ); | ||
| 732 | } | ||
| 733 | |||
| 734 | if ( $ARGS{'method'} =~ m/^(POST|PUT)$/ ) { | ||
| 735 | $r->header( 'Content-Type' => 'application/json' ); | ||
| 736 | if ( my $body = $ARGS{'req_body'} ) { | ||
| 737 | my $tmpvar = JSON->new->utf8(0)->encode( $body ); | ||
| 738 | $r->content( encode_utf8( $tmpvar ) ); | ||
| 739 | } | ||
| 740 | } | ||
| 741 | |||
| 742 | # request is ready - send it and get response | ||
| 743 | my $response = $ua->request( $r ); | ||
| 744 | |||
| 745 | # process response | ||
| 746 | my $body_json = $response->decoded_content; | ||
| 747 | $log->debug( "rest_req: decoded JSON body " . Dumper $body_json ); | ||
| 748 | $response->content(''); | ||
| 749 | my $body; | ||
| 750 | try { | ||
| 751 | $body = JSON->new->decode( $body_json ); | ||
| 752 | } catch { | ||
| 753 | $body = { 'code' => $body, 'text' => $body }; | ||
| 754 | }; | ||
| 755 | |||
| 756 | return { | ||
| 757 | hr => $response, | ||
| 758 | body => $body | ||
| 759 | }; | ||
| 760 | } | ||
| 761 | |||
| 762 | 1; |