PSGI.pm 11 KB
Newer Older
1 2 3 4
package Lemonldap::NG::Common::PSGI;

use 5.10.0;
use Mouse;
5
use JSON::MaybeXS;
6 7 8
use Lemonldap::NG::Common::PSGI::Constants;
use Lemonldap::NG::Common::PSGI::Request;

9
our $VERSION = '1.9.0';
10 11 12 13 14 15 16 17 18

our $_json = JSON->new->allow_nonref;

has error        => ( is => 'rw', default => '' );
has languages    => ( is => 'rw', isa     => 'Str', default => 'en' );
has logLevel     => ( is => 'rw', isa     => 'Str' );
has staticPrefix => ( is => 'rw', isa     => 'Str' );
has templateDir  => ( is => 'rw', isa     => 'Str' );
has links        => ( is => 'rw', isa     => 'ArrayRef' );
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
has syslog => (
    is      => 'rw',
    isa     => 'Str',
    trigger => sub {
        if ( $_[0]->{syslog} ) {
            eval {
                require Sys::Syslog;
                Sys::Syslog->import(':standard');
                openlog( 'lemonldap-ng', 'ndelay,pid', $_[0]->{syslog} );
            };
            $_[0]
              ->error("Unable to use syslog with facility $_[0]->{syslog}: $@")
              if ($@);
        }
    },
);
35

36 37 38 39
## @method void lmLog(string mess, string level)
# Log subroutine. Print on STDERR messages if it exceeds `logLevel` value
# @param $mess Text to log
# @param $level Level (debug|info|notice|warn|error)
40 41 42 43 44 45 46 47 48 49 50 51 52 53
sub lmLog {
    my ( $self, $msg, $level ) = splice @_;
    my $levels = {
        error  => 4,
        warn   => 3,
        notice => 2,
        info   => 1,
        debug  => 0
    };
    my $l = $levels->{$level} || 1;
    return if ( ref($self) and $l < $levels->{ $self->{logLevel} } );
    print STDERR "[$level] " . ( $l ? '' : (caller)[0] . ': ' ) . " $msg\n";
}

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
##@method void userLog(string mess, string level)
# Log user actions on Apache logs or syslog.
# @param $mess string to log
# @param $level level of log message
sub userLog {
    my ( $self, $mess, $level ) = @_;
    if ( $self->{syslog} ) {
        $self->startSyslog();
        $level =~ s/^warn$/warning/;
        syslog( $level || 'notice', $mess );
    }
    else {
        $self->lmLog( $mess, $level );
    }
}

##@method void userInfo(string mess)
# Log non important user actions. Alias for userLog() with facility "info".
# @param $mess string to log
sub userInfo {
    my ( $self, $mess ) = @_;
    $self->userLog( $mess, 'info' );
}

##@method void userNotice(string mess)
# Log user actions like access and logout. Alias for userLog() with facility
# "notice".
# @param $mess string to log
sub userNotice {
    my ( $self, $mess ) = @_;
    $self->userLog( $mess, 'notice' );
}

##@method void userError(string mess)
# Log user errors like "bad password". Alias for userLog() with facility
# "warn".
# @param $mess string to log
sub userError {
    my ( $self, $mess ) = @_;
    $self->userLog( $mess, 'warn' );
}

96 97 98 99 100 101
# Responses methods
sub sendJSONresponse {
    my ( $self, $req, $j, %args ) = splice @_;
    $args{code} ||= 200;
    my $type = 'text/json';
    if ( ref $j ) {
Xavier Guimard's avatar
Xavier Guimard committed
102
        $j = $_json->encode($j);
103 104 105 106 107 108 109 110
    }
    return [ $args{code}, [ 'Content-Type', $type ], [$j] ];
}

sub sendError {
    my ( $self, $req, $err, $code ) = splice @_;
    $err  ||= $req->error;
    $code ||= 500;
111
    $self->lmLog( "Error $code: $err", $code > 499 ? 'error' : 'notice' );
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
    return $self->sendJSONresponse( $req, { error => $err }, code => $code );
}

sub abort {
    my ( $self, $err ) = splice @_;
    $self->lmLog( $err, 'error' );
    return sub {
        $self->sendError( Lemonldap::NG::Common::PSGI::Request->new( $_[0] ),
            $err, 500 );
    };
}

sub _mustBeDefined {
    my $name = ( caller(1) )[3];
    $name =~ s/^.*:://;
    my $call = ( caller(1) )[0];
    my $ref = ref( $_[0] ) || $call;
    die "$name() method must be implemented (probably in $ref)";
}

sub init { 1 }

sub router { _mustBeDefined(@_) }

sub sendHtml {
    my ( $self, $req, $template ) = splice @_;
    my $htpl;
Xavier Guimard's avatar
Xavier Guimard committed
139
    $template = $self->templateDir . "/$template.tpl";
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    return $self->sendError( $req, "Unable to read $template", 500 )
      unless ( -r $template and -f $template );
    eval {
        $self->lmLog( "Starting HTML generation using $template", 'debug' );
        require HTML::Template;
        $htpl = HTML::Template->new(
            filehandle             => IO::File->new($template),
            path                   => $self->templateDir,
            die_on_bad_params      => 1,
            die_on_missing_include => 1,
            cache                  => 0,
        );

        # TODO: replace app
        # TODO: warn if STATICPREFIX does not end with '/'
        my $sp = $self->staticPrefix;
        $sp =~ s/\/*$/\//;
        $htpl->param(
            SCRIPT_NAME         => $req->scriptname,
            STATIC_PREFIX       => $sp,
            AVAILABLE_LANGUAGES => $self->languages,
Xavier Guimard's avatar
Xavier Guimard committed
161 162
            LINKS   => $self->links ? encode_json( $self->links ) : '""',
            VERSION => $VERSION,
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
        );
    };
    if ($@) {
        return $self->sendError( $req, "Unable to load template: $@", 500 );
    }
    $self->lmLog(
        'For more performance, store the result of this as static file',
        'info' );

    # Set headers
    my $hdrs = [ 'Content-Type' => 'text/html' ];
    unless ( $self->logLevel eq 'debug' ) {
        push @$hdrs,
          ETag            => "LMNG-manager-$VERSION",
          'Cache-Control' => 'private, max-age=2592000';
    }
    $self->lmLog( "Sending $template", 'debug' );
    return [ 200, $hdrs, [ $htpl->output() ] ];
}

###############
# Main method #
###############

sub run {
    my ( $self, $args ) = splice @_;
    $self = $self->new($args) unless ref($self);
    return $self->abort( $self->error ) unless ( $self->init($args) );
    return $self->_run;
}

sub _run {
    my $self = shift;
    return sub {
        $self->router( Lemonldap::NG::Common::PSGI::Request->new( $_[0] ) );
    };
}

1;
Xavier Guimard's avatar
Xavier Guimard committed
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
__END__

=head1 NAME

=encoding utf8

Lemonldap::NG::Common::PSGI - Base library for PSGI modules of Lemonldap::NG.
Use Lemonldap::NG::Common::PSGI::Router for REST API.

=head1 SYNOPSIS

  package My::PSGI;
  
  use base Lemonldap::NG::Common::PSGI;
  
  sub init {
    my ($self,$args) = splice @_;
    # Will be called 1 time during startup
  
    # Store debug level
    $self->logLevel('info');
    # Can use syslog for user actions
    $self->syslog('daemon');
  
    # Return a boolean. If false, then error message has to be stored in
    # $self->error
    return 1;
  }
  
  sub router {
    my ( $self, $req ) = splice @_;
    # Do something and return a PSGI response
    # NB: $req is a Lemonldap::NG::Common::PSGI::Request object
    
    return [ 200, [ 'Content-Type' => 'text/plain' ], [ 'Body lines' ] ];
  }

This package could then be called as a CGI, using FastCGI,...

  #!/usr/bin/env perl
  
  use My::PSGI;
  use Plack::Handler::FCGI; # or Plack::Handler::CGI

  Plack::Handler::FCGI->new->run( My::PSGI->run() );

=head1 DESCRIPTION

This package provides base class for Lemonldap::NG web interfaces but could be
used regardless.

=head1 METHODS

=head2 Running methods

=head3 run ( $args )

Main method that will manage requests. It can be called using class or already
created object:

=over

=item Class->run($args): launch new($args), init(), then manage requests (using
private _run() method

=item $object->run(): manage directly requests. Initialization must have be done
earlier.

=back

=head2 Logging

=head3 lmLog ( $msg, $level)

Print on STDERR messages if level > $self->{logLevel}. Defined log levels are:
debug, info, notice, warn, error.

=head3 userLog ($msg, $level)

If $self->syslog is configured, store message with it, else called simply lmLog().
$self->syslog must be empty or contain syslog facility

=head3 userError() userNotice() userInfo()

Alias for userLog(level).

=head2 Content sending

Note that $req, the first argument of these functions, is a
L<Lemonldap::NG::Common::PSGI::Request>. See the corresponding documentation.

=head3 sendHtml ( $req, $template )

This method build HTML response using HTML::Template and the template $template.
$template file must be in $self->templateDir directory.
HTML template will receive 5 variables:

=over

=item SCRIPT_NAME: the path to the (F)CGI

=item STATIC_PREFIX: content of $self->staticPrefix

=item AVAILABLE_LANGUAGES: content of $self->languages

=item LINKS: JSON stringification of $self->links

=item VERSION: Lemonldap::NG version

=back

The response is always send with a 200 code.

=head3 sendJSONresponse ( $req, $json, %args )

Stringify $json object and send it to the client. $req is the
Lemonldap::NG::Common::PSGI::Request object; %args can define the HTTP error
code (200 by default).

If client is not json compatible (`Accept` header), response is send in XML.

Examples:

  $self->sendJSONresponse ( $req, { result => 0 }, code => 400 );

  $self->sendJSONresponse ( $req, { result => 1 } );

=head3 sendError ( $req, $msg, $code )

Call sendJSONresponse with `{ error => $msg }` and code (default to 500) and
call lmLog() to duplicate error in logs

=head3 abort ( $msg )

When an error is detected during startup (init() sub), you must not call
sendError() but call abort(). Each request received later will receive the
error (abort uses sendError() behind the scene).

=head2 Accessors

=head3 error

String error. Used if init() fails or if sendError is called without argument.

=head3 languages

String containing list of languages (ie "fr, en'). Used by sendHtml().

=head3 logLevel

See lmLog().

=head3 staticPrefix

String indicating the path of static content (js, css,...). Used by sendHtml().

=head3 templateDir

Directory containing template files.

=head3 links

Array of links to display by sendHtml(). Each element has the form:

 { target => 'http://target', title => 'string to display' }

=head3 syslog

Syslog facility. If empty, STDERR will be used for logging

=head1 SEE ALSO

L<http://lemonldap-ng.org/>, L<Lemonldap::NG::Portal>, L<Lemonldap::NG::Handler>,
L<Plack>, L<PSGI>, L<Lemonldap::NG::Common::PSGI::Router>,
Xavier Guimard's avatar
Xavier Guimard committed
376
L<Lemonldap::NG::Common::PSGI::Request>, L<HTML::Template>, 
Xavier Guimard's avatar
Xavier Guimard committed
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

=head1 AUTHORS

=over

=item Clement Oudot, E<lt>clem.oudot@gmail.comE<gt>

=item François-Xavier Deltombe, E<lt>fxdeltombe@gmail.com.E<gt>

=item Xavier Guimard, E<lt>x.guimard@free.frE<gt>

=item Thomas Chemineau, E<lt>thomas.chemineau@gmail.comE<gt>

=back

=head1 BUG REPORT

Use OW2 system to report bug or ask for features:
L<http://jira.ow2.org>

=head1 DOWNLOAD

Lemonldap::NG is available at
L<http://forge.objectweb.org/project/showfiles.php?group_id=274>

=head1 COPYRIGHT AND LICENSE

=over

=item Copyright (C) 2015 by Xavier Guimard, E<lt>x.guimard@free.frE<gt>

408 409
=item Copyright (C) 2015 by Clément Oudot, E<lt>clem.oudot@gmail.comE<gt>

Xavier Guimard's avatar
Xavier Guimard committed
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
=back

This library is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see L<http://www.gnu.org/licenses/>.

=cut