blib/lib/Lemonldap/NG/Portal/Lib/Notifications/JSON.pm untested

filter: Statementstmt 0.0% 0 / 253 Branchbran 0.0% 0 / 106 Conditioncond 0.0% 0 / 37 MC/DCmcdc 0.0% 0 / 22 Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 435 CC 54 SCAR 54.6
CC
54
Cov
0%
getNotifBack
462.0
notificationServer
210.0
checkForNotifications
156.0
CRAP 234.3
1 package Lemonldap::NG::Portal::Lib::Notifications::JSON;
2  
3 use strict;
4 use Mouse;
5 use JSON qw(from_json);
6 use POSIX qw(strftime);
7  
8 our $VERSION = '2.23.0';
9  
10 no warnings 'redefine';
11  
12 # Lemonldap::NG::Portal::Main::Plugin provides addAuthRoute() and
13 # addUnauthRoute() methods in addition of Lemonldap::NG::Common::Module.
14 extends 'Lemonldap::NG::Portal::Main::Plugin';
15  
16 # PROPERTIES
17  
18 # Underlying notifications storage object (File, DBI, LDAP,...)
19 has notifObject => ( is => 'rw' );
20  
21 # INITIALIZATION
22  
23 sub init {
24 return 1;
25 }
26  
27 # Search for notifications and if any, returns HTML fragment.
28 sub checkForNotifications {
29 my ( $self, $req ) = @_;
30  
31 # Look for pending notifications in database
32 my $uid = $req->sessionInfo->{ $self->notifObject->notifField };
33 my ( $notifs, $forUser ) = $self->notifObject->getNotifications($uid);
34 my $form;
35 unless ($notifs) {
36 $self->logger->info("No notification found");
37 return 0;
38 }
39  
40 # Transform notifications
41 my $i = 0; # Files count
42 my @res;
43 my $now = strftime "%Y-%m-%d", localtime;
44  
45 foreach my $file ( values %$notifs ) {
46 my $json = eval { from_json( $file, { allow_nonref => 1 } ) };
47 $self->userLogger->warn(
48 "Bad JSON file: a notification for $uid was not done ($@)")
49 if ($@);
50 my $j = 0; # Notifications count
51 $json = [$json] unless ( ref $json eq 'ARRAY' );
52 LOOP: foreach my $notif ( @{$json} ) {
53  
54 # Get the reference
55 my $reference = $notif->{reference};
56 $self->logger->debug("Get reference: $reference");
57  
58 # Check it in session
59 if ( exists $req->{sessionInfo}->{"notification_$reference"} ) {
60  
61 # The notification was already accepted
62 $self->logger->debug(
63 "Notification $reference was already accepted");
64 next LOOP;
65 }
66  
67 # Check date
68 my $date = $notif->{date};
69 $self->logger->debug("Get date: $date");
70 unless ( $date and $date =~ /\b\d{4}-\d{2}-\d{2}\b/ ) {
71 $self->logger->error('Malformed date');
72 next LOOP;
73 }
74 unless ( $date le $now ) {
75 $self->logger->debug('Notification date not reached');
76 next LOOP;
77 }
78  
79 # Check condition if any
80 if ( my $condition = $notif->{condition} ) {
81 $self->logger->debug("Get condition $condition");
82 $condition = $self->p->HANDLER->substitute($condition);
83 unless ( $condition = $self->p->HANDLER->buildSub($condition) )
84 {
85 $self->logger->error( 'Notification condition error: '
86 . $self->p->HANDLER->tsv->{jail}->error );
87 next LOOP;
88 }
89 unless ( $condition->( $req, $req->sessionInfo ) ) {
90 $self->logger->debug(
91 'Notification condition not authorized');
92 next LOOP;
93 }
94 }
95 push @res, $notif;
96 $j++;
97 }
98  
99 # Go to next file if no notification found
100 next unless $j;
101 $i++;
102 }
103 @res =
104 sort { $a->{date} cmp $b->{date} or $a->{reference} cmp $b->{reference} }
105 @res;
106 $form .= $self->toForm( $req, @res );
107  
108 # Stop here if nothing to display
109 return 0 unless $i;
110 $self->userLogger->info("$i pending notification(s) found for $uid");
111  
112 # Returns HTML fragment
113 return $form;
114 }
115  
116 # Search for accepted notification and if any, returns HTML fragment.
117 sub viewNotification {
118 my ( $self, $req, $ref, $epoch ) = @_;
119  
120 # Look for accepted notifications in database
121 my $uid = $req->userData->{ $self->notifObject->notifField };
122 my ( $notifs, $forUser ) =
123 $self->notifObject->getAcceptedNotifs( $uid, $ref );
124 my $form;
125 unless ($notifs) {
126 $self->logger->info("No accepted notification found");
127 return 0;
128 }
129  
130 # Transform notifications
131 my $i = 0; # Files count
132 my @res;
133  
134 foreach my $file ( values %$notifs ) {
135 my $json = eval { from_json( $file, { allow_nonref => 1 } ) };
136 $self->userLogger->warn(
137 "Bad JSON file: a notification for $uid was not done ($@)")
138 if ($@);
139 my $j = 0; # Notifications count
140 $json = [$json] unless ( ref $json eq 'ARRAY' );
141 LOOP: foreach my $notif ( @{$json} ) {
142  
143 # Get the reference
144 my $reference = $notif->{reference};
145 $self->logger->debug("Get reference: $reference");
146  
147 # Check it in session
148 unless ( exists $req->userData->{"notification_$reference"}
149 and $req->userData->{"notification_$reference"} eq $epoch
150 and $reference eq $ref )
151 {
152  
153 # The notification is not already accepted
154 $self->logger->debug(
155 "Notification $reference is not already accepted");
156 next LOOP;
157 }
158 push @res, $notif;
159 $j++;
160 }
161  
162 # Go to next file if no notification found
163 next unless $j;
164 $i++;
165 }
166 $form .= $self->toForm( $req, @res );
167  
168 # Stop here if nothing to display
169 return 0 unless $i;
170 $self->userLogger->info("$i accepted notification(s) found for $uid");
171  
172 # Returns HTML fragment
173 return $form;
174 }
175  
176 sub getNotifBack {
177 my ( $self, $req, $name ) = @_;
178  
179 # Search for Lemonldap::NG cookie (ciphered)
180 my $id;
181 return $self->p->sendError( $req, 'No cookie found', 401 )
182 unless ( $id = $req->cookies->{ $self->{conf}->{cookieName} } );
183  
184 if ( $req->param('cancel') ) {
185 $self->logger->debug('Cancel called -> remove ciphered cookie');
186 $req->addCookie(
187 $self->p->genDomainCookie(
188 $req,
189 name => $self->conf->{cookieName},
190 value => 0,
191 secure => $self->conf->{securedCookie},
192 expires => 'Wed, 21 Oct 2015 00:00:00 GMT'
193 )
194 );
195 $req->mustRedirect(1);
196 return $self->p->do( $req, [] );
197 }
198  
199 # Look if all notifications have been accepted.
200 # If not, redirect to Portal
201  
202 # Try to decrypt Lemonldap::NG ciphered cookie
203 $id = $self->p->HANDLER->tsv->{cipher}->decrypt($id)
204 or
205 return $self->p->sendError( $req, 'Unable to decrypt ciphered id', 400 );
206  
207 # Check that session exists
208 $req->userData( $self->p->HANDLER->retrieveSession( $req, $id ) )
209 or return $self->p->sendError( $req, 'Unknown session', 401 );
210  
211 # Restore data
212 $self->p->importHandlerData($req);
213 my $uid = $req->sessionInfo->{ $self->notifObject->notifField };
214  
215 # ALL notifications are returned here => Need to check active ones only
216 my ( $notifs, $forUser ) =
217 eval { $self->notifObject->getNotifications($uid) };
218 return $self->p->sendError( $req, $@, 500 ) if ($@);
219  
220 if ($notifs) {
221  
222 # Get accepted notifications
223 my ( $refs, $checks ) = ( {}, {} );
224 my $prms = $req->parameters;
225 foreach ( keys %$prms ) {
226 my $v = $prms->{$_};
227 if (s/^reference//) {
228 $refs->{$v} = $_;
229 }
230 elsif ( s/^check// and /^(\d+x\d+)x(\d+)$/ and $v eq 'accepted' ) {
231 push @{ $checks->{$1} }, $2;
232 }
233 }
234  
235 my $result = 1;
236 my $now = strftime "%Y-%m-%d", localtime;
237 foreach my $fileName ( keys %$notifs ) {
238 my $file = $notifs->{$fileName};
239 my $fileResult = 1;
240 my $json = from_json( $file, { allow_nonref => 1 } );
241 $json = [$json] unless ( ref $json eq 'ARRAY' );
242  
243 # Get pending notifications and verify that they have been accepted
244 LOOP: foreach my $notif (@$json) {
245  
246 # Get the reference
247 my $reference = $notif->{reference};
248 $self->logger->debug("Get reference: $reference");
249  
250 # Check it in session
251 if ( exists $req->{sessionInfo}->{"notification_$reference"} ) {
252  
253 # The notification was already accepted
254 $self->logger->debug(
255 "Notification $reference was already accepted");
256 next LOOP;
257 }
258  
259 # Check date
260 my $date = $notif->{date};
261 $self->logger->debug("Get date: $date");
262 unless ( $date and $date =~ /\b\d{4}-\d{2}-\d{2}\b/ ) {
263 $self->logger->error('Malformed date');
264 next LOOP;
265 }
266 unless ( $date le $now ) {
267 $self->logger->debug('Notification date not reached');
268 $fileResult = 0; # Do not delete notification
269 next LOOP;
270 }
271  
272 # Check condition if any
273 if ( my $condition = $notif->{condition} ) {
274 $self->logger->debug("Get condition $condition");
275 $condition = $self->p->HANDLER->substitute($condition);
276 unless ( $condition =
277 $self->p->HANDLER->buildSub($condition) )
278 {
279 $self->logger->error( 'Notification condition error: '
280 . $self->p->HANDLER->tsv->{jail}->error );
281 next LOOP;
282 }
283 unless ( $condition->( $req, $req->sessionInfo ) ) {
284 $self->logger->debug(
285 'Notification condition not authorized');
286 $fileResult = 0; # Do not delete notification
287 next LOOP;
288 }
289 }
290  
291 # Check if this pending notification has been seen
292 if ( my $refId = $refs->{$reference} ) {
293  
294 # Verity that checkboxes have been checked
295 if ( $notif->{check} ) {
296 $notif->{check} = [ $notif->{check} ]
297 unless ( ref( $notif->{check} ) eq 'ARRAY' );
298 if ( my $toCheckCount = @{ $notif->{check} } ) {
299 unless ($checks->{$refId}
300 and $toCheckCount == @{ $checks->{$refId} } )
301 {
302 $self->userLogger->notice(
303 "$uid has not accepted notification $reference"
304 );
305 $result = $fileResult = 0;
306 next LOOP;
307 }
308 }
309 }
310 }
311 else {
312 # Current pending notification has not been found in
313 # request
314 $self->logger->debug(
315 'Current pending notification has not been found');
316 $result = $fileResult = 0;
317 next LOOP;
318 }
319  
320 # Register acceptation
321 $self->userLogger->notice(
322 "$uid has accepted notification $reference");
323 $self->p->updatePersistentSession( $req,
324 { "notification_$reference" => time() } );
325 $self->logger->debug(
326 "Notification $reference registered in persistent session");
327 }
328  
329 # Notifications accepted for this file, delete it unless it's a wildcard
330 if ( $fileResult and exists $forUser->{$fileName} ) {
331 $self->logger->debug("Notification file deleted");
332 $self->notifObject->delete($fileName);
333 }
334 }
335 unless ($result) {
336  
337 # One pending notification has been found and not accepted,
338 # restart process to display pending notifications
339 # TODO: is it a good idea to launch all 'endAuth' subs ?
340 $self->logger->debug(
341 'Pending notification has been found and not accepted');
342 return $self->p->do( $req, [ @{ $self->p->endAuth } ] );
343 }
344  
345 # All pending notifications have been accepted, restore cookies and
346 # launch 'controlUrl' to restore "urldc" using do()
347 $self->logger->debug('All pending notifications have been accepted');
348 $self->p->rebuildCookies($req);
349 return $self->p->do( $req, [ 'controlUrl', @{ $self->p->endAuth } ] );
350 }
351 else {
352 # No notifications checked here, this entry point must not be called.
353 # Redirecting to portal
354 $self->logger->debug('No notifications checked');
355 $req->mustRedirect(1);
356 return $self->p->do( $req, [] );
357 }
358 }
359  
360 sub toForm {
361 my ( $self, $req, @notifs ) = @_;
362 my $i = 0;
363 @notifs = map {
364 $i++;
365 if ( $_->{check} ) {
366 $_->{check} = [ $_->{check} ]
367 unless ( ref( $_->{check} ) eq 'ARRAY' );
368 my $j = 0;
369 $_->{check} =
370 [ map { $j++; { id => '1x' . $i . 'x' . $j, value => $_ } }
371 @{ $_->{check} } ];
372 }
373 if ( $_->{text} ) {
374 $_->{text} =~ s/\$(\w+)/$req->{sessionInfo}->{$1} || ''/ge;
375 }
376 $_->{id} = "1x$i";
377 $_;
378 } @notifs;
379 return $self->loadTemplate( $req, 'notifinclude',
380 params => { notifications => \@notifs } );
381 }
382  
383 sub notificationServer {
384 my ( $self, $req, @args ) = @_;
385 $self->p->logger->debug("REST request for notifications");
386 return $self->p->sendError( $req, 'Only JSON requests here', 400 )
387 unless ( $req->wantJSON );
388 $self->p->logger->debug( "JSON content: " . $req->content );
389 my ( $res, $err );
390 if ( $req->method =~ /^POST$/i ) {
391 $self->p->logger->debug("POST request");
392 ( $res, $err ) = eval {
393 $self->notifObject->newNotification( $req->content,
394 $self->conf->{notificationDefaultCond} );
395 };
396 return $self->p->sendError( $req, $@, 500 ) if ($@);
397 }
398 elsif ( $req->method =~ /^GET$/i ) {
399 $self->p->logger->debug("GET request");
400 my ( $uid, $ref ) = @args;
401 my $notifs;
402 ( $notifs, $err ) =
403 eval { $self->notifObject->getNotifications($uid) };
404 return $self->p->sendError( $req, $@, 500 ) if ($@);
405 $res = [];
406 foreach my $notif ( keys %$notifs ) {
407 $self->p->logger->debug("Found notification $notif");
408 my $json =
409 eval { from_json( $notifs->{$notif}, { allow_nonref => 1 } ) };
410 return $self->p->sendError( $req, "Unable to decode JSON file: $@",
411 400 )
412 if ($@);
413 $self->p->logger->debug(
414 "Notification $notif: " . $notifs->{$notif} );
415 if ($ref) {
416 push( @$res,
417 map { "$_" => $json->{$_} },
418 split /\s+/,
419 $self->conf->{notificationServerSentAttributes} )
420 if ( $json->{reference} =~ /^$ref$/ );
421 }
422 else {
423 push @$res,
424 {
425 "uid" => $json->{uid},
426 "reference" => ( $json->{reference} || $json->{ref} )
427 };
428 }
429 }
430 }
431 elsif ( $req->method =~ /^DELETE$/i ) {
432 $self->p->logger->debug("DELETE request");
433 my $uid = $req->params('uid');
434 my $ref = $req->params('reference');
435 return $self->p->sendError( $req,
436 "Missing parameters -> uid: $uid / ref: $ref", 400 )
437 unless ( $uid and $ref );
438 ( $res, $err ) =
439 eval { $self->notifObject->deleteNotification( $uid, $ref ); };
440 return $self->p->sendError( $req, $@, 500 ) if ($@);
441 }
442 else {
443 return $self->p->sendError( $req, "Unknown HTTP method: $req->method",
444 400 );
445 }
446 return $self->p->sendError( $req, ( $err ? $err : 'Bad request' ), 400 )
447 unless ($res);
448 return $self->p->sendJSONresponse( $req, { result => $res } );
449 }
450  
451 1;