MuForm/Role/RequestToken.pm untested

filter: Statementstmt 0.0% 0 / 49 Branchbran 0.0% 0 / 14 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 14 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 86 SCAR 42.8
CC
8
Cov
0%
verify_token
56.0
validate__token
6.0
build_token_expiration_time
2.0
CRAP 72.0
1 package Data::MuForm::Role::RequestToken;
2 # ABSTRACT: Role to incluse a token for csrf protection
3 use Moo::Role;
4 use Data::MuForm::Meta;
5  
6 use Crypt::CBC;
7 use MIME::Base64 ('decode_base64', 'encode_base64');
8 use Try::Tiny;
9  
10 has 'token_expiration_time' => ( is => 'rw', lazy => 1, builder => 'build_token_expiration_time' );
11 sub build_token_expiration_time { '3600' }
12 has 'token_prefix' => ( is => 'rw', builder => 'build_token_prefix' );
13 sub build_token_prefix { '' }
14 has 'crypto_key' => ( is => 'rw', lazy => 1, builder => 'build_crypto_key' );
15 sub build_crypto_key { }
16 has 'crypto_cipher_type' => ( is => 'rw', buider => 'build_crypto_cipher_type' );
17 sub build_crypto_cipher_type { 'Blowfish' }
18 has 'cipher' => ( is => 'ro', lazy => 1, builder => 'build_cipher' );
19 sub build_cipher {
20 my $self = shift;
21 return Crypt::CBC->new(
22 -key => $self->crypto_key,
23 -cipher => $self->crypto_cipher_type,
24 -salt => 1,
25 -header => 'salt',
26 );
27 }
28  
29 has_field '_token' => (
30 type => 'Hidden',
31 required => 1,
32 order => 100,
33 );
34  
35 sub default__token {
36 my $self = shift;
37 return $self->get_token;
38 }
39  
40 sub validate__token {
41 my ( $self, $field ) = @_;
42  
43 unless ( $self->verify_token($field->value) ) {
44 $field->add_error();
45 }
46 }
47  
48 sub verify_token {
49 my ($self, $token) = @_;
50  
51 return undef unless($token);
52  
53 my $value = undef;
54 try {
55 $value = $self->cipher->decrypt(decode_base64($token));
56 if ( my $prefix = $self->token_prefix ) {
57 return undef unless ($value =~ s/^\Q$prefix\E//);
58 }
59 }
60 catch {};
61  
62 return undef unless defined($value);
63 return undef unless ( $value =~ /^\d+$/ );
64 return undef if ( time() > $value );
65  
66 return 1;
67 }
68  
69 sub get_token {
70 my $self = shift;
71  
72 my $value = $self->token_prefix . (time() + $self->token_expiration_time);
73 my $token = encode_base64($self->cipher->encrypt($value));
74 $token =~ s/[\s\r\n]+//g;
75 return $token;
76 }
77  
78  
79  
80 1;
81  
82 __END__
83  
84 =pod
85  
86 =encoding UTF-8
87  
88 =head1 NAME
89  
90 Data::MuForm::Role::RequestToken - Role to incluse a token for csrf protection
91  
92 =head1 VERSION
93  
94 version 0.04
95  
96 =head1 AUTHOR
97  
98 Gerda Shank
99  
100 =head1 COPYRIGHT AND LICENSE
101  
102 This software is copyright (c) 2017 by Gerda Shank.
103  
104 This is free software; you can redistribute it and/or modify it under
105 the same terms as the Perl 5 programming language system itself.
106  
107 =cut