#!/usr/bin/perl -w

###
##
# admlogin
#
#  * Allow a user to login and set a login cookie.
#
# SDE, 20 Oct 2001 
#
# License: GPL.
##
###

use lib '../lib/';
use NoCat;
use strict;

my $authserv	= NoCat->auth_service( ConfigFile => $ENV{NOCAT} );
my $cgi		= $authserv->cgi;
my $params	= $cgi->Vars;

# Debug configuration setup.
$authserv->check_config(qw( 
    AdmLoginForm FatalForm LoginOKForm
    LoginGreeting LoginMissing LoginBadUser LoginBadPass
));

$authserv->log( 7, sprintf( "User %s from %s requests %s", 
    $params->{user} || "UNKNOWN", $cgi->remote_host, lc( $params->{mode} ) || "form" ) );

# Figure out which image button was clicked (since they don't have value="" attributes).
if (my ($button) = grep $params->{"mode_$_.x"}, qw( login skip logout )) {
    delete $params->{$_} for ( "mode_$button.x", "mode_$button.y" );
    $params->{mode} = $button;
}

# Have we filled in the form yet?  No?  If not, present one.
$authserv->display( AdmLoginForm => "LoginGreeting" ) unless $params->{mode};

# Are we just missing required fields?
$authserv->display( AdmLoginForm => "LoginMissing"   ) unless $params->{user} and $params->{pass};

# Does the login info match what we have on file?
my $user = $authserv->user->fetch( $params->{user} );

$authserv->display( AdmLoginForm => "LoginBadUser" ) unless $user->id;
$authserv->display( AdmLoginForm => "LoginBadPass" ) unless $user->authenticate( $params->{pass} );

# Set the login cookie.
$authserv->set_cookie( $user );

# Execute on the plan and tell a compelling story to the user.
$authserv->success( LoginOKForm => $params );

# Fin
