Display.pm 15.3 KB
Newer Older
Yadd's avatar
Yadd committed
1 2 3 4 5 6 7 8 9
## @file
# Display functions for LemonLDAP::NG Portal
package Lemonldap::NG::Portal::Main::Display;

our $VERSION = '2.0.0';

package Lemonldap::NG::Portal::Main;
use strict;

Yadd's avatar
Yadd committed
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
has skinRules => ( is => 'rw' );

sub displayInit {
    my ($self) = @_;
    $self->skinRules( [] );
    if ( $self->conf->{portalSkinRules} ) {
        foreach my $skinRule ( sort keys %{ $self->conf->{portalSkinRules} } ) {
            my $sub = HANDLER->buildSub( HANDLER->substitute($skinRule) );
            if ($sub) {
                push @{ $self->skinRules },
                  [ $self->conf->{portalSkinRules}->{$skinRule}, $sub ];
            }
            else {
                $self->lmLog(
                    qq(Skin rule "$skinRule" returns an error: )
                      . HANDLER->tsv->{jail}->error,
                    'error'
                );
            }
        }
    }
}

Yadd's avatar
Yadd committed
33 34 35 36 37 38
# Call portal process and set template parameters
# @return template name and template parameters
sub display {
    my ( $self, $req ) = @_;

    my $skin_dir = $self->conf->{templatesDir};
Yadd's avatar
Yadd committed
39
    my ( $skinfile, %templateParams );
Yadd's avatar
Yadd committed
40 41 42 43 44 45 46

    # 0. Display error page
    if ( my $http_error = $req->param('lmError') ) {

        $skinfile = 'error';

        # Check URL
Yadd's avatar
Yadd committed
47
        $self->controlUrl($req);
Yadd's avatar
Yadd committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61

        %templateParams = (
            PORTAL_URL => $self->conf->{portal},
            LOGOUT_URL => $self->conf->{portal} . "?logout=1",
            URL        => $req->{urldc},
        );

        # Error code
        foreach ( 403, 500, 503 ) {
            $templateParams{"ERROR$_"} = ( $http_error == $_ ? 1 : 0 );
        }

    }

Yadd's avatar
Yadd committed
62
    # 1. Authentication not complete
Yadd's avatar
Yadd committed
63

Yadd's avatar
Yadd committed
64
    # 1.1 A notification has to be done (session is created but hidden and
Yadd's avatar
Yadd committed
65
    #     unusable until the user has accept the message)
Yadd's avatar
Yadd committed
66
    if ( my $notif = $req->datas->{notification} ) {
Yadd's avatar
Yadd committed
67 68 69 70
        $skinfile       = 'notification';
        %templateParams = (
            AUTH_ERROR_TYPE => $req->error_type,
            NOTIFICATION    => $notif,
Yadd's avatar
Yadd committed
71
            HIDDEN_INPUTS   => $self->buildHiddenForm($req),
Yadd's avatar
Yadd committed
72
            AUTH_URL        => $req->{datas}->{_url},
Yadd's avatar
Yadd committed
73
            CHOICE_PARAM    => $self->conf->{authChoiceParam},
Yadd's avatar
Yadd committed
74
            CHOICE_VALUE    => $req->datas->{_authChoice},
Yadd's avatar
Yadd committed
75 76 77
        );
    }

Yadd's avatar
Yadd committed
78
    # 1.2 An authentication (or userDB) module needs to ask a question
Yadd's avatar
Yadd committed
79 80 81 82 83 84
    #     before processing to the request
    elsif ( $req->{error} == PE_CONFIRM ) {
        $skinfile       = 'confirm';
        %templateParams = (
            AUTH_ERROR      => $req->error,
            AUTH_ERROR_TYPE => $req->error_type,
Yadd's avatar
Yadd committed
85
            AUTH_URL        => $req->{datas}->{_url},
Yadd's avatar
Yadd committed
86
            MSG             => $req->info,
Yadd's avatar
Yadd committed
87
            HIDDEN_INPUTS   => $self->buildHiddenForm($req),
Yadd's avatar
Yadd committed
88
            ACTIVE_TIMER    => $req->datas->{activeTimer},
Yadd's avatar
Yadd committed
89 90
            FORM_METHOD     => $self->conf->{confirmFormMethod},
            CHOICE_PARAM    => $self->conf->{authChoiceParam},
Yadd's avatar
Yadd committed
91
            CHOICE_VALUE    => $req->datas->{_authChoice},
Yadd's avatar
Yadd committed
92
            CHECK_LOGINS    => $self->conf->{portalCheckLogins}
Yadd's avatar
Yadd committed
93 94
              && $req->datas->{login},
            ASK_LOGINS => $req->datas->{checkLogins},
Yadd's avatar
Yadd committed
95 96
            CONFIRMKEY => $self->stamp(),
            LIST       => $req->datas->{list} || [],
Yadd's avatar
Yadd committed
97
            REMEMBER   => $req->datas->{confirmRemember},
Yadd's avatar
Yadd committed
98 99 100
        );
    }

Yadd's avatar
Yadd committed
101 102
    # 1.3 There is a message to display
    elsif ( my $info = $req->info ) {
Yadd's avatar
Yadd committed
103 104 105 106 107 108
        $skinfile       = 'info';
        %templateParams = (
            AUTH_ERROR      => $self->error,
            AUTH_ERROR_TYPE => $req->error_type,
            MSG             => $info,
            URL             => $req->{urldc},
Yadd's avatar
Yadd committed
109
            HIDDEN_INPUTS   => $self->buildHiddenForm($req),
Yadd's avatar
Yadd committed
110
            ACTIVE_TIMER    => $req->datas->{activeTimer},
Yadd's avatar
Yadd committed
111 112
            FORM_METHOD     => $self->conf->{infoFormMethod},
            CHOICE_PARAM    => $self->conf->{authChoiceParam},
Yadd's avatar
Yadd committed
113
            CHOICE_VALUE    => $req->datas->{_authChoice},
Yadd's avatar
Yadd committed
114 115 116
        );
    }

Yadd's avatar
Yadd committed
117
    # 1.4 OpenID menu page
Yadd's avatar
Yadd committed
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
    elsif ($req->{error} == PE_OPENID_EMPTY
        or $req->{error} == PE_OPENID_BADID )
    {
        $skinfile = 'openid';
        my $p = $self->{portal} . $self->{issuerDBOpenIDPath};
        $p =~ s#(?<!:)/\^?/#/#g;
        %templateParams = (
            AUTH_ERROR      => $self->error,
            AUTH_ERROR_TYPE => $req->error_type,
            PROVIDERURI     => $p,
            ID              => $self->{_openidPortal}
              . $req->{sessionInfo}
              ->{ $self->conf->{openIdAttr} || $self->conf->{whatToTrace} },
            PORTAL_URL => $self->conf->{portal},
            MSG        => $req->info(),
        );
    }

Yadd's avatar
Yadd committed
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
    # 2. Good authentication

    # 2.1 Redirection
    elsif ( $req->{error} == PE_REDIRECT ) {
        $skinfile       = "redirect";
        %templateParams = (
            URL           => $req->{urldc},
            HIDDEN_INPUTS => $self->buildHiddenForm($req),
            FORM_METHOD   => $req->datas->{redirectFormMethod} || 'get',
        );
    }

    # 2.2 Case : display menu
    elsif ( $req->error == PE_OK ) {

        $skinfile = 'menu';

        #utf8::decode($auth_user);

        %templateParams = (
            AUTH_USER => $req->{sessionInfo}->{ $self->conf->{portalUserAttr} },
            NEWWINDOW => $self->conf->{portalOpenLinkInNewWindow},
            LOGOUT_URL     => $self->conf->{portal} . "?logout=1",
            APPSLIST_ORDER => $req->{sessionInfo}->{'appsListOrder'},
            PING           => $self->conf->{portalPingInterval},
            $self->menu->params($req),
        );
    }

    # 3 Authentication has been refused OR this is the first access
Yadd's avatar
Yadd committed
166
    else {
Yadd's avatar
Yadd committed
167 168 169
        $skinfile = 'login';
        my $login = $self->userId($req);
        $login = '' if ( $login eq 'anonymous' );
Yadd's avatar
Yadd committed
170 171 172
        %templateParams = (
            AUTH_ERROR            => $req->error,
            AUTH_ERROR_TYPE       => $req->error_type,
Yadd's avatar
Yadd committed
173
            AUTH_URL              => $req->{datas}->{_url},
Yadd's avatar
Yadd committed
174
            LOGIN                 => $login,
Yadd's avatar
Yadd committed
175 176 177 178 179 180
            CHECK_LOGINS          => $self->conf->{portalCheckLogins},
            ASK_LOGINS            => $self->conf->{checkLogins},
            DISPLAY_RESETPASSWORD => $self->conf->{portalDisplayResetPassword},
            DISPLAY_REGISTER      => $self->conf->{portalDisplayRegister},
            MAIL_URL              => $self->conf->{mailUrl},
            REGISTER_URL          => $self->conf->{registerUrl},
Yadd's avatar
Yadd committed
181
            HIDDEN_INPUTS         => $self->buildHiddenForm($req),
Yadd's avatar
Yadd committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
        );

        # Display captcha if it's enabled
        if ( $self->{captcha_login_enabled} ) {
            %templateParams = (
                %templateParams,
                CAPTCHA_IMG  => $req->{captcha_img},
                CAPTCHA_CODE => $req->{captcha_code},
                CAPTCHA_SIZE => $req->{captcha_size}
            );
        }

        # Show password form if password policy error
        if (

               $req->{error} == PE_PP_CHANGE_AFTER_RESET
            or $req->{error} == PE_PP_MUST_SUPPLY_OLD_PASSWORD
            or $req->{error} == PE_PP_INSUFFICIENT_PASSWORD_QUALITY
            or $req->{error} == PE_PP_PASSWORD_TOO_SHORT
            or $req->{error} == PE_PP_PASSWORD_TOO_YOUNG
            or $req->{error} == PE_PP_PASSWORD_IN_HISTORY
            or $req->{error} == PE_PASSWORD_MISMATCH
            or $req->{error} == PE_BADOLDPASSWORD
            or $req->{error} == PE_PASSWORDFORMEMPTY
206 207
            or (    $req->{error} == PE_PP_PASSWORD_EXPIRED
                and $self->conf->{ldapAllowResetExpiredPassword} )
Yadd's avatar
Yadd committed
208 209 210 211 212 213 214 215 216 217 218 219 220
          )
        {
            %templateParams = (
                %templateParams,
                REQUIRE_OLDPASSWORD =>
                  1,    # Old password is required to check user credentials
                DISPLAY_FORM          => 0,
                DISPLAY_OPENID_FORM   => 0,
                DISPLAY_YUBIKEY_FORM  => 0,
                DISPLAY_PASSWORD      => 1,
                DISPLAY_RESETPASSWORD => 0,
                AUTH_LOOP             => [],
                CHOICE_PARAM          => $self->conf->{authChoiceParam},
Yadd's avatar
Yadd committed
221
                CHOICE_VALUE          => $req->datas->{_authChoice},
222 223
                OLDPASSWORD           => $self->checkXSSAttack( 'oldpassword',
                    $req->datas->{oldpassword} )
Yadd's avatar
Yadd committed
224
                ? ""
Yadd's avatar
Yadd committed
225
                : $req->datas->{oldpassword},
Yadd's avatar
Yadd committed
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
                HIDE_OLDPASSWORD => $self->conf->{hideOldPassword},
            );
        }

        # Disable all forms on:
        # * Logout message
        # * Bad URL error
        elsif ($req->{error} == PE_LOGOUT_OK
            or $req->{error} == PE_BADURL )
        {
            %templateParams = (
                %templateParams,
                DISPLAY_RESETPASSWORD => 0,
                DISPLAY_FORM          => 0,
                DISPLAY_OPENID_FORM   => 0,
                DISPLAY_YUBIKEY_FORM  => 0,
                AUTH_LOOP             => [],
                PORTAL_URL            => $self->conf->{portal},
                MSG                   => $req->info(),
            );

        }

        # Display authentifcation form
        else {

            # Authentication loop
Yadd's avatar
Yadd committed
253 254 255
            if ( $req->sessionInfo->{_choice}
                and my $authLoop = $self->_buildAuthLoop($req) )
            {
Yadd's avatar
Yadd committed
256 257
                %templateParams = (
                    %templateParams,
Yadd's avatar
Yadd committed
258
                    AUTH_LOOP            => $authLoop,
Yadd's avatar
Yadd committed
259
                    CHOICE_PARAM         => $self->conf->{authChoiceParam},
Yadd's avatar
Yadd committed
260
                    CHOICE_VALUE         => $req->datas->{_authChoice},
Yadd's avatar
Yadd committed
261 262 263 264 265 266 267 268 269
                    DISPLAY_FORM         => 0,
                    DISPLAY_OPENID_FORM  => 0,
                    DISPLAY_YUBIKEY_FORM => 0,
                );
            }

            # Choose what form to display if not in a loop
            else {

Yadd's avatar
Yadd committed
270
                my $displayType = $self->_authentication->getDisplayType($req);
Yadd's avatar
Yadd committed
271 272 273 274 275 276 277 278 279 280

                $self->lmLog( "Display type $displayType ", 'debug' );

                %templateParams = (
                    %templateParams,
                    DISPLAY_FORM => $displayType eq "standardform" ? 1 : 0,
                    DISPLAY_OPENID_FORM => $displayType eq "openidform" ? 1 : 0,
                    DISPLAY_YUBIKEY_FORM => $displayType eq "yubikeyform" ? 1
                    : 0,
                    DISPLAY_LOGO_FORM => $displayType eq "logo" ? 1 : 0,
Yadd's avatar
Yadd committed
281 282
                    module => $displayType eq "logo"
                    ? $self->getModule( $req, 'auth' )
Yadd's avatar
Yadd committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
                    : "",
                    AUTH_LOOP => [],
                    PORTAL_URL =>
                      ( $displayType eq "logo" ? $self->conf->{portal} : 0 ),
                    MSG => $req->info(),
                );

            }

        }

    }

    ## Common template params
    my $skin       = $self->getSkin($req);
    my $portalPath = $self->conf->{portal};
    $portalPath =~ s#^https?://[^/]+/?#/#;
    $portalPath =~ s#[^/]+\.pl$##;
    %templateParams = (
        %templateParams,
        SKIN_PATH => $portalPath . "skins",
        SKIN      => $skin,
        ANTIFRAME => $self->conf->{portalAntiFrame},
        SKIN_BG   => $self->conf->{portalSkinBackground},
Yadd's avatar
Yadd committed
307 308
        %{ $self->customParameters },
        %{ $req->{customParameters} // {} },
Yadd's avatar
Yadd committed
309 310 311 312 313 314 315
    );

    ## Custom template params
    if ( my $customParams = $self->getCustomTemplateParameters() ) {
        %templateParams = ( %templateParams, %$customParams );
    }

Yadd's avatar
Yadd committed
316
    $self->lmLog( "Skin returned: $skinfile", 'debug' );
Yadd's avatar
Yadd committed
317
    return ( $skinfile, \%templateParams );
Yadd's avatar
Yadd committed
318 319 320 321 322 323 324 325
}

##@method public void printImage(string file, string type)
# Print image to STDOUT
# @param $file The path to the file to print
# @param $type The content-type to use (ie: image/png)
# @return void
sub staticFile {
Yadd's avatar
Yadd committed
326
    my ( $self, $req, $file, $type ) = @_;
Yadd's avatar
Yadd committed
327 328 329 330
    require Plack::Util;
    require Cwd;
    require HTTP::Date;
    open my $fh, '<:raw', $self->conf->{templatesDir} . "/$file"
Yadd's avatar
Yadd committed
331
      or return $self->sendError( $req, $!, 403 );
Yadd's avatar
Yadd committed
332 333 334 335 336 337 338 339 340 341 342 343 344 345
    my @stat = stat $file;
    Plack::Util::set_io_path( $fh, Cwd::realpath($file) );
    return [
        200,
        [
            'Content-Type'   => $type,
            'Content-Length' => $stat[7],
            'Last-Modified'  => HTTP::Date::time2str( $stat[9] )
        ],
        $fh,
    ];
}

sub buildHiddenForm {
Yadd's avatar
Yadd committed
346 347 348
    my ( $self, $req ) = @_;
    my @keys = keys %{ $req->{portalHiddenFormValues} };
    my $val  = '';
Yadd's avatar
Yadd committed
349 350 351 352 353

    foreach (@keys) {

        # Check XSS attacks
        next
Yadd's avatar
Yadd committed
354
          if $self->checkXSSAttack( $_, $req->{portalHiddenFormValues}->{$_} );
Yadd's avatar
Yadd committed
355 356 357

        # Build hidden input HTML code
        $val .= qq{<input type="hidden" name="$_" id="$_" value="}
Yadd's avatar
Yadd committed
358
          . $req->{portalHiddenFormValues}->{$_} . '" />';
Yadd's avatar
Yadd committed
359 360 361 362 363 364 365
    }

    return $val;
}

# Return skin name
# @return skin name
Yadd's avatar
Yadd committed
366
# TODO: create property for skinRule
Yadd's avatar
Yadd committed
367 368 369 370 371 372 373 374 375 376
sub getSkin {
    my ( $self, $req ) = @_;

    my $skin = $self->conf->{portalSkin};

    # Fill sessionInfo to eval rule if empty (unauthenticated user)
    $req->{sessionInfo}->{_url}   ||= $req->{urldc};
    $req->{sessionInfo}->{ipAddr} ||= $req->remote_ip;

    # Load specific skin from skinRules
Yadd's avatar
Yadd committed
377 378 379 380
    foreach my $rule ( @{ $self->skinRules } ) {
        if ( $rule->[1]->( $req->sessionInfo ) ) {
            $skin = $rule->[0];
            $self->lmLog( "Skin $skin selected from skin rule", 'debug' );
Yadd's avatar
Yadd committed
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
        }
    }

    # Check skin GET/POST parameter
    my $skinParam = $req->param('skin');
    if ( defined $skinParam && !$self->checkXSSAttack( 'skin', $skinParam ) ) {
        $skin = $skinParam;
        $self->lmLog( "Skin $skin selected from GET/POST parameter", 'debug' );
    }

    return $skin;
}

# Find custom templates parameters
# @return Custom parameters
sub getCustomTemplateParameters {
    my ($self)          = @_;
    my $conf            = $self->conf;
    my $customTplParams = {};

    foreach ( keys %$conf ) {
        next unless ( $_ =~ /^tpl_(.+)$/ );
        my $tplParam = $1;
        my $tplValue = $conf->{$_};
        $self->lmLog( "Set custom template parameter $tplParam with $tplValue",
            'debug' );

        $customTplParams->{$tplParam} = $tplValue;
    }

    return $customTplParams;
}

Yadd's avatar
Yadd committed
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
# Build an HTML array to display sessions
# @param $sessions Array ref of hash ref containing sessions datas
# @param $title Title of the array
# @param $displayUser To display "User" column
# @param $displaError To display "Error" column
# @return HTML string
sub mkSessionArray {
    my ( $self, $sessions, $title, $displayUser, $displayError ) = @_;

    return "" unless ( ref $sessions eq "ARRAY" and @$sessions );

    my $tmp = $title ? "<h3>$title</h3>" : "";
    $tmp .=
        '<table class="info"><tbody><tr>'
      . ( $displayUser ? '<th trspan="user">User</th>' : '' )
      . '<th trspan="date">Date</th><th trspan="ipAddr">IP address</th>';
    $tmp .= "<th>" . $self->conf->{sessionDataToRemember}->{$_} . "</th>"
      foreach ( keys %{ $self->conf->{sessionDataToRemember} } );
Yadd's avatar
Yadd committed
432 433
    $tmp .= '<th trspan="errorMsg">Error message</th>'
      if ($displayError);
Yadd's avatar
Yadd committed
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
    $tmp .= '</tr>';

    foreach my $session (@$sessions) {
        $tmp .= "<tr>";
        $tmp .= "<td>$session->{user}</td>" if ($displayUser);
        $tmp .=
"<td><script type=\"text/javascript\">var _date=new Date($session->{_utime}*1000);document.write(_date.toLocaleString());</script></td>";
        $tmp .= "<td>$session->{ipAddr}</td>";
        $tmp .= "<td>" . ( $session->{$_} || "" ) . "</td>"
          foreach ( keys %{ $self->conf->{sessionDataToRemember} } );
        $tmp .= "<td>$session->{error}</td>" if ($displayError);
        $tmp .= "</tr>";
    }
    $tmp .= '</tbody></table>';
    return $tmp;
}

Yadd's avatar
Yadd committed
451
1;