Debian Codegraph @

lemonldap-ng-common/lib/Lemonldap/NG/Common/PSGI.pm

raw
1 package Lemonldap::NG::Common::PSGI;
2
3 use strict;
4 use Mouse;
5 use HTTP::Status;
6 use JSON;
7 use Lemonldap::NG::Common::PSGI::Constants;
8 use Lemonldap::NG::Common::PSGI::Request;
9
10 our $VERSION = '2.23.0';
11
12 our $_json = JSON->new->allow_nonref;
13
14 # PROPERTIES
15
16 has error => ( is => 'rw', default => '' );
17 has languages => ( is => 'rw', isa => 'Str', default => 'en' );
18 has logLevel => ( is => 'rw', isa => 'Str', default => 'info' );
19 has staticPrefix => ( is => 'rw', isa => 'Str' );
20 has instanceName => ( is => 'rw', isa => 'Str', default => '' );
21 has customCSS => ( is => 'rw', isa => 'Str', default => '' );
22 has customPortalUrl => ( is => 'rw', isa => 'Str', default => '' );
23 has templateDir => ( is => 'rw', isa => 'Str|ArrayRef' );
24 has links => ( is => 'rw', isa => 'ArrayRef' );
25 has menuLinks => ( is => 'rw', isa => 'ArrayRef' );
26 has logger => ( is => 'rw' );
27 has userLogger => ( is => 'rw' );
28 has _auditLogger => ( is => 'rw' );
29
30 # portal only stores the "default" portal URL, in case a request
31 # is not available in the current context to compute the dynamic portal URL
32 has portal => ( is => 'rw', isa => 'Str' );
33
34 # INITIALIZATION
35
36 sub init {
37 my ( $self, $args ) = @_;
38 unless ( ref $args ) {
39 $self->error('init argument must be a hashref');
40 return 0;
41 }
42 foreach my $k ( keys %$args ) {
43 $self->{$k} = $args->{$k} unless ( $k eq 'logger' );
44 }
45 $self->_initLogger($args);
46
47 return 1;
48 }
49
50 sub _initLogger {
51 my ( $self, $args ) = @_;
52
53 my $logger =
54 $args->{logger}
55 || $ENV{LLNG_DEFAULTLOGGER}
56 || 'Lemonldap::NG::Common::Logger::Std';
57 unless ( ref $self->logger ) {
58 eval "require $logger";
59 die $@ if ($@);
60 my $err;
61 unless ( $self->{logLevel} =~ /^(?:debug|info|notice|warn|error)$/ ) {
62 $err =
63 'Bad logLevel value \''
64 . $self->{logLevel}
65 . "', switching to 'info'";
66 $self->{logLevel} = 'info';
67 }
68 $self->logger( $logger->new($self) );
69 $self->logger->error($err) if $err;
70 }
71
72 unless ( ref $self->userLogger ) {
73 $logger = $ENV{LLNG_USERLOGGER} || $args->{userLogger} || $logger;
74 eval "require $logger";
75 die $@ if ($@);
76 require Lemonldap::NG::Common::Logger::_Duplicate;
77 $self->userLogger(
78 Lemonldap::NG::Common::Logger::_Duplicate->new(
79 $self,
80 user => 1,
81 logger => $logger,
82 dup => $self->logger
83 )
84 );
85 }
86
87 unless ( ref $self->_auditLogger ) {
88 $logger =
89 $ENV{LLNG_AUDITLOGGER}
90 || $args->{auditLogger}
91 || "Lemonldap::NG::Common::AuditLogger::UserLoggerCompat";
92 eval "require $logger";
93 die $@ if ($@);
94 $self->_auditLogger( $logger->new($self) );
95 }
96 }
97
98 sub getLanguage {
99 my ( $self, $req ) = @_;
100
101 # Get the list of allowed languages from config
102 my @langArray = split( qr/[ ,]+/, $self->languages );
103
104 # If the language in the cookie is found in allowed languages, use it
105 my $cookie_lang = $req->cookies->{llnglanguage};
106 if ( $cookie_lang and grep { $_ eq $cookie_lang } @langArray ) {
107 return $cookie_lang;
108 }
109
110 # Get ordered list of preferred languages from Accept-Language header
111 my @preferred_req_language = $self->_getLanguageListFromHeader($req);
112
113 # Go through preferred languages and pick the first allowed one
114 for my $req_lang (@preferred_req_language) {
115 if ( grep { lc($_) eq lc($req_lang) } @langArray ) {
116 return $req_lang;
117 }
118 }
119
120 # fallback: pick the first allowed language, default to english
121 return ( $langArray[0] || 'en' );
122 }
123
124 sub _getLanguageListFromHeader {
125 my ( $self, $req ) = @_;
126
127 # Extract [2 letter code, priority] from list of Accept-Language values
128 my @req_languages_and_prio = map {
129 my ( $lang, $prio ) = m/^(\w+)(?:.*q=(\d\.[\d+]))?/;
130 $prio ||= 1;
131
132 # Skip invalid entries
133 $lang ? ( [ $lang, $prio ] ) : ()
134 }
135 split( qr/\s*,\s*/, $req->languages || "" );
136
137 # Sort by priority (perl sort is stable by default)
138 @req_languages_and_prio =
139 sort { $b->[1] <=> $a->[1] } @req_languages_and_prio;
140
141 # Keep only language code
142 my @preferred_req_language = map { $_->[0] } @req_languages_and_prio;
143
144 return @preferred_req_language;
145 }
146
147 sub auditLog {
148 my ( $self, $req, %info ) = @_;
149 $self->_auditLogger->log( $req, %info );
150 }
151
152 # RUNNING METHODS
153
154 ## @method void lmLog(string mess, string level)
155 # Log subroutine. Print on STDERR messages if it exceeds `logLevel` value
156 # @param $mess Text to log
157 # @param $level Level (debug|info|notice|warn|error)
158 sub lmLog {
159 my ( $self, $msg, $level ) = @_;
160 return $self->logger->$level($msg);
161 }
162
163 ##@method void userLog(string mess, string level)
164 # Log user actions on Apache logs or syslog.
165 # @param $mess string to log
166 # @param $level level of log message
167 sub userLog {
168 my ( $self, $msg, $level ) = @_;
169 return $self->userLogger->$level($msg);
170 }
171
172 ##@method void userInfo(string mess)
173 # Log non important user actions. Alias for userLog() with facility "info".
174 # @param $mess string to log
175 sub userInfo {
176 my ( $self, $msg ) = @_;
177 return $self->userLogger->info($msg);
178 }
179
180 ##@method void userNotice(string mess)
181 # Log user actions like access and logout. Alias for userLog() with facility
182 # "notice".
183 # @param $mess string to log
184 sub userNotice {
185 my ( $self, $msg ) = @_;
186 return $self->userLogger->notice($msg);
187 }
188
189 ##@method void userWarn(string mess)
190 # Log user errors like "bad password". Alias for userLog() with facility
191 # "warn".
192 # @param $mess string to log
193 sub userWarn {
194 my ( $self, $msg ) = @_;
195 return $self->userLogger->warn($msg);
196 }
197
198 ##@method void userError(string mess)
199 # Log user errors like "try to change password without token". Alias for
200 # userLog() with facility "error".
201 # @param $mess string to log
202 sub userError {
203 my ( $self, $msg ) = @_;
204 return $self->userLogger->error($msg);
205 }
206
207 # Responses methods
208 sub sendJSONresponse {
209 my ( $self, $req, $j, %args ) = @_;
210 $args{code} ||= 200;
211 $args{headers} ||= [ $req->spliceHdrs ];
212 my $type = 'application/json; charset=utf-8';
213 if ( ref $j ) {
214 eval {
215 if ( $args{pretty} ) {
216
217 # This avoids changing the settings of the $_json reference
218 $j = to_json(
219 $j,
220 {
221 allow_nonref => 1,
222 pretty => 1,
223 canonical => 1
224 }
225 );
226 }
227 else {
228 $j = $_json->encode($j);
229 }
230 };
231 return $self->sendError( $req, $@ ) if ($@);
232 }
233 utf8::downgrade($j);
234 return $self->_buildPsgiResponse(
235 $args{code},
236 [
237 'Content-Type' => $type,
238 'Content-Length' => length($j),
239 @{ $args{headers} }
240 ],
241 [$j]
242 );
243 }
244
245 sub sendError {
246 my ( $self, $req, $err, $code ) = @_;
247 $err ||= $req->error || '';
248 $code ||= 500;
249 $self->lmLog( "Error $code: $err", $code > 499 ? 'error' : 'notice' );
250
251 # SOAP responses
252 if ( $req->env->{HTTP_SOAPACTION} ) {
253 my $s = '<soapenv:Body>
254 <soapenv:Fault>
255 <Faultcode>soapenv:Client</Faultcode>
256 <Faultstring>' . $err . '.</Faultstring>
257 <Detail>
258 <Key>Fred</Key>
259 </Detail>
260 </soapenv:Fault>
261 </soapenv:Body>';
262 return $self->_buildPsgiResponse(
263 $code,
264 [
265 'Content-Type' => 'application/xml; charset=utf-8',
266 'Content-Length' => length($s),
267 $req->spliceHdrs,
268 ],
269 [$s]
270 );
271 }
272
273 # Handle Ajax responses
274 elsif ( ( $req->accept // "" ) =~ /json/ ) {
275 return $self->sendJSONresponse( $req, { error => $err },
276 code => $code );
277 }
278
279 # Default response: HTML
280 else {
281 my $title = eval { HTTP::Status::status_message($code) } || 'Error';
282 print STDERR $@ if $@;
283
284 # TODO: this should probably use a template instead
285 my $s = "<html><head><title>$title</title>
286 <style>
287 body{background:#000;color:#fff;padding:10px 50px;font-family:sans-serif;}a{text-decoration:none;color:#fff;}h1{text-align:center;}
288 </style>
289 </head>
290 <body>
291 <h1>$title</h1>
292 <p>$err</p>
293 <center><a href=\"https://lemonldap-ng.org\">LemonLDAP::NG</a></center>
294 </body>
295 </html>";
296 return $self->sendRawHtml( $req, $s, code => $code );
297 }
298 }
299
300 sub sendRawHtml {
301 my ( $self, $req, $s, %args ) = @_;
302 my $code = $args{code} || 200;
303 my $headers = $args{headers} || [ $req->spliceHdrs ];
304 return $self->_buildPsgiResponse(
305 $code,
306 [
307 'Content-Type' => 'text/html; charset=utf-8',
308 'Content-Length' => length($s),
309 @{$headers},
310 ],
311 [$s]
312 );
313 }
314
315 sub abort {
316 my ( $self, $err ) = @_;
317 eval { $self->logger->error($err) };
318 return $self->psgiAdapter(
319 sub {
320 $self->sendError( $_[0], $err, 500 );
321 }
322 );
323 }
324
325 sub _mustBeDefined {
326 my $name = ( caller(1) )[3];
327 $name =~ s/^.*:://;
328 my $call = ( caller(1) )[0];
329 my $ref = ref( $_[0] ) || $call;
330 die "$name() method must be implemented (probably in $ref)";
331 }
332
333 sub handler { _mustBeDefined(@_) }
334
335 sub sendJs {
336 my ( $self, $req ) = @_;
337 my $sp = $self->staticPrefix;
338 $sp =~ s/\/*$/\//;
339 my $sc = $req->script_name // "";
340
341 my $portal = $req->can('portal') ? $req->portal : $self->portal;
342
343 # Javascript scriptname is assumed by our JS code to end with /
344 $sc =~ s#/*$#/#;
345 my $s =
346 sprintf 'var staticPrefix="%s";'
347 . 'var scriptname="%s";'
348 . 'var availableLanguages="%s".split(/[,;] */);'
349 . 'var portal="%s";', $sp, $sc, $self->languages,
350 $portal;
351 $s .= $self->javascript($req) if ( $self->can('javascript') );
352 return $self->_buildPsgiResponse(
353 200,
354 [
355 'Content-Type' => 'application/javascript',
356 'Content-Length' => length($s),
357 'Cache-Control' => 'public,max-age=2592000',
358 ],
359 [$s]
360 );
361 }
362
363 sub sendTextResponse {
364 my ( $self, $req, $text, %args ) = @_;
365
366 my $data = $text;
367
368 #my $data = Encode::encode( "UTF-8", $text );
369
370 $args{type} ||= "text/plain; charset=utf-8";
371
372 return $self->sendBinaryResponse( $req, $data, %args );
373 }
374
375 sub sendBinaryResponse {
376 my ( $self, $req, $data, %args ) = @_;
377 $args{code} ||= 200;
378 $args{type} ||= "application/octet-stream";
379 my $headers = $args{headers} || [ $req->spliceHdrs ];
380
381 return $self->_buildPsgiResponse(
382 $args{code},
383 [
384 'Content-Type' => $args{type},
385 'Content-Length' => length($data),
386 @$headers,
387 ],
388 [$data]
389 );
390 }
391
392 sub sendHtml {
393 my ( $self, $req, $template, %args ) = @_;
394 my $sp = $self->staticPrefix;
395 $sp =~ s/\/*$/\//;
396 my $sc = $req->script_name // "";
397
398 # SCRIPTNAME is assumed by our templates to end with /
399 $sc =~ s#/*$#/#;
400 $args{code} ||= 200;
401 $args{headers} ||= [ $req->spliceHdrs ];
402 my $htpl;
403 eval {
404 $self->logger->debug("Starting HTML generation using $template");
405 require HTML::Template;
406 $htpl = HTML::Template->new(
407 filename => $template . ".tpl",
408 path => ( $args{templateDir} // $self->templateDir ),
409 search_path_on_include => 1,
410 die_on_bad_params => 0,
411 die_on_missing_include => 1,
412 cache => 0,
413 global_vars => 1,
414 loop_context_vars => 1,
415 );
416
417 # TODO: replace app
418 # TODO: warn if STATICPREFIX does not end with '/'
419 $htpl->param(
420 STATIC_PREFIX => $sp,
421 INSTANCE_NAME => $self->instanceName,
422 CUSTOM_CSS => $self->customCSS,
423 SCRIPTNAME => $sc,
424 ( $self->can('tplParams') ? ( $self->tplParams($req) ) : () ),
425 (
426 $args{params}
427 ? %{ $args{params} }
428 : ()
429 ),
430 );
431 };
432 if ($@) {
433 $self->logger->error("Unable to render template $template.tpl: $@");
434 return $self->sendError( $req,
435 "Unable to render template $template.tpl", 500 );
436 }
437
438 # Set headers
439 my $hdrs = [ 'Content-Type' => 'text/html', @{ $args{headers} } ];
440 $self->logger->debug("Sending $template");
441 return $self->_buildPsgiResponse( $args{code}, $hdrs, [ $htpl->output() ] );
442 }
443
444 ###############
445 # Main method #
446 ###############
447
448 sub run {
449 my ( $self, $args ) = @_;
450 $args //= {};
451 unless ( ref $self ) {
452 $self = $self->new($args);
453 $self->init($args) or $self->logger->error('Initialization failed');
454 }
455 return $self->_run;
456 }
457
458 sub _run {
459 my $self = shift;
460 return $self->psgiAdapter(
461 sub {
462 $self->handler( $_[0] );
463 }
464 );
465 }
466
467 # This method returns a sub that takes a Lemonldap::NG::Common::PSGI::Request
468 # object and returns a PSGI response into a proper PSGI method.
469 sub psgiAdapter {
470 my ( $self, $sub ) = @_;
471 return sub {
472 my $env = shift;
473 my $req = Lemonldap::NG::Common::PSGI::Request->new($env);
474 return $self->logAndRun( $req, $sub );
475 }
476 }
477
478 # This method sets up LemonLDAP::NG logging for the current request
479 sub logAndRun {
480 my ( $self, $req, $sub ) = @_;
481
482 # register the request object to the logging system
483 if ( ref( $self->logger ) and $self->logger->can('setRequestObj') ) {
484 $self->logger->setRequestObj($req);
485 }
486 if ( ref( $self->userLogger ) and $self->userLogger->can('setRequestObj') )
487 {
488 $self->userLogger->setRequestObj($req);
489 }
490
491 if ( ref $self->logger ) {
492 $self->logger->info( "New request "
493 . ref($self) . " "
494 . $req->method . " "
495 . $req->request_uri );
496 }
497 my $res = $sub->($req);
498
499 # Clear the logging system before the next request
500 if ( ref( $self->logger ) and $self->logger->can('clearRequestObj') ) {
501 $self->logger->clearRequestObj($req);
502 }
503 if ( ref( $self->userLogger )
504 and $self->userLogger->can('clearRequestObj') )
505 {
506 $self->userLogger->clearRequestObj($req);
507 }
508
509 return $res;
510 }
511
512 sub sendRedirection {
513 my ( $self, $req, $destination, %args ) = @_;
514
515 $args{code} ||= 302;
516 $args{headers} ||= [ $req->spliceHdrs ];
517
518 return $self->_buildPsgiResponse(
519 $args{code},
520 [
521 ( $destination ? ( Location => $destination ) : () ),
522 @{ $args{headers} }
523 ],
524 []
525 );
526 }
527
528 sub _buildPsgiResponse {
529 my ( $self, $code, $header, $data ) = @_;
530 return [ $code, $header, $data ];
531 }
532
533 1;
534 __END__
535
536 =head1 NAME
537
538 =encoding utf8
539
540 Lemonldap::NG::Common::PSGI - Base library for PSGI modules of Lemonldap::NG.
541 Use Lemonldap::NG::Common::PSGI::Router for REST API.
542
543 =head1 SYNOPSIS
544
545 package My::PSGI;
546
547 use base Lemonldap::NG::Common::PSGI;
548
549 sub init {
550 my ($self,$args) = @_;
551 # Will be called 1 time during startup
552
553 # Store debug level
554 $self->logLevel('info');
555 # It is possible to use syslog for user actions
556 $self->syslog('daemon');
557
558 # Return a boolean. If false, then error message has to be stored in
559 # $self->error
560 return 1;
561 }
562
563 sub handler {
564 my ( $self, $req ) = @_;
565 # Do something and return a PSGI response
566 # NB: $req is a Lemonldap::NG::Common::PSGI::Request object
567
568 return [ 200, [ 'Content-Type' => 'text/plain' ], [ 'Body lines' ] ];
569 }
570
571 This package could then be called as a CGI, using FastCGI,...
572
573 #!/usr/bin/env perl
574
575 use My::PSGI;
576 use Plack::Handler::FCGI; # or Plack::Handler::CGI
577
578 Plack::Handler::FCGI->new->run( My::PSGI->run() );
579
580 =head1 DESCRIPTION
581
582 This package provides base class for Lemonldap::NG web interfaces but could be
583 used regardless.
584
585 =head1 METHODS
586
587 =head2 Running methods
588
589 =head3 run ( $args )
590
591 Main method that will manage requests. It can be called using class or already
592 created object:
593
594 =over
595
596 =item Class->run($args):
597
598 launch new($args), init(), then manage requests (using private _run() method
599
600 =item $object->run():
601
602 manage directly requests. Initialization must have be done earlier.
603
604 =back
605
606 =head2 Logging
607
608 =head3 lmLog ( $msg, $level)
609
610 Print on STDERR messages if level > $self->{logLevel}. Defined log levels are:
611 debug, info, notice, warn, error.
612
613 =head3 userLog ($msg, $level)
614
615 Alias for $self->userLogger->$level($msg). Prefer to use this form (required
616 for Auth/Combination)
617
618 =head3 userError() userNotice() userInfo()
619
620 Alias for userLog(level). Note that you must use $self->userLogger->$level
621 instead
622
623 =head2 Content sending
624
625 Note that $req, the first argument of these functions, is a
626 L<Lemonldap::NG::Common::PSGI::Request>. See the corresponding documentation.
627
628 =head3 sendHtml ( $req, $template )
629
630 This method build HTML response using HTML::Template and the template $template.
631 $template file must be in $self->templateDir directory.
632 HTML template will receive 5 variables:
633
634 =over
635
636 =item SCRIPT_NAME: the path to the (F)CGI
637
638 =item STATIC_PREFIX: content of $self->staticPrefix
639
640 =item AVAILABLE_LANGUAGES: content of $self->languages
641
642 =item LINKS: JSON stringification of $self->links
643
644 =item VERSION: Lemonldap::NG version
645
646 =back
647
648 The response is always send with a 200 code.
649
650 =head3 sendJSONresponse ( $req, $json, %args )
651
652 Stringify $json object and send it to the client. $req is the
653 Lemonldap::NG::Common::PSGI::Request object; %args can define the HTTP error
654 code (200 by default) or headers to add.
655
656 If client is not json compatible (`Accept` header), response is send in XML.
657
658 Examples:
659
660 $self->sendJSONresponse ( $req, { result => 0 }, code => 400 );
661
662 $self->sendJSONresponse ( $req, { result => 1 } );
663
664 $self->sendJSONresponse ( $req, { result => 1 }, headers => [ X => Z ] );
665
666 =head3 sendError ( $req, $msg, $code )
667
668 Call sendJSONresponse with `{ error => $msg }` and code (default to 500) and
669 call lmLog() to duplicate error in logs
670
671 =head3 abort ( $msg )
672
673 When an error is detected during startup (init() sub), you must not call
674 sendError() but call abort(). Each request received later will receive the
675 error (abort uses sendError() behind the scene).
676
677 =head2 Accessors
678
679 =head3 error
680
681 String error. Used if init() fails or if sendError is called without argument.
682
683 =head3 languages
684
685 String containing list of languages (ie "fr, en'). Used by sendHtml().
686
687 =head3 logLevel
688
689 See lmLog().
690
691 =head3 staticPrefix
692
693 String indicating the path of static content (js, css,...). Used by sendHtml().
694
695 =head3 templateDir
696
697 Directory containing template files.
698
699 =head3 links
700
701 Array of links to display by sendHtml(). Each element has the form:
702
703 { target => 'http://target', title => 'string to display' }
704
705 =head3 syslog
706
707 Syslog facility. If empty, STDERR will be used for logging
708
709 =head1 SEE ALSO
710
711 L<http://lemonldap-ng.org/>, L<Lemonldap::NG::Portal>, L<Lemonldap::NG::Handler>,
712 L<Plack>, L<PSGI>, L<Lemonldap::NG::Common::PSGI::Router>,
713 L<Lemonldap::NG::Common::PSGI::Request>, L<HTML::Template>,
714
715 =head1 AUTHORS
716
717 =over
718
719 =item LemonLDAP::NG team L<http://lemonldap-ng.org/team>
720
721 =back
722
723 =head1 BUG REPORT
724
725 Use OW2 system to report bug or ask for features:
726 L<https://gitlab.ow2.org/lemonldap-ng/lemonldap-ng/issues>
727
728 =head1 DOWNLOAD
729
730 Lemonldap::NG is available at
731 L<https://lemonldap-ng.org/download>
732
733 =head1 COPYRIGHT AND LICENSE
734
735 See COPYING file for details.
736
737 This library is free software; you can redistribute it and/or modify
738 it under the terms of the GNU General Public License as published by
739 the Free Software Foundation; either version 2, or (at your option)
740 any later version.
741
742 This program is distributed in the hope that it will be useful,
743 but WITHOUT ANY WARRANTY; without even the implied warranty of
744 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
745 GNU General Public License for more details.
746
747 You should have received a copy of the GNU General Public License
748 along with this program. If not, see L<http://www.gnu.org/licenses/>.
749
750 =cut