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

Hi there monks,

I've run into a strange problem: when I first login into my perl site,whos using CGI::Session to handle the sessions part, using FireFox or IE, the first login of the day returns me to the login screen again. The second time I try, I get in. Doing a little debugging on the login part I can see that the session is created on file in the directory I specified with all the right data in, the authentication part is correct but the browser doesn't see it.

Here is the code I used:
$s = new CGI::Session( "driver:file", undef, {Directory=>'/tmp/'} ) or + die CGI::Session->errstr; # the user's data $s->param('username',$user); $s->param('userid',$userid); $s->param('name',$name); $s->param('surname',$surname); $s->param('~logged-in',"true"); $ipaddr = $s->param('_SESSION_REMOTE_ADDR'); $hostname = qx#host $ipaddr |awk {'print \$5'}#; # verify the user's access level if($isadmin eq 1) { $s->param('isadmin',"true"); } else { $s->param('isadmin',"false"); $s->param('access',"11"); } # register the last login my $lastlogin = funcs::DB->dbgetuniq("SELECT access FR +OM users_access WHERE userid=\"$userid\" ORDER BY access DESC","acces +s"); $s->param('lastlogin',"$lastlogin"); $s->expire("~logged-in", "30m"); $s->expire('+6h'); # register the user access funcs::DB->dbdo("INSERT INTO users_access VALUES('','$ +userid','$ipaddr','$hostname',NOW())"); print $s->header(-location=>'http://mysite/');


Any ideas?

Replies are listed 'Best First'.
Re: CGI::Session login problems
by Anonymous Monk on Feb 27, 2009 at 12:53 UTC
    This is potentially dangerous.
    $ipaddr = $s->param('_SESSION_REMOTE_ADDR'); $hostname = qx#host $ipaddr |awk {'print \$5'}#;
    Turn on -Taint, then untaint $ipaddr, like
    $ipaddr = $1 if $s->param('_SESSION_REMOTE_ADDR') =~ /([\d.]+)/;
Re: CGI::Session login problems
by Anonymous Monk on Feb 27, 2009 at 12:46 UTC
Re: CGI::Session login problems
by Anonymous Monk on Feb 28, 2009 at 02:04 UTC
    Keep in mind that after setting the cookie (with the session ID, which I'm assuming you're doing), you're not going to receive that cookie in the same request as it's been set. I'm guessing: - User logs in - You set cookie - You try to display main page - You check for session ID in cookie - Cookie not yet set, fail - User tries again, since this is a new request, the cookie you previously set now is sent to the server and the login succeeds.
      Mistery solved:

      the session part was correctly configured; the problem was that I requested the login page at http://webpage/ and after the auth the login script redirected the user at http://webpage.domain. I suppose the cookie was valid only for a domain. My bad ;P