| 1 | package Dancer::Plugin::UUID; | ||
| 2 | |||
| 3 | #ABSTRACT: Maintain unique identifiers for each visitor of the application. | ||
| 4 | |||
| 5 | |||
| 6 | use strict; | ||
| 7 | use warnings; | ||
| 8 | use feature ':5.10'; | ||
| 9 | use Dancer ':syntax'; | ||
| 10 | use Dancer::Plugin; | ||
| 11 | use Digest::SHA1 'sha1_hex'; | ||
| 12 | use Data::UUID; | ||
| 13 | |||
| 14 | # constants | ||
| 15 | my $uuid_cookie_name = 'dancer.uuid'; | ||
| 16 | my $drop_test_name = 'dancer.uuid.test'; | ||
| 17 | |||
| 18 | hook 'before' => sub { | ||
| 19 | |||
| 20 | # if Do Not Track, do nothing | ||
| 21 | return if request->env->{'HTTP_DNT'}; | ||
| 22 | |||
| 23 | # if we have a UUID already, return | ||
| 24 | my $uuid = cookies->{$uuid_cookie_name}; | ||
| 25 | return if defined $uuid; | ||
| 26 | |||
| 27 | # no UUID cookie is found, do we have the 'test cookie'? | ||
| 28 | if ( defined cookies->{$drop_test_name} ) { | ||
| 29 | |||
| 30 | # check the value, to make sure that's our cookie | ||
| 31 | my $expected = _build_test_cookie_value(); | ||
| 32 | |||
| 33 | # the test cookie has the expected value, we can drop our UUID cookie | ||
| 34 | if ( $expected eq cookies->{$drop_test_name}->value ) { | ||
| 35 | my $uuid_fact = Data::UUID->new; | ||
| 36 | $uuid = $uuid_fact->create(); | ||
| 37 | cookie $uuid_cookie_name => $uuid_fact->to_string($uuid), | ||
| 38 | expires => "3 years"; | ||
| 39 | } | ||
| 40 | } | ||
| 41 | |||
| 42 | # drop the test cookie, for the session | ||
| 43 | cookie $drop_test_name => _build_test_cookie_value(); | ||
| 44 | }; | ||
| 45 | |||
| 46 | register uuid => sub { | ||
| 47 | return _uuid_value(); | ||
| 48 | }; | ||
| 49 | |||
| 50 | hook 'before_template_render' => sub { | ||
| 51 | my $tokens = shift; | ||
| 52 | $tokens->{'dancer.uuid'} = _uuid_value(); | ||
| 53 | }; | ||
| 54 | |||
| 55 | # private | ||
| 56 | |||
| 57 | sub _build_test_cookie_value { | ||
| 58 | return sha1_hex( __FILE__ ); | ||
| 59 | } | ||
| 60 | |||
| 61 | sub _uuid_value { | ||
| 62 | if ( !request->env->{HTTP_DNT} ) { | ||
| 63 | my $uuid = cookies->{$uuid_cookie_name}; | ||
| 64 | return $uuid->value if defined $uuid; | ||
| 65 | } | ||
| 66 | undef; | ||
| 67 | } | ||
| 68 | |||
| 69 | register_plugin; | ||
| 70 | 1; | ||
| 71 | |||
| 72 | __END__ |