Simple.pm 23.6 KB
Newer Older
1 2 3 4 5 6
package Lemonldap::NG::Handler::Simple;

use strict;

use MIME::Base64;
use Exporter 'import';
Xavier Guimard's avatar
Xavier Guimard committed
7
use Safe;
8
require POSIX;
9

10
our $VERSION = '0.84';
11 12

our %EXPORT_TAGS = (
13 14 15
    localStorage =>
      [ qw( $localStorage $localStorageOptions $refLocalStorage ) ],
    globalStorage => [ qw( $globalStorage $globalStorageOptions ) ],
16 17 18
    locationRules => [
        qw(
          $locationCondition $defaultCondition $locationCount
Xavier Guimard's avatar
Xavier Guimard committed
19
          $locationRegexp $apacheRequest $datas $safe $portal
20
          $logout
21 22
          )
    ],
23
    import  => [ qw( import @EXPORT_OK @EXPORT %EXPORT_TAGS ) ],
24 25
    headers => [
        qw(
26 27 28
          $forgeHeaders lmHeaderIn lmSetHeaderIn lmHeaderOut
          lmSetHeaderOut lmSetErrHeaderOut $cookieName $cookieSecured
          $https $port
29 30
          )
    ],
31 32
    traces => [ qw( $whatToTrace ) ],
    apache =>
Xavier Guimard's avatar
Xavier Guimard committed
33
      [ qw( MP OK REDIRECT FORBIDDEN DONE DECLINED SERVER_ERROR ) ],
34 35 36
);

our @EXPORT_OK = ();
37 38
push( @EXPORT_OK, @{ $EXPORT_TAGS{$_} } )
  foreach (
39
    qw( localStorage globalStorage locationRules import headers traces apache )
40
  );
41 42 43 44 45 46
$EXPORT_TAGS{all} = \@EXPORT_OK;

our @EXPORT = ();

# Shared variables
our (
47 48 49 50 51
    $locationRegexp,      $locationCondition,    $defaultCondition,
    $forgeHeaders,        $apacheRequest,        $locationCount,
    $cookieName,          $portal,               $datas,
    $globalStorage,       $globalStorageOptions, $localStorage,
    $localStorageOptions, $whatToTrace,          $https,
Xavier Guimard's avatar
Xavier Guimard committed
52
    $refLocalStorage,     $safe,                 $cookieSecured,
53
    $logout,              $port
54 55 56 57 58 59 60 61
);

##########################################
# COMPATIBILITY WITH APACHE AND APACHE 2 #
##########################################

BEGIN {
    if ( exists $ENV{MOD_PERL} ) {
62
        if ( $ENV{MOD_PERL_API_VERSION} and $ENV{MOD_PERL_API_VERSION} >= 2 ) {
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
            *MP = sub { 2 };
        }
        else {
            *MP = sub { 1 };
        }
    }
    else {
        *MP = sub { 0 };
    }
    if ( MP() == 2 ) {
        require Apache2::RequestRec;
        Apache2::RequestRec->import();
        require Apache2::Log;
        require Apache2::Const;
        Apache2::Const->import( '-compile', qw(:common :log) );
        *FORBIDDEN    = \&Apache2::Const::FORBIDDEN;
        *REDIRECT     = \&Apache2::Const::REDIRECT;
        *OK           = \&Apache2::Const::OK;
        *DECLINED     = \&Apache2::Const::DECLINED;
        *DONE         = \&Apache2::Const::DONE;
        *SERVER_ERROR = \&Apache2::Const::SERVER_ERROR;
        require Apache2::compat;
        Apache2::compat->import();
        eval {
            require threads::shared;
            threads::shared::share($locationRegexp);
            threads::shared::share($locationCondition);
            threads::shared::share($defaultCondition);
            threads::shared::share($forgeHeaders);
            threads::shared::share($locationCount);
            threads::shared::share($cookieName);
            threads::shared::share($portal);
            threads::shared::share($globalStorage);
            threads::shared::share($globalStorageOptions);
            threads::shared::share($localStorage);
            threads::shared::share($localStorageOptions);
            threads::shared::share($whatToTrace);
            threads::shared::share($https);
101
            threads::shared::share($port);
102 103 104 105 106 107 108 109 110 111
            threads::shared::share($refLocalStorage);
        };
    }
    elsif ( MP() == 1 ) {
        require Apache;
        require Apache::Log;
        require Apache::Constants;
        Apache::Constants->import(':common');
        Apache::Constants->import(':response');
    }
Xavier Guimard's avatar
Xavier Guimard committed
112
    else {    # For Test or CGI
113
        eval '
Xavier Guimard's avatar
Xavier Guimard committed
114
            sub OK {0}
115
            sub FORBIDDEN {1}
Xavier Guimard's avatar
Xavier Guimard committed
116
            sub REDIRECT {2}
117
            sub DECLINED {1}
Xavier Guimard's avatar
Xavier Guimard committed
118 119
            sub DONE {4}
            sub SERVER_ERROR {5}
120 121 122
        ';
    }
    *handler = ( MP() == 2 ) ? \&handler_mp2 : \&handler_mp1;
123
    *logout = ( MP() == 2 ) ? \&logout_mp2 : \&logout_mp1;
124 125 126
}

sub handler_mp1 ($$) { shift->run(@_) }
127
sub handler_mp2 : method { shift->run(@_); }
128

129 130
sub logout_mp1 ($$) { shift->unlog(@_) }
sub logout_mp2 : method { shift->unlog(@_); }
131

Xavier Guimard's avatar
Xavier Guimard committed
132
sub lmLog {
133 134 135 136
    my ( $class, $mess, $level ) = @_;
    if ( MP() == 2 ) {
        Apache2::ServerRec->log->$level($mess);
    }
Xavier Guimard's avatar
Xavier Guimard committed
137
    elsif ( MP() == 1 ) {
138 139
        Apache->server->log->$level($mess);
    }
Xavier Guimard's avatar
Xavier Guimard committed
140 141 142
    else {
        print STDERR "$mess\n";
    }
143 144 145 146 147 148 149 150 151 152 153 154 155
}

sub regRemoteIp {
    my ( $class, $str ) = @_;
    $str =~ s/\$datas->\{ip\}/\$apacheRequest->connection->remote_ip/g;
    return $str;
}

sub lmSetHeaderIn {
    my ( $r, $h, $v ) = @_;
    if ( MP() == 2 ) {
        return $r->headers_in->set( $h => $v );
    }
Xavier Guimard's avatar
Xavier Guimard committed
156
    elsif ( MP() == 1 ) {
157 158 159 160 161 162 163 164 165
        return $r->header_in( $h => $v );
    }
}

sub lmHeaderIn {
    my ( $r, $h, $v ) = @_;
    if ( MP() == 2 ) {
        return $r->headers_in->{$h};
    }
Xavier Guimard's avatar
Xavier Guimard committed
166
    elsif ( MP() == 1 ) {
167 168 169 170 171 172 173 174 175
        return $r->header_in($h);
    }
}

sub lmSetErrHeaderOut {
    my ( $r, $h, $v ) = @_;
    if ( MP() == 2 ) {
        return $r->err_headers_out->set( $h => $v );
    }
Xavier Guimard's avatar
Xavier Guimard committed
176
    elsif ( MP() == 1 ) {
177
        return $r->err_header_out( $h => $v );
178 179 180 181 182 183 184 185
    }
}

sub lmSetHeaderOut {
    my ( $r, $h, $v ) = @_;
    if ( MP() == 2 ) {
        return $r->headers_out->set( $h => $v );
    }
Xavier Guimard's avatar
Xavier Guimard committed
186
    elsif ( MP() == 1 ) {
187 188 189 190 191 192 193 194 195
        return $r->header_out( $h => $v );
    }
}

sub lmHeaderOut {
    my ( $r, $h, $v ) = @_;
    if ( MP() == 2 ) {
        return $r->headers_out->{$h};
    }
Xavier Guimard's avatar
Xavier Guimard committed
196
    elsif ( MP() == 1 ) {
197 198 199 200 201 202 203 204
        return $r->header_out($h);
    }
}

##############################
# Initialization subroutines #
##############################

Xavier Guimard's avatar
Xavier Guimard committed
205 206
# Security jail
$safe = new Safe;
207
$safe->share( '&encode_base64', '$datas', '&lmSetHeaderIn', '$apacheRequest' );
Xavier Guimard's avatar
Xavier Guimard committed
208

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
# init() : by default, it calls localInit and globalInit, but with
#          a shared configuration, init() is overloaded to call only
#          localInit; globalInit is called later when the configuration
#          is loaded.
sub init($$) {
    my $class = shift;
    $class->localInit(@_);
    $class->globalInit(@_);
}

# Local storage initialization
sub localInit($$) {
    my ( $class, $args ) = @_;
    if ( $localStorage = $args->{localStorage} ) {
        $localStorageOptions = $args->{localStorageOptions};
        $localStorageOptions->{namespace}          ||= "lemonldap";
        $localStorageOptions->{default_expires_in} ||= 600;

        eval "use $localStorage;";
228
        die("Unable to load $localStorage: $@") if ($@);
229 230 231

        # At each Apache (re)start, we've to clear the cache to avoid living
        # with old datas
232 233 234
        eval '$refLocalStorage = new '
          . $localStorage
          . '($localStorageOptions);';
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
        if ( defined $refLocalStorage ) {
            $refLocalStorage->clear();
        }
        else {
            $class->lmLog( "Unable to clear local cache: $@", 'error' );
        }
    }

    # We don't initialise local storage in the "init" subroutine because it can
    # be used at the starting of Apache and so with the "root" privileges. Local
    # Storage is also initialized just after Apache's fork and privilege lost.

    # Local storage is cleaned after giving the content of the page to increase
    # performances.
    no strict;
    if ( MP() == 2 ) {
251 252 253
        Apache->push_handlers(
            PerlChildInitHandler => sub { return $class->initLocalStorage( $_[1], $_[0] ); }
        );
254 255 256
        Apache->push_handlers(
            PerlCleanupHandler => sub { return $class->cleanLocalStorage(@_); }
        );
257
    }
Xavier Guimard's avatar
Xavier Guimard committed
258
    elsif ( MP() == 1 ) {
259 260 261 262 263 264
        Apache->push_handlers(
            PerlChildInitHandler => sub { return $class->initLocalStorage(@_); }
        );
        Apache->push_handlers(
            PerlCleanupHandler => sub { return $class->cleanLocalStorage(@_); }
        );
265
    }
266
    1;
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
}

# Global initialization process :
sub globalInit {
    my $class = shift;
    $class->locationRulesInit(@_);
    $class->defaultValuesInit(@_);
    $class->portalInit(@_);
    $class->globalStorageInit(@_);
    $class->forgeHeadersInit(@_);
}

# locationRulesInit : used to pre-compile rules :
#   - rules are stored in a hash containing regexp=>test expressions where :
#       - regexp is used to test URIs
#       - test contains an expression used to grant the user

284
# TODO: split locationRules into 2 arrays
285 286 287 288 289 290 291
sub locationRulesInit {
    my ( $class, $args ) = @_;
    $locationCount = 0;

    # Pre compilation : both regexp and conditions
    foreach ( keys %{ $args->{locationRules} } ) {
        if ( $_ eq 'default' ) {
292 293
            $defaultCondition =
              $class->conditionSub( $args->{locationRules}->{$_} );
294 295
        }
        else {
296 297 298
            $locationCondition->[$locationCount] =
              $class->conditionSub( $args->{locationRules}->{$_} );
            $locationRegexp->[$locationCount] = qr/$_/;
299 300 301 302 303 304 305
            $locationCount++;
        }
    }

    # Default police: all authenticated users are accepted
    $defaultCondition = $class->conditionSub('accept')
      unless ($defaultCondition);
306
    1;
307 308 309 310 311 312 313 314 315 316
}

# conditionSub returns a pre-compiled subroutine used to grant users (used by
# locationRulesInit().
sub conditionSub {
    my ( $class, $cond ) = @_;
    return sub { 1 }
      if ( $cond =~ /^accept$/i );
    return sub { 0 }
      if ( $cond =~ /^deny$/i );
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
    if ( $cond =~ /^logout(?:_sso)?(?:\s+(.*))?$/i ) {
        my $url = $1 || $class->encodeUrl ( "/" );
        return sub { $logout = $url; return 0 }
    }
    if( MP() == 2 ) {
        if ( $cond =~ /^logout_app(?:\s+(.*))?$/i ) {
            my $u = $1;
            eval 'use Apache2::Filter' unless($INC{"Apache2/Filter.pm"});
            return sub {
                $apacheRequest->add_output_filter(sub {
                        return $class->redirectFilter( $u, @_ );
                    }
                );
                1;
            };
        }
        elsif ( $cond =~ /^logout_app_sso(?:\s+(.*))?$/i ) {
            eval 'use Apache2::Filter' unless($INC{"Apache2/Filter.pm"});
            my $u = encode_base64($1);
            $u =~ s/[\r\n]//g;
            return sub {
                $class->localUnlog;
                $apacheRequest->add_output_filter(sub {
                        return $class->redirectFilter( "$portal?url=$u&logout=1", @_ );
                    }
                );
                1;
            };
        }
    }
347
    $cond =~ s/\$date/&POSIX::strftime("%Y%m%d%H%M%S",localtime())/e;
348 349
    $cond =~ s/\$(\w+)/\$datas->{$1}/g;
    my $sub;
Xavier Guimard's avatar
Xavier Guimard committed
350
    $sub = $safe->reval("sub {return ( $cond )}");
351 352 353 354 355 356 357 358
    return $sub;
}

# defaultValuesInit : set default values for non-customized variables
sub defaultValuesInit {
    my ( $class, $args ) = @_;

    # Other values
359 360 361
    $cookieName    = $args->{cookieName}    || 'lemonldap';
    $cookieSecured = $args->{cookieSecured} || 0;
    $whatToTrace   = $args->{whatToTrace}   || '$uid';
362
    $whatToTrace =~ s/\$//g;
363 364
    $https = $args->{https} || 1 unless defined($https);
    $port = $args->{port} || 0 unless defined($port);
365
    1;
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
}

# portalInit : verify that portal variable exists
sub portalInit {
    my ( $class, $args ) = @_;
    $portal = $args->{portal} or die("portal parameter required");
}

# globalStorageInit : initialize the Apache::Session::* package used to
# share user's variables
sub globalStorageInit {
    my ( $class, $args ) = @_;
    $globalStorage = $args->{globalStorage} or die "globalStorage required";
    eval "use $globalStorage;";
    die($@) if ($@);
    $globalStorageOptions = $args->{globalStorageOptions};
}

# forgeHeadersInit : create the &$forgeHeaders subroutine used to insert
# headers into the HTTP request (which are used for accounting by the
# application)
sub forgeHeadersInit {
    my ( $class, $args ) = @_;

    # Creation of the subroutine who will generate headers
    my %tmp;
    if ( $args->{exportedHeaders} ) {
        %tmp = %{ $args->{exportedHeaders} };
    }
    else {
        %tmp = ( 'User-Auth' => '$uid' );
    }
    foreach ( keys %tmp ) {
        $tmp{$_} =~ s/\$(\w+)/\$datas->{$1}/g;
        $tmp{$_} = $class->regRemoteIp( $tmp{$_} );
    }

    my $sub;
    foreach ( keys %tmp ) {
405 406 407
        $sub .=
          "lmSetHeaderIn(\$apacheRequest,'$_' => join('',split(/[\\r\\n]+/,"
          . $tmp{$_} . ")));";
408
    }
409

Xavier Guimard's avatar
Xavier Guimard committed
410 411 412
    #$sub = "\$forgeHeaders = sub {$sub};";
    #eval "$sub";
    $forgeHeaders = $safe->reval("sub {$sub};");
413 414
    $class->lmLog( "$class: Unable to forge headers: $@: sub {$sub}", 'error' )
      if ($@);
415
    1;
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
}

################
# MAIN PROCESS #
################

# grant : grant or refuse client
sub grant {
    my ( $class, $uri ) = @_;
    for ( my $i = 0 ; $i < $locationCount ; $i++ ) {
        return &{ $locationCondition->[$i] }($datas)
          if ( $uri =~ $locationRegexp->[$i] );
    }
    return &$defaultCondition;
}

# forbidden : used to reject non authorizated requests
sub forbidden {
    my $class = shift;
435 436 437 438 439 440
    if( $logout ) {
        $apacheRequest->headers_out->set(
                'Location' => "$portal?url=$logout"
        );
        return REDIRECT;
    }
441 442 443 444
    $class->lmLog(
        'The user "' . $datas->{$whatToTrace} . '" was reject when he tried to access to ' . shift,
        'notice'
    );
445 446 447
    return FORBIDDEN;
}

448
# hideCookie : hide Lemonldap::NG cookie to the protected application
449
sub hideCookie {
450 451
    my $class = shift;
    $class->lmLog( "$class: removing cookie", 'debug' );
452 453 454 455 456
    my $tmp = lmHeaderIn( $apacheRequest, 'Cookie' );
    $tmp =~ s/$cookieName[^;]*;?//o;
    lmSetHeaderIn( $apacheRequest, 'Cookie' => $tmp );
}

457 458
sub encodeUrl {
    my ( $class, $url ) = @_;
459 460
    my $portString = $port || $apacheRequest->get_server_port();
    $portString =
461 462
        (  $https && $port == 443 ) ? ''
      : ( !$https && $port == 80 )  ? ''
463
      :                               ':' . $portString;
464
    my $u =
465 466 467
      encode_base64( "http"
          . ( $https ? "s" : "" ) . "://"
          . $apacheRequest->get_server_name()
468
          . $portString
469
          . $url );
470 471 472 473 474 475 476
    $u =~ s/[\r\n\s]//sg;
    return $u;
}

# Redirect non-authenticated users to the portal
sub goToPortal() {
    my ( $class, $url, $arg ) = @_;
477 478 479 480 481 482
    $class->lmLog(
        "Redirect "
          . $apacheRequest->connection->remote_ip
          . " to portal (url was $url)",
        'debug'
    );
483
    my $urlc_init = $class->encodeUrl ( $url );
Xavier Guimard's avatar
Xavier Guimard committed
484 485 486
    $apacheRequest->headers_out->set(
        'Location' => "$portal?url=$urlc_init" . ( $arg ? "&$arg" : "" )
    );
487 488 489
    return REDIRECT;
}

490 491 492 493 494 495
# Fetch $id
sub fetchId() {
    my $t = lmHeaderIn( $apacheRequest, 'Cookie' );
    return ($t =~ /$cookieName=([^; ]+);?/o ) ? $1: 0;
}

496
# MAIN SUBROUTINE called by Apache (using PerlHeaderParserHandler option)
497 498 499 500
sub run ($$) {
    my $class;
    ( $class, $apacheRequest ) = @_;

501 502
    return DECLINED unless ( $apacheRequest->is_initial_req );
    my $uri = $apacheRequest->uri . ( $apacheRequest->args ? "?" . $apacheRequest->args : "" );
503 504 505 506

    # AUTHENTICATION
    # I - recover the cookie
    my $id;
507
    unless ( $id = $class->fetchId ) {
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
        $class->lmLog( "$class: No cookie found", 'info' );
        return $class->goToPortal($uri);
    }

    # II - recover the user datas
    #  2.1 search if the user was the same as previous (very efficient in
    #      persistent connection).
    unless ( $id eq $datas->{_session_id} ) {

        # 2.2 search in the local cache if exists
        unless ( $refLocalStorage and $datas = $refLocalStorage->get($id) ) {

            # 2.3 search in the central cache
            my %h;
            eval { tie %h, $globalStorage, $id, $globalStorageOptions; };
            if ($@) {

                # The cookie isn't yet available
526 527
                $class->lmLog( "The cookie $id isn't yet available: $@",
                    'info' );
528 529 530 531 532 533 534 535 536 537 538 539 540 541
                return $class->goToPortal($uri);
            }
            $datas->{$_} = $h{$_} foreach ( keys %h );

            # Store now the user in the local storage
            if ($refLocalStorage) {
                $refLocalStorage->set( $id, $datas, "10 minutes" );
            }
            untie %h;
        }
    }

    # ACCOUNTING
    # 1 - Inform Apache
542
    $apacheRequest->connection->user( $datas->{$whatToTrace} ) if( $datas->{$whatToTrace} );
543 544 545

    # AUTHORIZATION
    return $class->forbidden($uri) unless ( $class->grant($uri) );
546 547 548 549 550 551
    $class->lmLog(
        "User "
          . $datas->{$whatToTrace}
          . " was authorizated to access to $uri",
        'debug'
    );
552 553 554 555 556 557

    # ACCOUNTING
    # 2 - Inform remote application
    $class->sendHeaders;

    # SECURITY
558
    # Hide Lemonldap::NG cookie
559
    $class->hideCookie;
560 561 562 563 564 565 566 567 568 569
    OK;
}

sub sendHeaders {
    &$forgeHeaders;
}

sub initLocalStorage {
    my ( $class, $r ) = @_;
    if ( $localStorage and not $refLocalStorage ) {
570 571 572
        eval '$refLocalStorage = new '
          . $localStorage
          . '($localStorageOptions);';
573 574 575 576 577 578 579 580 581 582 583
    }
    $class->lmLog( "Local cache initialization failed: $@", 'error' )
      unless ( defined $refLocalStorage );
    return DECLINED;
}

sub cleanLocalStorage {
    $refLocalStorage->purge() if ($refLocalStorage);
    return DECLINED;
}

Xavier Guimard's avatar
Xavier Guimard committed
584
sub unprotect {
Xavier Guimard's avatar
Xavier Guimard committed
585
    OK;
586 587
}

588 589
sub localUnlog {
    my $class = shift;
590 591 592 593 594 595 596 597 598 599
    if( my $id = $class->fetchId ) {
        # Delete Apache thread datas
        if ( $id eq $datas->{_session_id} ) {
            $datas = {};
        }
        # Delete Apache local cache
        if( $refLocalStorage and $refLocalStorage->get($id) ) {
            $refLocalStorage->remove($id);
        }
    }
600 601 602 603 604 605 606
}

sub unlog ($$) {
    my $class;
    $logout = 0;
    ($class, $apacheRequest ) = @_;
    $class->localUnlog;
607
    return $class->goToPortal( '/', 'logout=1' );
Xavier Guimard's avatar
Xavier Guimard committed
608 609
}

610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
sub redirectFilter {
    my $class = shift;
    my $url   = shift;
    my $f     = shift;
    unless ($f->ctx) {
        $f->r->status(REDIRECT);
        $f->r->status_line("302 Temporary Moved");
        $f->r->err_headers_out->set('Location' => $url);
        $f->ctx(1);
    }
    while ($f->read(my $buffer, 1024)) {
    }
    return REDIRECT;
}

625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
1;
__END__

=head1 NAME

Lemonldap::NG::Handler::Simple - Perl base extension for building Lemonldap::NG
compatible handler.

=head1 SYNOPSIS

Create your own package:

  package My::Package;
  use Lemonldap::NG::Handler::Simple;

  our @ISA = qw(Lemonldap::NG::Handler::Simple);

642
  __PACKAGE__->init ({
643
         locationRules        => {
644
               default          => '$ou =~ /brh/'
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
         globalStorage        => 'Apache::Session::MySQL',
         globalStorageOptions => {
               DataSource       => 'dbi:mysql:database=dbname;host=127.0.0.1',
               UserName         => 'db_user',
               Password         => 'db_password',
               TableName        => 'sessions',
               LockDataSource   => 'dbi:mysql:database=dbname;host=127.0.0.1',
               LockUserName     => 'db_user',
               LockPassword     => 'db_password',
           },
         localStorage         => 'Cache::DBFile',
         localStorageOptions  => {},
         portal               => 'https://portal/',
       });

More complete example

  package My::Package;
  use Lemonldap::NG::Handler::Simple;

  our @ISA = qw(Lemonldap::NG::Handler::Simple);

  __PACKAGE__->init ( { locationRules => {
             '^/pj/.*$'       => q($qualif="opj"),
             '^/rh/.*$'       => q($ou=~/brh/),
             '^/rh_or_opj.*$' => q($qualif="opj or $ou=~/brh/),
             default => 'accept', # means that all authenticated users are greanted
           },
           globalStorage        => 'Apache::Session::MySQL',
           globalStorageOptions => {
               DataSource       => 'dbi:mysql:database=dbname;host=127.0.0.1',
               UserName         => 'db_user',
               Password         => 'db_password',
               TableName        => 'sessions',
               LockDataSource   => 'dbi:mysql:database=dbname;host=127.0.0.1',
               LockUserName     => 'db_user',
               LockPassword     => 'db_password',
           },
           localStorage         => 'Cache::DBFile',
           localStorageOptions  => {},
           cookieName           => 'lemon',
           portal               => 'https://portal/',
           whatToTrace          => '$uid',
           exportedHeaders      => {
               'Auth-User'      => '$uid',
               'Unit'           => '$ou',
           https                => 1,
         }
       );

Call your package in <apache-directory>/conf/httpd.conf

  PerlRequire MyFile
  # TOTAL PROTECTION
700
  PerlHeaderParserHandler My::Package
701 702
  # OR SELECTED AREA
  <Location /protected-area>
703
    PerlHeaderParserHandler My::Package
704
  </Location>
Xavier Guimard's avatar
Xavier Guimard committed
705
  
Xavier Guimard's avatar
Xavier Guimard committed
706 707
You can also unprotect an URI

Xavier Guimard's avatar
Xavier Guimard committed
708 709 710
  <Files "*.gif">
    PerlHeaderParserHandler My::Package->unprotect
  </Files>
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

=head1 DESCRIPTION

Lemonldap::NG::Handler::Simple is designed to be overloaded. See
L<Lemonldap::NG::Handler> for more.

=head2 INITIALISATION PARAMETERS

This section presents the C<init> method parameters.

=over

=item B<locationRules> (required)

Reference to a hash that contains "url-regexp => perl-expression" entries to
manage authorizations.

=over

=item * "url-regexp" can be a perl regexp or the keyword 'default' which
corresponds to the default police (accept by default).

=item * "perl-expression" can be a perl condition or the keyword "accept" or the
keyword "deny". All the variables announced by $<name of the variable> are
replaced by the values resulting from the global session store.

=back

=item B<globalStorage> E<amp> B<globalStorageOptions> (required)

Name and parameters of the Apache::Session::* module used by the portal to
store user's datas. See L<Lemonldap::NG::Portal(3)> for more explanations.

=item B<localStorage> E<amp> B<localStorageOptions>

Name and parameters of the optional but recommanded Cache::* module used to
share user's datas between Apache processes. There is no need to set expires
options since L<Lemonldap::NG::Handler::Simple> call the Cache::*::purge
method itself.

=item B<cookieName> (default: lemon)

753
Name of the cookie used by the Lemonldap::NG infrastructure.
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774

=item B<portal> (required)

Url of the portal used to authenticate users.

=item B<whatToTrace> (default: uid)

Stored user variable to use in Apache logs.

=item B<exportedHeaders>

Reference to a hash that contains "Name => value" entries. Those headers are
calculated for each user by replacing the variables announced by "$" by their
values resulting from the global session store.

=item B<https> (default: 1)

Indicates if the protected server is protected by SSL. It is used to build
redirections, so you have to set it to avoid bad redirections after
authentication.

775 776 777 778
=item B<port> (default: undef)

If port is not well defined in redirection, you can fix listen port here.

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
=back

=head2 EXPORT

None by default. You can import the following tags for inheritance:

=over

=item * B<:localStorage> : variables used to manage local storage

=item * B<:globalStorage> : variables used to manage global storage

=item * B<:locationRules> : variables used to manage area protection

=item * B<:import> : import function inherited from L<Exporter> and related
variables

=item * B<:headers> : functions and variables used to manage custom HTTP
headers exported to the applications

=item * B<apache> : functions and variables used to dialog with mod_perl.
This is done to be compatible both with Apache 1 and 2.

=back

=head1 SEE ALSO

806 807
L<Lemonldap::NG::Handler>, L<Lemonldap::NG::Portal>,
http://wiki.lemonldap.objectweb.org/xwiki/bin/view/NG/Presentation
808 809 810 811 812

=head1 AUTHOR

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

Xavier Guimard's avatar
Xavier Guimard committed
813 814 815 816 817 818 819 820 821 822
=head1 BUG REPORT

Use OW2 system to report bug or ask for features:
L<http://forge.objectweb.org/tracker/?group_id=274>

=head1 DOWNLOAD

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

823 824
=head1 COPYRIGHT AND LICENSE

825
Copyright (C) 2005-2007 by Xavier Guimard E<lt>x.guimard@free.frE<gt>
826 827 828 829 830 831

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.4 or,
at your option, any later version of Perl 5 you may have available.

=cut