Auth-GoogleAuthenticator

 view release on metacpan or  search on metacpan

lib/Auth/GoogleAuthenticator.pm  view on Meta::CPAN

package Auth::GoogleAuthenticator;
use strict;
use Authen::OATH;
use Convert::Base32;
use Math::Random::MT 'rand'; # to generate good passcodes
use URI::Escape;

use vars qw($VERSION);
$VERSION= '0.03';

sub new {
    my ($class, %args) = @_;
    if( $args{ secret_base32 }) {
        $args{ secret } = decode_base32( delete $args{ secret_base32 });
    };
    
    $args{ auth } ||= Authen::OATH->new();
    bless \%args => $class;
}

sub auth { $_[0]->{auth} };

sub registration_qr_code {
    my ($self, $label, $type) = @_;
    # if we have an OTP, dislay the QRCode to the user
    require Imager::QRCode;
    my $qrcode = Imager::QRCode->new(
        size => 4,
        margin => 4,
        version => 1,
        level => 'M',
        casesensitive => 1,
    );
    my $img = $qrcode->plot($self->registration_url($label, $type));
    $img->write( data => \my $res, type => 'png' );
    $res
}

sub registration_key {
    return encode_base32( $_[0]->{secret} );
}

sub totp {
    my ($self, $ts) = @_;
    $self->auth->totp( $self->{secret}, $ts )
};

sub registration_url {
    my ($self, $label, $type) = @_;
    $type ||= 'totp';
    $label= uri_escape($label);
    return "otpauth://$type/$label?secret=" . $self->registration_key
}

sub verify {
    my ($self, $code, $ts) = @_;
    return ($code and
        $self->totp( $ts ) == $code);
}

1;

=head1 WORKFLOW

=over 4

=item *

Install Google Authenticator

=item *

Visit the "Install Two Factor Authentication" page

=item *

Display the secret key there

 view all matches for this distribution
 view release on metacpan -  search on metacpan

( run in 2.666 seconds using v1.00-cache-2.02-grep-82fe00e-cpan-1925d2aa809 )