File Coverage

blib/lib/OpenID/Lite/Nonce.pm
Criterion Covered Total %
statement 45 45 100.0
branch 16 18 88.8
condition 3 3 100.0
subroutine 9 9 100.0
pod 0 4 0.0
total 73 79 92.4


line stmt bran cond sub pod time code
1             package OpenID::Lite::Nonce;
2              
3 3     3   1393 use strict;
  3         6  
  3         127  
4 3     3   16 use warnings;
  3         6  
  3         90  
5              
6 3     3   1957 use String::Random;
  3         7085  
  3         144  
7 3     3   2967 use POSIX;
  3         24784  
  3         25  
8 3     3   13784 use Time::Local;
  3         6532  
  3         1839  
9              
10             my $SKEW = 60 * 60 * 5;
11              
12             sub gen_nonce {
13 10     10 0 3987 my $class = shift;
14 10         15 my $t = shift;
15 10 100       103 $t = time() unless defined $t;
16 10         651 my $time = POSIX::strftime( q{%FT%TZ}, gmtime($t) );
17 10         52 my $random = String::Random->new;
18 10         267 my $salt = $random->randregex('[a-zA-Z0-9]{6}');
19 10         1938 return $time . $salt;
20             }
21              
22             sub split_nonce {
23 30     30 0 8151 my $class = shift;
24 30         76 my $nonce = shift;
25 30         39 my $pos = length(q{0000-00-00T00:00:00Z});
26 30         69 my $timestamp = substr( $nonce, 0, $pos );
27 30 100       147 return if length($timestamp) < $pos;
28 27 100       152 return unless $timestamp =~ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/;
29 24         28 my $time;
30 24         31 eval { $time = Time::Local::timegm($6, $5, $4, $3, $2 - 1, $1); };
  24         123  
31 24 100       4654 if ($@) { return; }
  1         7  
32 23         38 my $rest = substr( $nonce, $pos );
33 23         74 return ( $time, $rest );
34             }
35              
36             sub skew {
37 27     27 0 502 my ( $class, $new_skew ) = @_;
38 27 100       62 $SKEW = $new_skew if $new_skew;
39 27         167 return $SKEW;
40             }
41              
42             sub check_timestamp {
43 8     8 0 2739 my ( $class, $nonce_str, $allowed_skew, $now ) = @_;
44 8 50       30 $allowed_skew = $class->skew() unless defined $allowed_skew;
45 8 50       15 $now = time() unless defined $now;
46 8 100       18 my ( $stamp, $foo ) = $class->split_nonce($nonce_str)
47             or return 0;
48 7         22 my $past = $now - $allowed_skew;
49 7         9 my $future = $now + $allowed_skew;
50 7 100 100     49 return ( $past <= $stamp && $stamp <= $future ) ? 1 : 0;
51             }
52              
53             1;
54