File: PSGI.pm

package info (click to toggle)
lemonldap-ng 2.16.1%2Bds-deb12u6
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 27,364 kB
  • sloc: perl: 65,855; javascript: 12,430; xml: 6,336; makefile: 1,228; sh: 470; python: 51; php: 26; sql: 5
file content (260 lines) | stat: -rw-r--r-- 7,843 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
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
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
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
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
package Lemonldap::NG::Handler::Lib::PSGI;

use strict;
use Mouse;

#use Lemonldap::NG::Handler::Main qw(:jailSharedVars);

our $VERSION = '2.0.14';

has protection => ( is => 'rw', isa => 'Str' );
has rule       => ( is => 'rw', isa => 'Str' );
has api        => ( is => 'rw', isa => 'Str' );

## @method boolean init($args)
# Initalize main handler
sub init {
    my ( $self, $args ) = @_;
    eval { $self->api->init($args) };
    if ( $@ and not( $args->{protection} and $args->{protection} eq 'none' ) ) {
        $self->error($@);
        return 0;
    }
    unless ( $self->api->checkConf($self)
        or ( $args->{protection} and $args->{protection} eq 'none' ) )
    {
        $self->error(
            "Unable to protect this server ($Lemonldap::NG::Common::Conf::msg)"
        );
        return 0;
    }
    eval { $self->portal( $self->api->tsv->{portal}->() ) };
    my $rule =
      $args->{protection} || $self->api->localConfig->{protection} || '';
    $self->rule(
        $rule eq 'authenticate' ? 1 : $rule eq 'manager' ? '' : $rule );
    return 1;
}

## @methodi void _run()
# Check if protecton is activated then return a code ref that will launch
# _logAuthTrace() if protection in on or handler() else
#@return code-ref
sub _run {
    my $self = shift;

    # Override _run() only if protection != 'none'
    if ( !$self->rule or $self->rule ne 'none' ) {
        $self->logger->debug('PSGI app is protected');

        # Handle requests
        # Developers, be careful: Only this part is executed at each request
        return sub {
            return $self->_logAuthTrace(
                Lemonldap::NG::Common::PSGI::Request->new( $_[0] ) );
        };
    }

    else {
        $self->logger->debug('PSGI app is not protected');

        # Check if main handler initialization has been done
        unless ( $self->api->tsv ) {
            $self->logger->debug('Checking conf');
            eval { $self->api->checkConf() };
            $self->logger->error($@) if ($@);
        }

        # Handle unprotected requests
        return sub {
            my $req = Lemonldap::NG::Common::PSGI::Request->new( $_[0] );
            my $res = $self->_logAndHandle($req);
            push @{ $res->[1] }, $req->spliceHdrs;
            return $res;
        };
    }
}

sub status {
    my ( $class, $args ) = @_;
    $args //= {};
    my $self = $class->new($args);
    $self->init($args);

    # Check if main handler initialization has been done
    unless ( %{ $self->api->tsv } ) {
        eval { $self->api->checkConf() };
        $self->logger->error($@) if ($@);
    }
    return sub {
        my $req = Lemonldap::NG::Common::PSGI::Request->new( $_[0] );
        $self->api->status($req);
        return [ 200, [ $req->spliceHdrs ], [ $req->{respBody} ] ];
    };
}

sub reload {
    my ( $class, $args ) = @_;
    $args //= {};
    my $self = $class->new($args);
    $self->init($args);

    # Check if main handler initialization has been done
    unless ( %{ $self->api->tsv } ) {
        eval { $self->api->checkConf() };
        $self->logger->error($@) if ($@);
    }
    return sub {
        my $req = Lemonldap::NG::Common::PSGI::Request->new( $_[0] );
        $self->api->reload($req);
        return [ 200, [ $req->spliceHdrs ], [ $req->{respBody} ] ];
    };
}

sub _logAuthTrace {
    my ( $self, $req, $noCall ) = @_;

    # register the request object to the logging system
    if ( ref( $self->logger ) and $self->logger->can('setRequestObj') ) {
        $self->logger->setRequestObj($req);
    }
    if ( ref( $self->userLogger ) and $self->userLogger->can('setRequestObj') )
    {
        $self->userLogger->setRequestObj($req);
    }

    # Call the handler
    my $res = $self->_authAndTrace( $req, $noCall );

    # Clear the logging system before the next request
    if ( ref( $self->logger ) and $self->logger->can('clearRequestObj') ) {
        $self->logger->clearRequestObj($req);
    }
    if ( ref( $self->userLogger )
        and $self->userLogger->can('clearRequestObj') )
    {
        $self->userLogger->clearRequestObj($req);
    }

    return $res;
}

## @method private PSGI-Response _authAndTrace($req)
# Launch $self->api::run() and then handler() if
# response is 200.
sub _authAndTrace {
    my ( $self, $req, $noCall ) = @_;

    # TODO: handle types
    my $type = $self->api->checkType($req);
    if ( my $t = $req->env->{VHOSTTYPE} ) {
        $type = $t;
    }
    my $tmp = $self->api;
    $tmp =~ s/::\w+$/::/;
    $type = $tmp . $type;
    eval "require $type";
    die $@ if ($@);
    my ( $res, $session ) = $type->run( $req, $self->{rule} );
    eval { $self->portal( $type->tsv->{portal}->() ) } unless $self->portal;
    $self->logger->warn($@)  if $@;
    $req->userData($session) if ($session);

    if ( $res < 300 ) {
        if ($noCall) {
            return [ $res, [ $req->spliceHdrs ], [] ];
        }
        else {
            $self->logger->debug('User authenticated, calling handler()');
            $res = $self->_logAndHandle($req);
            push @{ $res->[1] }, $req->spliceHdrs;
            return $res;
        }
    }
    elsif ( $res < 400 ) {
        if ( $req->wantJSON ) {
            my %h    = ( $req->spliceHdrs );
            my $host = $req->env->{HTTP_HOST};
            if (    $h{Location}
                and $h{Location} =~ m#^\Q$self->{portal}\E#
                and $h{Location} !~ m#^https?://$host# )
            {
                return [
                    401, [ 'WWW-Authenticate' => 'SSO ' . $self->{portal} ], []
                ];
            }
        }
        return [ $res, [ $req->spliceHdrs ], [] ];
    }
    else {
        my $s = ( $self->portal ? $self->portal . "/lmerror/$res" : '' );
        $s =
            '<html><head><title>Redirection</title></head><body>'
          . qq{<script type="text/javascript">window.location='$s'</script>}
          . '<h1>Please wait</h1>'
          . qq{<p>An error occurs, you're going to be redirected to <a href="$s">$s</a>.</p>}
          . '</body></html>';
        return [
            $res,
            [
                $req->spliceHdrs,
                'Content-Type'   => 'text/html',
                'Content-Length' => length $s
            ],
            [$s]
        ];
    }
}

## @method hashRef user()
# @return hash of user data
sub user {
    my ( $self, $req ) = @_;
    return $req->userData
      || { $Lemonldap::NG::Handler::Main::tsv->{whatToTrace}
          || _whatToTrace => 'anonymous' };
}

## @method hashRef custom()
# @return hash of custom data
sub custom {
    my ( $self, $req ) = @_;
    return { $Lemonldap::NG::Handler::Main::tsv->{customToTrace} };
}

## @method string userId()
# @return user identifier to log
sub userId {
    my ( $self, $req ) = @_;
    my $userId =
      $req->userData->{ $Lemonldap::NG::Handler::Main::tsv->{whatToTrace}
          || '_whatToTrace' }
      || $req->userData->{'_user'}    # Fix 2377
      || 'anonymous';

    $self->logger->debug("Returned userId: $userId");
    return $userId;
}

## @method boolean group(string group)
# @param $group name of the Lemonldap::NG group to test
# @return boolean : true if user is in this group
sub group {
    my ( $self, $req, $group ) = @_;
    return () unless ( $req->userData->{groups} );
    return ( $req->userData->{groups} =~ /\b$group\b/ );
}

## @method PSGI::Response sendError($req,$err,$code)
# Add user id to $err before calling Lemonldap::NG::Common::PSGI::sendError()
# @param $req Lemonldap::NG::Common::PSGI::Request
# @param $err String to push
# @code int HTTP error code (default to 500)
sub sendError {
    my ( $self, $req, $err, $code ) = @_;
    $err ||= $req->error;
    $self->userLogger->warn( '[' . $self->userId($req) . "] $err" );
    return $self->Lemonldap::NG::Common::PSGI::sendError( $req, $err, $code );
}

1;