package Apache::AuthTieDBI;

use strict;
use Apache::Constants qw(:common);
use Tie::DBI ();

sub handler {
    my $r = shift;
    
    # get user's authentication credentials
    my($res, $sent_pw) = $r->get_basic_auth_pw;
    return $res if $res != OK;
    my $user = $r->connection->user;
    
    my $reason = authenticate($r, $user, $sent_pw);
 
    if($reason) {
   	$r->note_basic_auth_failure;
   	$r->log_reason($reason, $r->filename);
   	return AUTH_REQUIRED;
    }
    return OK;
}

sub authenticate {
    my($r, $user, $sent_pw) = @_;

    # get configuration information
    my $dsn        = $r->dir_config('TieDatabase') || 'mysql:test_www';
    my $table_data = $r->dir_config('TieTable')    || 'users:user:passwd';
    my($table, $userfield, $passfield) = split ':', $table_data;
    
    $user && $sent_pw or return 'empty user names and passwords disallowed';
    
    tie my %DB, 'Tie::DBI', {
	db => $dsn, table => $table, key => $userfield,
    } or return "couldn't open database";

    $DB{$user} or return "invalid account";

    my $saved_pw = $DB{$user}{$passfield};
    $saved_pw eq crypt($sent_pw, $saved_pw) or return "password mismatch";

    # if we get here, all is well
    return "";
}

1;
__END__
