| 1 | package Web::App::Session::Cookie; | ||
| 2 | # $Id: Cookie.pm,v 1.1 2009/03/29 10:12:26 apla Exp $ | ||
| 3 | |||
| 4 | use strict; | ||
| 5 | |||
| 6 | use CGI::Cookie; | ||
| 7 | |||
| 8 | use Digest::MD5; | ||
| 9 | |||
| 10 | use Web::App; | ||
| 11 | |||
| 12 | use Class::Easy; | ||
| 13 | |||
| 14 | sub detected_session { | ||
| 15 | my $pack = shift; | ||
| 16 | my $entity = shift; | ||
| 17 | |||
| 18 | my $app = Web::App->app; | ||
| 19 | |||
| 20 | my $request = $app->request; | ||
| 21 | my $session = $app->session; | ||
| 22 | |||
| 23 | my $cookies = CGI::Cookie->fetch; | ||
| 24 | |||
| 25 | my $cookie = $cookies->{$entity}; | ||
| 26 | |||
| 27 | return unless defined $cookie; | ||
| 28 | |||
| 29 | debug "cookie value is: '$cookie'"; | ||
| 30 | |||
| 31 | if ($session->no_parse_cookie) { | ||
| 32 | return $cookie->value; | ||
| 33 | } | ||
| 34 | |||
| 35 | my ($user, $expires, $hash) = split (':', $cookie->value); | ||
| 36 | |||
| 37 | my $chunk = "$user:$expires"; | ||
| 38 | my $digest_string = $session->salt.$chunk; | ||
| 39 | |||
| 40 | |||
| 41 | if (Digest::MD5::md5_hex ($digest_string) eq $hash and time < hex $expires) { | ||
| 42 | debug "user is: '$user'"; | ||
| 43 | return $user, $expires, $hash; | ||
| 44 | } else { | ||
| 45 | debug "hash for '$digest_string': received '$hash', but waiting for: ", | ||
| 46 | Digest::MD5::md5_hex ($digest_string), ", session expired"; | ||
| 47 | $session->expired (1); | ||
| 48 | return $user, $expires, $hash; | ||
| 49 | } | ||
| 50 | |||
| 51 | } | ||
| 52 | |||
| 53 | sub save { | ||
| 54 | my $class = shift; | ||
| 55 | my $entity = shift; | ||
| 56 | my @session = @_; | ||
| 57 | |||
| 58 | my $app = Web::App->app; | ||
| 59 | my $request = $app->request; | ||
| 60 | my $session = $app->session; | ||
| 61 | |||
| 62 | my $expires = time + 60*60; # one hour | ||
| 63 | my $hex_expires = sprintf '%x', $expires; | ||
| 64 | |||
| 65 | my $session_id = $session[0]; | ||
| 66 | |||
| 67 | # now we encrypt cookie | ||
| 68 | my $chunk = "$session_id:$hex_expires"; | ||
| 69 | my $digest_string = $session->salt.$chunk; | ||
| 70 | |||
| 71 | my $cookie = CGI::Cookie->new ( | ||
| 72 | -name => $entity, | ||
| 73 | -value => $chunk.':'.Digest::MD5::md5_hex ($digest_string), | ||
| 74 | -expires => '+10y', | ||
| 75 | ); | ||
| 76 | |||
| 77 | $app->response->headers->header ('Set-Cookie' => $cookie); | ||
| 78 | |||
| 79 | } | ||
| 80 | |||
| 81 | sub remove { | ||
| 82 | my $class = shift; | ||
| 83 | my $entity = shift; | ||
| 84 | |||
| 85 | my $app = Web::App->app; | ||
| 86 | |||
| 87 | my $cookie = CGI::Cookie->new ( | ||
| 88 | -name => $entity, | ||
| 89 | -value => '', | ||
| 90 | -expires => '-10y', | ||
| 91 | ); | ||
| 92 | |||
| 93 | $app->response->headers->header ('Set-Cookie' => $cookie); | ||
| 94 | |||
| 95 | } | ||
| 96 | |||
| 97 | |||
| 98 | 1; |