Skip to content
Snippets Groups Projects
AuthenticationToken.pm 1.47 KiB
Newer Older
package IdPAccountManager::AuthenticationToken;
Guillaume ROUSSE's avatar
Guillaume ROUSSE committed

use strict;
Guillaume ROUSSE's avatar
Guillaume ROUSSE committed

use base 'IdPAccountManager::DB::Object';

use Digest::MD5;
use POSIX qw(strftime);

Guillaume ROUSSE's avatar
Guillaume ROUSSE committed
__PACKAGE__->meta->setup(
    table   => 'authenticationtokens',

    columns => [
        id            => { type => 'bigserial', not_null => 1 },
        token         => { type => 'varchar', length => 50, not_null => 1 },
        email_address => { type => 'varchar', length => 200, not_null => 1 },
        sp_entityid   => { type => 'varchar', length => 200, not_null => 1 },
        creation_date => { type => 'integer' },
    ],

    primary_key_columns => [ 'id' ],

    unique_keys => [
        [ 'token' ],
        [ 'email_address', 'sp_entityid' ],
    ],
);

sub print {
    my ($self, $fd) = @_;
    $fd = \*STDOUT unless $fd;

    printf $fd
"AuthenticationToken ID=%s; token=%s; email_address=%s; sp_entityid=%s; creation_date=%s\n",
      $self->id(), $self->token(), $self->email_address(),
      $self->sp_entityid(),
      POSIX::strftime('%Y:%m:%d', localtime($self->creation_date()));
}

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

    # If no ID is defined, it is a new account
    if (! defined $self->id()) {
        $self->creation_date(time);
        $self->token(_generate_token($self->email_address()));
    }

    $self->SUPER::save();
}

sub _generate_token {
    my ($salt, $size) = @_;
    $size = 20 unless $size;

    # ID is based on time + PID
    return substr(Digest::MD5::md5_hex(time . $$ . $salt), -1 * $size);
}