Here's an example taken from one of my working apps that uses CG::Session, which I feel is a cleaner and better way to handle the cookie/session data. I had to strip out a few things for privacy reasons, but all of the key elements are there.
The login page
#!/usr/bin/perl
use warnings;
use strict;
use DBI;
use CGI;
use CGI::Session;
use HTML::Template;
use Crypt::PasswdMD5;
my $title = 'Email Administration Login';
my $cgi = CGI->new;
my $self = $cgi->url;
my %login = $cgi->Vars;
my $session = CGI::Session->new or die CGI::Session->errstr;
my $template = HTML::Template->new(
filename => '../../html/emadmin/login.t
+mpl',
associate => [$session],
die_on_bad_params => 0,
global_vars => 1,
cache => 0,
);
$session->clear if $cgi->param('logout');
$session->param('hostname', `hostname`);
if ( $cgi->param('Login') ) {
my $home = 'http://emailadmin.company.com/admin/search.pl';
print $cgi->redirect($home) if authenticated_user(\%login);
}
print $session->header;
print $template->output;
######################################################################
+##########
sub authenticated_user {
my $login = shift;
$session->param('login_failed',
'Invalid username, or password...Please try again'
+);
if ( defined $login->{'username'} && defined $login->{'password'}
+) {
my ($encrypted_pass, $roll, $name) = query_DB($login->{'userna
+me'});
if ( $encrypted_pass ) {
my $salt = substr($encrypted_pass, 3,8);
my $password = unix_md5_crypt( $login->{'password'}, $salt
+ );
if ( $password eq $encrypted_pass ) {
$session->clear('login_failed');
$session->param('logged_in', 1);
$template->param('logged_in', 1);
$session->param('admin', $login->{'username'});
$session->param('roll', $roll);
$session->param('gic', 1) if $roll eq 'admin';
return 1;
}
}
}
return 0;
}
The page/script it redirects to on successful login
#!/usr/bin/perl
use warnings;
use strict;
use DBI;
use CGI;
use CGI::Session;
use HTML::Template;
my $cgi = CGI->new;
my %form = $cgi->Vars;
my $session = CGI::Session->load;
if ($session->is_empty or $session->is_expired or !$session->param('lo
+gged_in')) {
my $login_page = 'http://emailadmin.company.com';
print $cgi->redirect($login_page);
}
print $cgi->header;
my $template = HTML::Template->new(filename => '../../html/emadmin/sea
+rch.tmpl',
associate => [$session],
global_vars => 1);
$template->param(title => 'Email Administration - Search Page');
$template->param(gic => 1) if $session->param('roll') eq 'admin';
if ( exists $form{'locate'} ) {
my @search_results = search_abook($form{searchfield}, $form{search
+value});
if ( @search_results ) {
$template->param(found => scalar @search_results);
$template->param(results => \@search_results);
}
else {
$template->param(not_found => 'Unable to locate any users matc
+hing your query');
}
}
print $template->output;