# -*- perl -*-

# Copyright (c) 2005 by Jeff Weisberg
# Author: Jeff Weisberg <argus @ tcp4me.com>
# Created: 2005-Dec-10 12:55 (EST)
# Function: 
#
# $Id: web_login.pl,v 1.2 2005/12/11 21:21:55 jaw Exp $

package Argus::Web;
use strict;
use vars qw($argusd %auth);

sub web_logout {
    my $me = shift;

    if( $me->{ci} ){
	delete $auth{$me->{ci}};
	sync_db();
    }
    $me->{co} = 'invalid';
    $me->heavy_redirect( $me->{q}->url() );
}

sub web_login {
    my $me = shift;
    my $q  = $me->{q};
    my( $emsg, $user );

    if( !defined &auth_user ){
	$me->create_auth( 'webanon', 'Top', 'root', 'staff', 'user' );
	my $func = $q->param('nextf') || 'page';
	my $home = $q->param('home') || 'Top';
	my $top  = 1;
	return $me->heavy_redirect( $me->{q}->url() . "?object=$home;func=$func;top=$top" );
    }
    
    if( $q->param('name') ){
	# authenticate user
	my @a;
	$user = $q->param('name');

	expire_auth();
	@a = auth_user( $user, $q->param('passwd') );

	if( @a ){
	    $me->create_auth( $user, @a );
	    my( $func, $home, $top );
	    $func = $q->param('nextf') || 'page';
	    if( $q->param('home') ){
		$home = $q->param('home');
		$top  = $q->param('top');
	    }else{
		$home = $a[0];
		$top  = 1;
	    }
	    return $me->heavy_redirect( $me->{q}->url() . "?object=$home;func=$func;top=$top" );
	}else{
	    $emsg = l10n('Authentication Failed');
	}
    }
    $me->web_login_form($emsg);
}

sub web_login_form {
    my $me = shift;
    my $emsg = shift;
    my( $q, $r );

    $q = $me->{q};
    $r = $argusd->command( func => 'logindata' ) || {};
    # no error if we fail to connect
    
    $me->startpage( l10n('Login'), undef, decode($r->{bkgimg}), decode($r->{style_sheet}), decode($r->{icon}) );

    print "<H2><FONT COLOR=\"#FF0000\">", l10n('ERROR'), ": $emsg</FONT></H2>\n" if $emsg;
    print decode($r->{header}), "\n";
    print "<B><I>", l10n("Please log in"), "...</I></B><BR>\n";
    print "<TABLE WIDTH=\"95%\" BORDER=1>\n<TR><TD VALIGN=TOP>\n";

    print $q->startform(), "\n";
    print "<INPUT TYPE=HIDDEN NAME=func VALUE=login>\n";
    print "<TABLE>\n";
    print "<TR><TD>", l10n("Username"), ": </TD><TD>", $q->textfield('name', '', 32, 32), "</TD></TR>\n";
    print "<TR><TD>", l10n("Password"), ": </TD><TD>", $q->password_field('passwd', '', 32, 32), "</TD></TR>\n";
    print "<TR><TD COLSPAN=2>", $q->submit(-name=>l10n('Login')), "</TD></TR>\n";
    print "</TABLE><P>\n";
    print $q->endform(), "\n";
    print "</TD></TR></TABLE>\n";
    print decode($r->{footer}), "\n";
    $me->endpage();
}


1;
