package POE::Component::YubiAuth;

use warnings;
use strict;

=head1 NAME

POE::Component::YubiAuth - Use Yubico Web Service API to check One Time Passwords

=cut

our $VERSION = '0.03';


=head1 SYNOPSIS

POE::Component::YubiAuth uses Yubico's public Web Service API to verify One Time Passwords
generated by Yubikey.

    use POE::Component::YubiAuth;

    # Get your API id and key at https://api.yubico.com/get-api-key/
    POE::Component::YubiAuth->spawn('<api id>', '<optionally api key>');

    # subref as callback
    POE::Kernel->post('yubi', 'verify', '<otp data>', sub {
        print Data::Dumper::Dumper($_[0]);
    });

    # session event as callback
    POE::Session->create(
        inline_states => {
            _start => sub {
                my ($kernel, $heap) = @_[KERNEL, HEAP];
                $kernel->post('yubi', 'verify', '<otp data>', 'dump');
                $kernel->alias_set('foo');
            },
            dump => sub {
                my ($kernel, $heap) = @_[KERNEL, HEAP];
                print Data::Dumper::Dumper($_[ARG0]);
                $kernel->alias_remove;
                $kernel->post('yubi', 'shutdown');
            },
        }
    );
    POE::Kernel->run();

=head1 CONSTRUCTOR

=head2 POE::Component::YubiAuth->spawn(<api id>, <api key>)

spawn() takes Yubico API ID and optionally API key as parameters and spawns a
POE session named 'yubi' that will respond to various events later:

    POE::Kernel->post('yubi', 'verify', ...);
        or
    $kernel->post('yubi', 'shutdown');

If API key is provided, verification requests will be signed with the key.

=cut

=head1 EVENTS

=head2 verify

verify() takes three parameters - One Time Password, a callback event and optional
callback data.

Callback can be a subroutine reference or a name of a POE event in the current
session. Examples on how to use both types of callbacks are provided in the
SYNOPSIS.

    POE::Kernel->post('yubi', 'verify', '<otp data>', sub {
        print Data::Dumper::Dumper(\@_);
    }, 'some callback data');

The callback will receive a hash reference with response from Yubico's server
and the provided callback data, which may be used to identify the response.

If the 'status' key in the response has the value 'OK', then the
verification process was successfull. If callback receives an undefined value
instead of a hash reference, then some strange error has occured (e.g. no
connection to the Yubico's server).

Please visit http://www.yubico.com/developers/api/ for more information.

=head2 shutdown

shutdown() terminates the 'yubi' session.

=cut


=head1 AUTHOR

Kirill Miazine, C<< <km@krot.org> >>

=head1 COPYRIGHT & LICENSE

Copyright 2010 Kirill Miazine.

This software is distributed under an ISC-style license, please see
<http://km.krot.org/code/license.txt> for details.

=cut

use POE::Session;
use POE::Component::Client::HTTP;
use HTTP::Request;
use MIME::Base64;
use Digest::HMAC_SHA1 qw(hmac_sha1);

sub spawn {
    my $proto = shift;
    my $class = ref($proto) || $proto;

    my $id = shift or die "Yubico ID is required\n";
    my $key = shift;

    POE::Session->create(
        inline_states => {
            _start => sub {
                my ($kernel, $heap) = @_[KERNEL, HEAP];
                $kernel->alias_set('yubi');
                POE::Component::Client::HTTP->spawn(Alias => '_yubi_ua');
            },
            _stop => sub { },
            shutdown => sub {
                my ($kernel, $heap) = @_[KERNEL, HEAP];
                POE::Kernel->post('_yubi_ua', 'shutdown');
                $kernel->alias_remove();
            },
            verify => sub {
                my ($kernel, $sender, $heap) = @_[KERNEL, SENDER, HEAP];
                my ($otp, $callback, $callback_data) = @_[ARG0, ARG1, ARG2];
                my $params = "id=$heap->{'id'}&otp=$otp&timestamp=1";
                if (my $key = $heap->{'key'}) {
                    $params .= '&h=' . encode_base64(hmac_sha1($params, decode_base64($key)), '');
                }
                my $req = HTTP::Request->new(GET =>
                    "http://api.yubico.com/wsapi/verify?$params"
                );
                $kernel->post('_yubi_ua', 'request', '_verify_cb', $req,
                              [$sender, $callback, $callback_data]);
            },
            _verify_cb => sub {
                my ($kernel, $heap) = @_[KERNEL, HEAP];
                my ($req, $res) = map { $_->[0] } @_[ARG0, ARG1];
                my ($sender, $callback, $callback_data) = @{$_[ARG0]->[1]};
                my $args;
                $args = {map { split /=/, $_, 2 } grep { /=/ } split /\r?\n/, $res->content}
                    if $res->is_success;
                if (ref $callback eq 'CODE') {
                    $callback->($args, $callback_data);
                } elsif (ref $callback) {
                    $callback->postback->($args, $callback_data);
                } else {
                    $kernel->post($sender, $callback, $args, $callback_data);
                }
            }
        },
        heap => {id => $id, key => $key},
    );
}

1; # End of POE::Component::YubiAuth
