blib/lib/Lemonldap/NG/Portal/Plugins/CheckUser.pm untested

filter: Statementstmt 0.0% 0 / 350 Branchbran 0.0% 0 / 160 Conditioncond 0.0% 0 / 78 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 617 CC 81 SCAR 62.1
CC
81
Cov
0%
check
1260.0
init
132.0
display
90.0
CRAP 496.2
1 package Lemonldap::NG::Portal::Plugins::CheckUser;
2  
3 use strict;
4 use Mouse;
5 use Lemonldap::NG::Common::Util qw(isHiddenAttr);
6 use Lemonldap::NG::Portal::Main::Constants qw(
7 PE_NOTOKEN
8 PE_TOKENEXPIRED
9 PE_MALFORMEDUSER
10 PE_BADCREDENTIALS
11 );
12  
13 our $VERSION = '2.21.0';
14  
15 extends qw(
16 Lemonldap::NG::Portal::Main::Plugin
17 Lemonldap::NG::Portal::Lib::_tokenRule
18 Lemonldap::NG::Portal::Lib::OtherSessions
19 );
20  
21 # INITIALIZATION
22 has ott => (
23 is => 'rw',
24 lazy => 1,
25 default => sub {
26 my $ott =
27 $_[0]->{p}->loadModule('Lemonldap::NG::Portal::Lib::OneTimeToken');
28 $ott->timeout( $_[0]->{conf}->{formTimeout} );
29 return $ott;
30 }
31 );
32  
33 has displayHistoryRule => ( is => 'rw', default => sub { 0 } );
34 has unrestrictedUsersRule => ( is => 'rw', default => sub { 0 } );
35 has displayEmptyValuesRule => ( is => 'rw', default => sub { 0 } );
36 has displayEmptyHeadersRule => ( is => 'rw', default => sub { 0 } );
37 has displayPersistentInfoRule => ( is => 'rw', default => sub { 0 } );
38 has displayComputedSessionRule => ( is => 'rw', default => sub { 0 } );
39 has displayHiddenAttributesRule => ( is => 'rw', default => sub { 0 } );
40 has displayNormalizedHeadersRule => ( is => 'rw', default => sub { 0 } );
41 has idRule => ( is => 'rw', default => sub { 1 } );
42 has sorted => ( is => 'rw', default => sub { 0 } );
43 has merged => ( is => 'rw', default => '' );
44  
45 # Prefix used for renaming session attributes during impersonation process
46 has prefix => (
47 is => 'ro',
48 lazy => 1,
49 default => sub {
50 my $self = $_[0];
51 return $self->conf->{impersonationPrefix};
52 }
53 );
54  
55 sub persistentAttrs {
56 $_[0]->{conf}->{persistentSessionAttributes}
57 || '_loginHistory _2fDevices notification_ _oidcConsents';
58 }
59  
60 sub init {
61 my ($self) = @_;
62 $self->addAuthRoute( checkuser => 'check', ['POST'] )
63 ->addAuthRouteWithRedirect( checkuser => 'display', ['GET'] );
64  
65 # Parse checkUser rules
66 $self->idRule(
67 $self->p->buildRule( $self->conf->{checkUserIdRule}, 'checkUserId' ) );
68 return 0 unless $self->idRule;
69  
70 $self->displayEmptyValuesRule(
71 $self->p->buildRule(
72 $self->conf->{checkUserDisplayEmptyValues},
73 'checkUserDisplayEmptyValues'
74 )
75 );
76 return 0 unless $self->displayEmptyValuesRule;
77  
78 $self->displayEmptyHeadersRule(
79 $self->p->buildRule(
80 $self->conf->{checkUserDisplayEmptyHeaders},
81 'checkUserDisplayEmptyHeaders'
82 )
83 );
84 return 0 unless $self->displayEmptyHeadersRule;
85  
86 $self->displayPersistentInfoRule(
87 $self->p->buildRule(
88 $self->conf->{checkUserDisplayPersistentInfo},
89 'checkUserDisplayPersistentInfo'
90 )
91 );
92 return 0 unless $self->displayPersistentInfoRule;
93  
94 $self->unrestrictedUsersRule(
95 $self->p->buildRule(
96 $self->conf->{checkUserUnrestrictedUsersRule},
97 'checkUserUnrestrictedUsersRule'
98 )
99 );
100 return 0 unless $self->unrestrictedUsersRule;
101  
102 $self->displayComputedSessionRule(
103 $self->p->buildRule(
104 $self->conf->{checkUserDisplayComputedSession},
105 'checkUserdisplayComputedSession'
106 )
107 );
108 return 0 unless $self->displayComputedSessionRule;
109  
110 $self->displayNormalizedHeadersRule(
111 $self->p->buildRule(
112 $self->conf->{checkUserDisplayNormalizedHeaders},
113 'checkUserDisplayNormalizedHeaders'
114 )
115 );
116 return 0 unless $self->displayNormalizedHeadersRule;
117  
118 $self->displayHistoryRule(
119 $self->p->buildRule(
120 $self->conf->{checkUserDisplayHistory},
121 'checkUserDisplayHistory'
122 )
123 );
124 return 0 unless $self->displayHistoryRule;
125  
126 $self->displayHiddenAttributesRule(
127 $self->p->buildRule(
128 $self->conf->{checkUserDisplayHiddenAttributes},
129 'checkUserDisplayHiddenAttributes'
130 )
131 );
132 return 0 unless $self->displayHistoryRule;
133  
134 # Init. other options
135 $self->sorted( $self->conf->{impersonationRule}
136 || $self->conf->{contextSwitchingRule} );
137 $self->merged( $self->conf->{impersonationMergeSSOgroups}
138 && $self->conf->{impersonationRule} ? 'Merged' : '' );
139  
140 return 1;
141 }
142  
143 # RUNNING METHODS
144 sub display {
145 my ( $self, $req ) = @_;
146 my $history = [ [], [] ];
147 my ( $attrs, $array_attrs ) = ( $req->userData, [] );
148  
149 $self->logger->debug("Display current session data...");
150 $self->userLogger->info("Using spoofed SSO groups if exist")
151 if ( $self->conf->{impersonationRule} );
152  
153 $history = $self->_concatHistory( $attrs->{_loginHistory} )
154 if $self->displayHistoryRule->( $req, $req->userData )
155 && $self->conf->{loginHistoryEnabled};
156  
157 $attrs =
158 $self->_removeKeys( $attrs, $self->persistentAttrs,
159 'Remove persistent session attributes...' )
160 unless $self->displayPersistentInfoRule->( $req, $req->userData );
161  
162 # Create an array of hashes and dispatch attributes for template loop
163 # ARRAY_REF = [ A_REF GROUPS, A_REF MACROS, A_REF OTHERS ]
164 $array_attrs = $self->_dispatchAttributes(
165 $self->_createArray( $req, $attrs, $req->userData ) );
166  
167 my $params = {
168 FORM_ACTION => $self->p->relativeUrl( $req, 'checkuser' ),
169 MSG => 'checkUser' . $self->merged,
170 ALERTE => ( $self->merged ? 'alert-warning' : 'alert-info' ),
171 LOGIN => $req->{userData}->{ $self->conf->{whatToTrace} },
172 HISTORY => ( @{ $history->[0] } || @{ $history->[1] } ) ? 1 : 0,
173 SUCCESS => $history->[0],
174 FAILED => $history->[1],
175 DISPLAY => (
176 @{ $array_attrs->[0] }
177 || @{ $array_attrs->[1] }
178 || @{ $array_attrs->[2] }
179 ) ? 1 : 0,
180 ATTRIBUTES => $array_attrs->[2],
181 MACROS => $array_attrs->[1],
182 GROUPS => $array_attrs->[0],
183 TOKEN => (
184 $self->ottRule->( $req, {} )
185 ? $self->ott->createToken()
186 : ''
187 )
188 };
189 return $self->sendJSONresponse( $req, $params ) if $req->wantJSON;
190  
191 # Display form
192 return $self->p->sendHtml( $req, 'checkuser', params => $params );
193 }
194  
195 sub check {
196 my ( $self, $req ) = @_;
197 my ( $attrs, $array_attrs, $array_hdrs ) = ( {}, [], [] );
198 my $msg = my $auth = my $computed = '';
199 my $savedUserData = $req->userData;
200 my $unUser = $self->unrestrictedUsersRule->( $req, $savedUserData ) || 0;
201 my $history = [ [], [] ];
202  
203 # Check token
204 if ( $self->ottRule->( $req, {} ) ) {
205 my $token;
206 if ( $token = $req->param('token') ) {
207 unless ( $self->ott->getToken($token) ) {
208 $self->userLogger->warn(
209 'CheckUser called with an expired/bad token');
210 $msg = PE_TOKENEXPIRED;
211 $token = $self->ott->createToken();
212 }
213 }
214 else {
215 $self->userLogger->warn('CheckUser called without token');
216 $msg = PE_NOTOKEN;
217 $token = $self->ott->createToken();
218 }
219  
220 my $params = {
221 FORM_ACTION => $self->p->relativeUrl( $req, 'checkuser' ),
222 MSG => "PE$msg",
223 ALERTE => 'alert-warning',
224 LOGIN => '',
225 TOKEN => $token,
226 };
227 return $self->p->sendJSONresponse( $req, $params )
228 if $req->wantJSON && $msg;
229  
230 # Display form
231 return $self->p->sendHtml( $req, 'checkuser', params => $params )
232 if $msg;
233 }
234  
235 ## Check user session datas
236 # Use submitted attributes if exists
237 my $url = $req->param('url') || '';
238 my $user = $req->param('user') || '';
239  
240 if ( $user and $user !~ /$self->{conf}->{userControl}/ ) {
241 $user = '';
242 $attrs = {};
243 return $self->p->sendError( $req, 'Malformed user', 400 )
244 if $req->wantJSON;
245 return $self->p->sendHtml(
246 $req,
247 'checkuser',
248 params => {
249 FORM_ACTION => $self->p->relativeUrl( $req, 'checkuser' ),
250 MSG => 'PE' . PE_MALFORMEDUSER,
251 ALERTE => 'alert-warning',
252 LOGIN => '',
253 TOKEN => (
254 $self->ottRule->( $req, {} )
255 ? $self->ott->createToken()
256 : ''
257 )
258 }
259 );
260 }
261  
262 if ( !$user || $req->{user} eq $user ) {
263 $self->userLogger->info("checkUser requested for himself");
264 $self->userLogger->info("Using spoofed SSO groups if exist")
265 if $self->conf->{impersonationRule};
266 $attrs = $req->userData;
267 $user = $req->{user};
268 }
269 else {
270 $self->userLogger->info("checkUser requested for $user");
271  
272 # Try to retrieve session from sessions DB
273 $self->logger->debug('Try to retrieve session from DB...');
274 my $moduleOptions = $self->conf->{globalStorageOptions} || {};
275 $moduleOptions->{backend} = $self->conf->{globalStorage};
276  
277 my $sessions = {};
278 my $searchAttrs =
279 $self->conf->{checkUserSearchAttributes}
280 ? $self->conf->{whatToTrace} . ' '
281 . $self->conf->{checkUserSearchAttributes}
282 : $self->conf->{whatToTrace};
283  
284 foreach ( split /[,\s]+/, $searchAttrs ) {
285 $self->logger->debug("Searching with: $_ = $user");
286 $sessions = $self->module->searchOn( $moduleOptions, $_, $user );
287 last if ( keys %$sessions );
288 }
289  
290 my $age = '1';
291 foreach my $id ( keys %$sessions ) {
292  
293 # searchOn() returns sessions indexed by their storage ID, then
294 # it is required to set hashStore to 0
295 my $session = $self->p->getApacheSession( $id, hashStore => 0, )
296 or next;
297  
298 if ( $session->{data}->{_utime} gt $age ) {
299 $attrs = $session->{data};
300 $age = $session->{data}->{_utime};
301 }
302 }
303 unless ( defined $attrs->{_session_id} ) {
304 $req->{user} = $user;
305 $self->userLogger->info(
306 "No session found in DB. Compute userData...");
307 $attrs = $self->_userData($req);
308 $computed = 1;
309 }
310  
311 # Check identities rule
312 $self->logger->info( '"'
313 . $savedUserData->{ $self->conf->{whatToTrace} }
314 . '" is an unrestricted user!' )
315 if $unUser;
316 unless ( $unUser || $self->idRule->( $req, $attrs ) ) {
317 $self->userLogger->warn(
318 "checkUser requested for an invalid user ($user)");
319 $req->{sessionInfo} = {};
320 $self->logger->debug('Identity not authorized');
321 $req->error(PE_BADCREDENTIALS)
322 ; # Catch error to preserve protected Id
323 }
324 }
325  
326 if ( $req->error ) {
327 $msg = 'PE' . $req->{error};
328 $array_attrs = [ [], [], [] ];
329 $attrs = {};
330 }
331 else {
332 $msg = 'checkUser' . $self->merged;
333 $history = $self->_concatHistory( $attrs->{_loginHistory} )
334 if $self->displayHistoryRule->( $req, $savedUserData )
335 && $self->conf->{loginHistoryEnabled};
336  
337 $attrs =
338 $self->_removeKeys( $attrs, $self->persistentAttrs,
339 'Remove persistent session attributes...' )
340 unless $self->displayPersistentInfoRule->( $req, $savedUserData );
341  
342 if ($computed) {
343 if ( $self->displayComputedSessionRule->( $req, $savedUserData ) ) {
344 $msg = 'checkUserComputedSession';
345 if ( $self->conf->{impersonationRule} ) {
346 $self->logger->debug("Map real attributes...");
347 my %realAttrs =
348 map { $self->prefix . $_ => $attrs->{$_} }
349 keys %$attrs;
350 $attrs = { %$attrs, %realAttrs };
351  
352 # Compute groups and macros with real and spoofed attributes
353 $self->logger->debug(
354 "Compute groups and macros with real and spoofed attributes"
355 );
356 $req->sessionInfo($attrs);
357 delete $req->sessionInfo->{groups};
358 $req->steps(
359 [ $self->p->groupsAndMacros, 'setLocalGroups' ] );
360 if ( my $error = $self->p->process($req) ) {
361 $self->logger->debug("Process returned error: $error");
362 return $req->error($error);
363 }
364 }
365 }
366 else {
367 $attrs = {};
368 $msg = 'checkUserNoSessionFound';
369 }
370 }
371  
372 # Create an array of hashes and dispatch attributes for template loop
373 # ARRAY_REF = [ A_REF GROUPS, A_REF MACROS, A_REF OTHERS ]
374 $array_attrs = $self->_dispatchAttributes(
375 $self->_createArray( $req, $attrs, $savedUserData ) );
376 }
377  
378 if ( $self->p->checkXSSAttack( 'CheckUser URL', $url ) ) {
379 $url = '';
380 $auth = 'VHnotFound';
381 }
382  
383 # Check if user is allowed to access submitted URL and compute headers
384 if ( $url and %$attrs ) {
385  
386 # Check url format
387 my $originalUrl;
388 ( $url, $originalUrl ) = $self->_resolveURL( $req, $url );
389  
390 # User is allowed ?
391 $self->logger->debug(
392 "checkUser requested for user: $attrs->{ $self->{conf}->{whatToTrace} } and URL: $url | alias: $originalUrl"
393 );
394 $auth = $self->_authorization( $req, $originalUrl, $attrs );
395 if ( $auth >= 0 ) {
396 $auth = $auth ? "allowed" : "forbidden";
397 $self->logger->debug(
398 "checkUser: $attrs->{ $self->{conf}->{whatToTrace} } is "
399 . "$auth to access to $url" );
400  
401 # Return VirtualHost headers
402 $array_hdrs =
403 $self->_headers( $req, $originalUrl, $attrs, $savedUserData );
404 }
405 else {
406 $auth = 'VHnotFound';
407 $self->userLogger->info("checkUser: $url has no configuration");
408 }
409 }
410  
411 my $alert_auth = 'alert-warning';
412 if ( $auth eq 'allowed' ) { $alert_auth = 'alert-success' }
413 elsif ( $auth eq 'forbidden' ) { $alert_auth = 'alert-danger' }
414  
415 # TODO:
416 my $params = {
417 FORM_ACTION => $self->p->relativeUrl( $req, 'checkuser' ),
418 MSG => $msg,
419 ALERTE => ( $msg eq 'checkUser' ? 'alert-info' : 'alert-warning' ),
420 LOGIN => $user,
421 URL => $url,
422 ALLOWED => $auth,
423 ALERTE_AUTH => $alert_auth,
424 HEADERS => $array_hdrs,
425 HISTORY => ( @{ $history->[0] } || @{ $history->[1] } ) ? 1 : 0,
426 SUCCESS => $history->[0],
427 FAILED => $history->[1],
428 DISPLAY => (
429 @{ $array_attrs->[0] }
430 || @{ $array_attrs->[1] }
431 || @{ $array_attrs->[2] }
432 ) ? 1 : 0,
433 ATTRIBUTES => $array_attrs->[2],
434 MACROS => $array_attrs->[1],
435 GROUPS => $array_attrs->[0],
436 TOKEN => (
437 $self->ottRule->( $req, {} )
438 ? $self->ott->createToken()
439 : ''
440 )
441 };
442 return $self->p->sendJSONresponse( $req, $params ) if $req->wantJSON;
443  
444 # Display form
445 return $self->p->sendHtml( $req, 'checkuser', params => $params );
446 }
447  
448 sub _resolveURL {
449 my ( $self, $req, $url ) = @_;
450 my ($proto) = $url =~ m#^(https?://).*#i;
451 my ( $vhost, $appuri ) = $url =~ m@^(?:https?://)?([^/#]*)(.*)@i;
452 my ($port) = $vhost =~ m#^.+(:\d+)$#;
453 $port ||= '';
454 $vhost =~ s/:\d+$//;
455 $vhost .= $self->p->getCookieDomain($req) unless ( $vhost =~ /\./ );
456 $proto =
457 $self->p->HANDLER->_isHttps( $req, $vhost ) ? 'https://' : 'http://'
458 unless $proto;
459 $self->logger->debug( 'VHost is ' . uc( ( split( /:/, $proto ) )[0] ) );
460 my $originalVhost = $self->p->HANDLER->resolveAlias($vhost);
461  
462 return (
463 lc("$proto$vhost$port") . $appuri,
464 lc("$proto$originalVhost$port") . $appuri
465 );
466 }
467  
468 sub _userData {
469 my ( $self, $req ) = @_;
470 my $realAuthLevel = $req->userData->{authenticationLevel};
471  
472 # Compute session
473 my $steps =
474 defined $realAuthLevel
475 ? [
476 'getUser', 'setAuthSessionInfo',
477 'setSessionInfo', $self->p->groupsAndMacros
478 ]
479 : [ 'getUser', 'setSessionInfo', $self->p->groupsAndMacros ];
480 $self->conf->{checkUserDisplayPersistentInfo}
481 ? push @$steps, 'setPersistentSessionInfo', 'setLocalGroups'
482 : push @$steps, 'setLocalGroups';
483 $req->steps($steps);
484 if ( my $error = $self->p->process($req) ) {
485 $self->userLogger->warn(
486 'checkUser requested for an invalid user (' . $req->{user} . ")" )
487 if ( $error == PE_BADCREDENTIALS );
488 $self->logger->debug("Process returned error: $error");
489 return $req->error(PE_BADCREDENTIALS);
490 }
491  
492 unless ( defined $req->sessionInfo->{uid} ) {
493  
494 # Avoid error with SAML, OIDC, etc...
495 $self->logger->debug("\"$req->{user}\" NOT found in userDB");
496 return $req->error(PE_BADCREDENTIALS);
497 }
498  
499 # Compute groups & macros again with real authenticationLevel
500 $req->sessionInfo->{authenticationLevel} = $realAuthLevel;
501 delete $req->sessionInfo->{groups};
502  
503 $req->steps(
504 [ 'setSessionInfo', $self->p->groupsAndMacros, 'setLocalGroups' ] );
505 if ( my $error = $self->p->process($req) ) {
506 $self->logger->debug("CheckUser: process returned error ($error)");
507 return $req->error($error);
508 }
509  
510 $self->logger->debug("Return \"$req->{user}\" sessionInfo");
511 return $req->{sessionInfo};
512 }
513  
514 sub _authorization {
515 my ( $self, $req, $uri, $attrs ) = @_;
516 my ( $vhost, $appuri ) = $uri =~ m@^https?://([^/#]*)(.*)@;
517 my $exist = 0;
518  
519 $vhost =~ s/:\d+$//;
520 foreach my $vh ( keys %{ $self->conf->{locationRules} } ) {
521 if ( $vh eq $vhost ) {
522 $exist = 1;
523 $self->logger->debug("VirtualHost: $vh found in Conf");
524 $req->env->{REQUEST_URI} = $appuri;
525 last;
526 }
527 }
528  
529 $self->logger->debug(
530 "Return \"$attrs->{ $self->{conf}->{whatToTrace} }\" authorization");
531 return $exist
532 ? $self->p->HANDLER->grant( $req, $attrs, $appuri, undef, $vhost )
533 : -1;
534 }
535  
536 sub _headers {
537 my ( $self, $req, $uri, $attrs, $savedUserData ) = @_;
538 my ($vhost) = $uri =~ m@^https?://([^/#]*).*@;
539  
540 $vhost =~ s/:\d+$//;
541 $req->{env}->{HTTP_HOST} = $vhost;
542 $self->p->HANDLER->headersInit( $self->{conf} );
543 my $headers = $self->p->HANDLER->checkHeaders( $req, $attrs );
544  
545 # Remove hidden headers relative to VHost if required
546 unless ( $self->unrestrictedUsersRule->( $req, $savedUserData ) ) {
547 my $keysToRemove = '';
548 $keysToRemove = '__ALL__'
549 if exists $self->conf->{checkUserHiddenHeaders}->{$vhost};
550 $keysToRemove = $self->conf->{checkUserHiddenHeaders}->{$vhost}
551 if ( $keysToRemove
552 && $self->conf->{checkUserHiddenHeaders}->{$vhost} =~ /\w+/ );
553  
554 if ( $keysToRemove && $keysToRemove eq '__ALL__' ) {
555 $self->logger->debug(
556 "Overwrite for VirtualHost: $vhost ALL valued header(s)...");
557 @$headers = map {
558 $_->{value} =~ /\w+/
559 ? { key => $_->{key}, value => '******' }
560 : $_
561 } @$headers;
562 }
563 elsif ($keysToRemove) {
564 $self->logger->debug(
565 "Mask hidden header(s) for VirtualHost: $vhost");
566 my $hash = { map { $_->{key} => $_->{value} } @$headers };
567 $hash = $self->_removeKeys( $hash, $keysToRemove,
568 "Overwrite valued \"$keysToRemove\" header(s)...", 1 );
569 @$headers = (
570 map { { key => $_, value => $hash->{$_} } }
571 sort keys %$hash
572 );
573 }
574 }
575  
576 # Remove empty headers if required
577 unless ( $self->displayEmptyHeadersRule->( $req, $savedUserData ) ) {
578 $self->logger->debug("Remove empty headers...");
579 @$headers = grep $_->{value} =~ /.+/, @$headers;
580 }
581  
582 # Normalize headers name if required
583 if ( $self->displayNormalizedHeadersRule->( $req, $savedUserData ) ) {
584 $self->logger->debug("Normalize headers...");
585 @$headers = map {
586 ; # Prevent compilation error with old Perl versions
587 no strict 'refs';
588 {
589 key => &{ $self->p->HANDLER . '::cgiName' }( $_->{key} ),
590 value => $_->{value}
591 }
592 } @$headers;
593 }
594  
595 $self->logger->debug(
596 "Return \"$attrs->{ $self->{conf}->{whatToTrace} }\" headers");
597 return $headers;
598 }
599  
600 sub _createArray {
601 my ( $self, $req, $attrs, $userData ) = @_;
602 my $array_attrs = [];
603 my @hidden = split /[,\s]+/, $self->conf->{checkUserHiddenAttributes};
604  
605 foreach ( sort keys %$attrs ) {
606 push @$array_attrs,
607 { key => $_, value => $attrs->{$_} }
608 unless ( (
609 isHiddenAttr( $self->conf->{hiddenAttributes}, $_, @hidden )
610 && !$self->displayHiddenAttributesRule->( $req, $userData )
611 )
612 || ( !$attrs->{$_}
613 && !$self->displayEmptyValuesRule->( $req, $userData ) )
614 );
615 }
616  
617 return $array_attrs;
618 }
619  
620 sub _dispatchAttributes {
621 my ( $self, $attrs ) = @_;
622 my ( $grps, $mcrs, $others ) = ( [], [], [] );
623 my $macros = $self->{conf}->{macros};
624  
625 $self->logger->debug("Dispatch attributes...");
626 while (@$attrs) {
627 my $element = shift @$attrs;
628 $self->logger->debug( "Processing element: $element->{key} => "
629 . ( $element->{value} // '' ) );
630 my $ok = 0;
631 if ( $element->{key} eq 'groups' ) {
632 $self->logger->debug('Key "groups" found');
633 my $separator = $self->{conf}->{multiValuesSeparator};
634 my @tmp = split /\Q$separator/, $element->{value};
635 $grps = [ map { { value => $_ } } sort @tmp ];
636 next;
637 }
638 if (%$macros) {
639 foreach my $key ( sort keys %$macros ) {
640 if ( $element->{key} eq $key ) {
641 $self->logger->debug('Macro found');
642 push @$mcrs, $element;
643 $ok = 1;
644 last;
645 }
646 }
647 }
648 push @$others, $element unless $ok;
649 }
650  
651 # Sort real and spoofed attributes if required
652 if ( $self->sorted ) {
653 $self->logger->debug('Sort real and spoofed attributes...');
654 my ( $realAttrs, $spoofedAttrs ) = ( [], [] );
655 my $prefix = $self->prefix;
656 while (@$others) {
657 my $element = shift @$others;
658 $self->logger->debug( "Processing attribute $element->{key} => "
659 . ( $element->{value} // '' ) );
660 if ( $element->{key} =~ /^$prefix.+$/ ) {
661 push @$realAttrs, $element;
662 $self->logger->debug(' -> Real attribute');
663 }
664 else {
665 push @$spoofedAttrs, $element;
666 }
667 }
668 @$others = ( @$spoofedAttrs, @$realAttrs );
669 }
670  
671 return [ $grps, $mcrs, $others ];
672 }
673  
674 sub _removeKeys {
675 my ( $self, $attrs, $hidden, $msg, $mask ) = @_;
676 my $regex = '^(?:' . join( '|', split( /\s+/, $hidden ) ) . ')';
677 my @keys = grep /$regex/, keys %$attrs;
678  
679 $self->logger->debug($msg);
680 if ($mask) {
681 $self->userLogger->info('Hide some headers...');
682 foreach (@keys) {
683 $attrs->{$_} = '******' if $attrs->{$_} =~ /\w+/;
684 }
685 }
686 else {
687 $self->userLogger->info('Remove some headers...');
688 delete @$attrs{@keys};
689 }
690  
691 return $attrs;
692 }
693  
694 sub _concatHistory {
695 my ( $self, $history ) = @_;
696 my ( $success, $failed ) = ( [], [] );
697  
698 $self->logger->debug('Concatenate history...');
699 @$success = map {
700 my $element = $_;
701 my $utime = delete $element->{_utime};
702 {
703 utime => $utime,
704 values => join $self->conf->{multiValuesSeparator},
705 map "$_=$element->{$_}", sort keys %$element
706 }
707 } @{ $history->{successLogin} };
708  
709 @$failed = map {
710 my $element = $_;
711 my $utime = delete $element->{_utime};
712 {
713 utime => $utime,
714 values => join $self->conf->{multiValuesSeparator},
715 map "$_=$element->{$_}", sort keys %$element
716 }
717 } @{ $history->{failedLogin} };
718  
719 return [ $success, $failed ];
720 }
721  
722 1;