There is nothign wrong with having the database handle in a global whatsoever. This is my suggestion. In fact in the Mason book they even weigh the alternative, which is even worse. Personally, I maintain many mason sites, and I have at least two globals in every app, one for the dbh - $dbh - and one for the session - $s.
If you follow this design your root /autohandler should have this
<%shared>
## Create database handle
$dbh = DBI->connect(
q{dbi:Pg:dbname=contacts},
q{ecarroll},
"",
{AutoCommit=>0, RaiseError=>1, PrintError=>1}
) || die "Could not Connect to DB".$dbi::errstr;
$dbh->commit;
</%shared>
<%cleanup>
undef $S;
$dbh->commit;
</%cleanup>
Than in your /auth/autohandler or whatever, you should have something like
<%init>
## Verfiy we have a cookie with a _session_id
my $j = Apache2::Cookie::Jar->new($r);
my $c = $j->cookies('Dealermade');
unless ( defined $c ) {
Dealermade::Error::nice_error($m, 'E201');
}
## Verify we have session that matches cookies ID
my %APACHE_SESSION;
eval {
tie %APACHE_SESSION, 'Apache::Session::Postgres', $c->
+value, {
Handle => $dbh,
Commit => 1,
};
};
if ( $@ ) {
## No tuple with matching ID (form cookie), bogus data
+.
$dbh->rollback;
Dealermade::Error::nice_error($m, 'E301');
}
$S = \%APACHE_SESSION;
## Verify that the sessioned user still has an entry in the us
+ers table
## Save user information into $U by ref
$U = $dbh->selectrow_hashref(
q{ SELECT * FROM users WHERE pkid = ? }, {}, $APACHE_S
+ESSION{'pkid'}
);
if ( defined $U ) {
delete $U->{'password'};
}
else {
$dbh->rollback;
Dealermade::Error::nice_error($m, 'E501');
}
</%init>
And finally this in your Apache2 conf
PerlSetVar MasonAllowGlobals $dbh
PerlAddVar MasonAllowGlobals $U
PerlAddVar MasonAllowGlobals $S
PerlModule Apache::DBI
PerlRequire /etc/apache2/db.pl
PerlModule Dealermade::Error
PerlModule CGI
PerlModule Dealermade::Event
PerlModule Apache2::Request
PerlModule Apache2::Cookie
PerlModule Data::HTMLDumper
PerlModule DBIx::Abstract
PerlModule Apache::Session::Postgres
PerlModule Digest::SHA1
PerlModule Template
PerlModule DBI
PerlModule DBD::Pg
<LocationMatch "(\.html|\.mas)$">
SetHandler perl-script
PerlHandler HTML::Mason::ApacheHandler
</LocationMatch>
<Location "/auth_required/edit/">
SetHandler perl-script
PerlHandler HTML::Mason::ApacheHandler
</Location>
<Location "/auth_required/add/">
SetHandler perl-script
PerlHandler HTML::Mason::ApacheHandler
</Location>
Evan Carroll www.EvanCarroll.com
|