johnnywang has asked for the wisdom of the Perl Monks concerning the following question:

I have some static contents in a folder that I'd like to give user access to after they login. This is easy with htaccess. The problem is that I already have a login page, where I store some user information in the CGI::Session. For this particular directory of static contents, I'd like to check whether the user is logged in by checking the CGI::Session, and allow the user to read the files (could be different types: .pdf, .xls, .doc, etc.) if they are already logged in, otherwise send them to the login page. I used to do this in java, where I just write a servlet filter. Can I do this in perl? a simple cgi script, or a mod_perl? Thanks.
  • Comment on Protecting static contents in Apache with perl/mod_perl

Replies are listed 'Best First'.
Re: Protecting static contents in Apache with perl/mod_perl
by perrin (Chancellor) on Aug 20, 2005 at 17:58 UTC
    The equivalent in mod_perl would probably be a PerlAccessHandler or an Authen/Authz handler. There are extensive docs about this on the mod_perl site, and many examples on CPAN.
      perrin is right on the money. Here is some code from a PerlAuthenHandler I wrote that uses CGI::Session. (I deleted some of the irrelevant details but this shows how it can be done.)

      sub redir_auth { my $r = shift; $r->status( REDIRECT ); $r->header_out( Location => '/login.cgi?' ); return REDIRECT; } sub handler { my $r = shift; my $apr = Apache::Request->new( $r ); my $q = CGI->new; # let through if we're trying to login return OK if $r->uri =~ /login.cgi$/; # block if no session cookie or query my $asid = $q->cookie( 'asid' ) || $apr->param( 'asid' ) || 0; return redir_auth( $r ) unless $asid; # if we have a valid session, let the request pass through my $session = Alex::Session->new( $q ); $session->expire('+1h'); return OK if $session->param( "logged_in" ); # default return redir_auth( $r ); }