./TravEpi/SimpleRulesBase/SimpleAuthenticator.pm


package MGH_Biostat::TravEpi::SimpleRulesBase::SimpleAuthenticator;
use Modern::Perl '2012';
use MIME::Base64;

# This is *heavily* based on Plack::Middleware::Auth::Basic.
# as in, completely stolen from there.

sub new {
    my $class = shift;
    my ( $realm, $user, $pass ) = @_;

    my $self = {
        'realm' => $realm,
        'user'  => $user,
        'pass'  => $pass,
    };
    return bless $self, $class;
}

sub auth {
    my $self = shift;
    my ($env) = @_;

    my $auth = $env->{HTTP_AUTHORIZATION}
      or return 0;

    if ( $auth =~ m/^Basic (.*)$/i ) {
        my ( $user, $pass ) = split /:/, ( MIME::Base64::decode($1) || ':' ), 2;
        $pass = '' unless defined $pass;
        return ( ( $user eq $self->{'user'} ) and ( $pass eq $self->{'pass'} ) )
    }
    else {
        return 0;
    }
}

sub unauth {
    my $self = shift;
    my $body = 'Authorization required';
    return [
        401,
        [
            'Content-Type'     => 'text/plain; charset=utf-8',
            'Content-Length'   => length $body,
            'WWW-Authenticate' => 'Basic realm="' . ( $self->{'realm'} || "restricted area" ) . '"'
        ],
        [ $body ],
    ];
}

1;