0

This is a follow up for this question Apache directory directive authentication based on Perl CGI::Session

 Alias /files /myData/all
<Directory /myData/all >
    RewriteEngine On
    RewriteBase /
    RewriteRule ^(.*)$ cgi-bin/checklogin.pl?url=/files/$1 [L,R]
    Options +Indexes
</Directory>

/files is a directory listing.

I edited the directive so that if a user goes to webserver/files/ they are redirected to checklogin.pl which checks for the existance of a session. If there is one it should redirect to the ?url if not it takes them to the loginpage.

The first part works. The redirect to $url causes a loop.

my $url = $cgi->param("url");
my $cookie = $cgi->cookie('mysession');
if(!$cookie){
        $session = new CGI::Session();
        print $session->redirect('/loginpage.html');
}else{
     # HOW DO I display folder or files now?
      $session  = new CGI::Session(undef, $cookie, {Directory=>'/tmp/'});
      print $session->redirect($url);
}

I am, obviously, getting a redirect loop error in Apache

This webpage has a redirect loop
Community
  • 1
  • 1
Jabda
  • 1,752
  • 5
  • 26
  • 54

1 Answers1

1

If you redirect every request to checklogin.pl, any requests made inside checklogin.pl will redirect to checklogin.pl, which will redirect to checklogin.pl, which will redirect to checklogin.pl...

Instead, why don't you make a master script with a logged_in function that you call with each request:

#!/usr/bin/perl -T

use strict;
use warnings;

use CGI;

sub logged_in {
    # Check session
}

my $q = CGI->new;

if (not logged_in()) {
    print $q->redirect('http://url/to/login.html'); # Need to use a full URL
}
else {
    # Do stuff
}
ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110
  • /files is not a script directly but contains files. Not scripts my session works fine for the rest of the site, I need a way to restrict access to directories – Jabda Jan 09 '14 at 21:47
  • 1
    This *does* restrict access to directories; users can't do anything that you don't put in the `else` block. I think what you're *really* asking is how to do user-based access control with Apache (since you want to show directory listings). You could, of course, print the contents of a particular directory in your Perl script. – ThisSuitIsBlackNot Jan 09 '14 at 22:07
  • How can I print the contents of a the directory in Perl so that the files are clickable – Jabda Jan 09 '14 at 22:51
  • 1
    If the user-supplied path maps to a directory (I say "maps" because users should not be able to control the exact location on your filesystem, just as with Apache's `Alias`), and the user has access to it, use `readdir` or [File::Find](http://perldoc.perl.org/File/Find.html) to get the directory contents and print a link to each one. If the path is a file, open it and print the contents. – ThisSuitIsBlackNot Jan 10 '14 at 15:33