package QBit::Application::Model::Yandex::FlashCookie;

use qbit;

use base qw(QBit::Application::Model);

use Crypt::OpenSSL::RSA;
use MIME::Base64;

__PACKAGE__->mk_ro_accessors('rsapub');

my $PUBLIC_KEY = q{-----BEGIN PUBLIC KEY-----
MHwwDQYJKoZIhvcNAQEBBQADawAwaAJhAOic0tmjQnu3RJm1jh4OXxjpYjS4sHbO
voYLKpOZ2x8PjFfEql5Cpzp3IWZY3vwHk87ikq2a4LKX2Fyoij5OxIBEbDnsUcUJ
pA1ewuxv7nTgM5bAQ+dCH3VqFRo4ty0RJwIDAQAB
-----END PUBLIC KEY-----
};

sub init {
    my ($self) = @_;

    $self->SUPER::init();

    $self->{'rsapub'} = Crypt::OpenSSL::RSA->new_public_key($PUBLIC_KEY);
}

sub check {
    my ($self, $fuid) = @_;

    return FALSE unless $fuid;

    $self->timelog->start('Checking flash cookie');

    $fuid =~ tr!-_!+/!;

    my ($time_str, $rand_str, $sign_str) = ($fuid =~ /^(.{8})(.{8})\.(.*)$/);

    my $time = hex($time_str);
    my $rand = hex($rand_str);

    $self->timelog->start('Decoding sign');
    my $sign = substr(decode_base64($sign_str), 0, $self->rsapub->size());
    $self->timelog->finish();

    $self->timelog->start('Verifying sign');
    my $res = $self->rsapub->verify(pack("NN", $time, $rand), $sign);
    $self->timelog->finish();

    $self->timelog->finish();

    return $res;
}

TRUE;
