/lib/perl/Blerg-Database/t/auth.t
use File::Path qw/remove_tree/;
use strict;
use warnings;

use Test::More tests => 21;
BEGIN { use_ok('Blerg::Database') };

### Setup
my $test_user = 'barfy';
my $test_dir = "/tmp/blerg_test_$$";
mkdir $test_dir;
chdir $test_dir;
mkdir 'data';
mkdir 'hash_tags';
mkdir 'ref_tags';

$ENV{BLERG_PATH} = $test_dir;
Blerg::Database::init();

my ($ptr, $password, $n);
$password = 'blargh';
$n = 0;

$ptr = Blerg::Database->open($test_user);
$ptr->close;

### Auth (C interface)
is(   Blerg::Database::auth_set_password($test_user, $password), 1 );
isnt( Blerg::Database::auth_set_password('fakeuser', $password), 1 );

is(   Blerg::Database::auth_check_password($test_user, $password), 1 );
isnt( Blerg::Database::auth_check_password('fakeuser', $password), 1 );
isnt( Blerg::Database::auth_check_password($test_user, 'wrongpass'), 1 );

my $token = Blerg::Database::auth_login($test_user, $password);
ok( defined $token );
ok( length($token) == 32 );
ok( Blerg::Database::auth_check_token($test_user, $token) );
isnt( Blerg::Database::auth_check_token($test_user, 'badtoken'), 1 );
isnt( Blerg::Database::auth_check_token('fakeuser', $token), 1 );
ok( Blerg::Database::auth_logout($test_user, $token) );

$token = Blerg::Database::auth_login($test_user, 'wrongpass');
ok( not defined $token );

$token = Blerg::Database::auth_login('wronguser', $password);
ok( not defined $token );

isnt( Blerg::Database::auth_logout($test_user, 'badtoken'), 1 );
isnt( Blerg::Database::auth_logout('fakeuser', 'badtoken'), 1 );

my $counter1 = Blerg::Database::auth_get_counter('fakeuser');
ok( !defined $counter1 );

$counter1 = Blerg::Database::auth_get_counter($test_user);
ok( defined $counter1 );
isnt( $counter1, 0);

Blerg::Database::auth_set_password($test_user, $password . 'X');
ok( Blerg::Database::auth_check_password($test_user, $password . 'X') );

my $counter2 = Blerg::Database::auth_get_counter($test_user);
ok( $counter1 != $counter2 );

END {
	chdir;
	remove_tree "/tmp/blerg_test_$$";
}