package Net::OpenVPN::Manager::Plugin::InternalToken;

use namespace::autoclean;
use Moose;
use Net::OpenVPN::Manager::Plugin;

with 'Net::OpenVPN::Manager::Authenticable';
with 'Net::OpenVPN::Manager::2Authenticable';

has '+order' => (
    default => 4,
);

sub authenticate {
    my ($self, $client) = @_;

    return $self->_check_token($client);
}

sub authenticate_phase2 {
    my ($self, $client) = @_;

    return $self->_check_token($client);
}

sub _check_token {
    my ($self, $client) = @_;

    # Initial = no token from client
    # Authenticate = token valid
    # Expired = valid but expired
    # Invalid = failed to validate
 
    my $state = $client->get_env('session_state');

    if (!$state) {
        $self->log("auth-token not activated on openvpn server config", $client);
        return PLUG_FATAL;
    } elsif ($state eq "Authenticated") {
        $self->log("auth-token validated", $client);
        return PLUG_OK;
    } elsif ($state eq "Initial") {
        $self->log("auth-token not yet present", $client);
        return PLUG_NOOP;
    }

    # reject any other state (Invalid, Expired, ...)
    $self->log("auth-token invalid or expired", $client);
    return PLUG_FATAL;
}

__PACKAGE__->meta->make_immutable;

1;

__END__

=head1 NAME

Net::OpenVPN::Manager::Plugin::InternalToken - Check OpenVPN auth-token to validate reauthentication

=head1 SYNOPSIS

OpenVPN server must configure auth-token-directive to use external
authentication to allow this plugin to work. For example :

  auth-gen-token 0 3600 external-auth

=head1 Attributes

=cut
