1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Creating and validating Sessions in Perl CGI

Discussion in 'Perl' started by Rakish, Jul 27, 2006.

  1. Rakish

    Rakish New Member

    Joined:
    Jun 30, 2006
    Messages:
    25
    Likes Received:
    0
    Trophy Points:
    0
    Hi everyone, how are yall doing?

    I am developing a system where upon login (valid username and password) a session is started.


    $session = new CGI::Session("driver:File", undef, {Directory=>"/tmp"});
    $cookie = $cgi->cookie(CGISESSID => $session->id);
    print $cgi->header( -cookie=>$cookie );



    I want to check at top of every page if the session is still valid or the user has logged out. If the user has logged out they should be redirected to the login.pl page.

    $sid = $cgi->cookie("CGISESSID") || undef;
    $session = new CGI::Session(undef, $sid, {Directory=>'/tmp'});



    My concern is if someone has logged out, or the CGISESSID cookie is not set at all and if some one creates a cookie with name CGISESSID (using tools like firefox webdeveloper too) they could not be granted access.

    I have been trying to fix this for 2-3 days but its just not happening

    I would really apprecite if you could provide me with the script for creating session after successful login and validating this session at everypage.

    Thankyou all for your prompt help and concern.

    -Rakesh Gupta
     
  2. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    Hi Rakesh,
    Well, to block users from other IPs using a fake cookie we need to use use CGI::Session ( '-ip_match' );
    Well, I've created a login page an index page, with login/logout capabilities, trying viewing the index page without logging in.

    login.pl
    Code:
    #!/usr/bin/perl
      
      # login.pl
      use CGI;
      use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
      use CGI::Session ( '-ip_match' );
      
      $q = new CGI;
      
      $usr = $q->param('usr');
      $pwd = $q->param('pwd');
      
      if($usr ne '')
      {
          # process the form
          if($usr eq "demo" and $pwd eq "demo")
          {
              $session = new CGI::Session();
              print $session->header(-location=>'index.pl');
          }
          else
          {
              print $q->header(-type=>"text/html",-location=>"login.pl");
          }
      }
      elsif($q->param('action') eq 'logout')
      {
          $session = CGI::Session->load() or die CGI::Session->errstr;
          $session->delete();
          print $session->header(-location=>'login.pl');
      }
      else
      {
          print $q->header;
          print <
              <form method="post">
              Username: <input type="text" name="usr">
      
              Password: <input type="password" name="pwd">
      
      
              <input type="submit">
              </form>
      HTML
      }
    index.pl
    Code:
    #!/usr/bin/perl
      
      # index.pl
      use CGI;
      use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
      use CGI::Session ( '-ip_match' );
      
      $session = CGI::Session->load();
      $q = new CGI;
      
      if($session->is_expired)
      {
          print $q->header(-cache_control=>"no-cache, no-store, must-revalidate");
          print "Your has session expired. Please login again.";
     print "<br/><a href='login.pl>Login</a>";
      }
      elsif($session->is_empty)
      {
          print $q->header(-cache_control=>"no-cache, no-store, must-revalidate");
          print "You have not logged in";
      }
      else
      {
          print $q->header(-cache_control=>"no-cache, no-store, must-revalidate");
          print "<h2>Welcome";
          print "<a href='login.pl?action=logout'>Logout";
      }
      
    I hope this solves your problem.
     
    kkrvicky likes this.
  3. Rakish

    Rakish New Member

    Joined:
    Jun 30, 2006
    Messages:
    25
    Likes Received:
    0
    Trophy Points:
    0
    Thank you pradeep,

    The sessions are finally working for me..

    -Rakesh
     
  4. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    Try upgrading CGI::Session to the latest version!
     
  5. sundeep.kumar

    sundeep.kumar New Member

    Joined:
    Dec 20, 2007
    Messages:
    29
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Was MIS person once now just a student.
    hi pradeep i am not able to get this working could you please give some explanation about the variables and i am also concerned about checking the inputs agains a MYSQL database ..
     
  6. sundeep.kumar

    sundeep.kumar New Member

    Joined:
    Dec 20, 2007
    Messages:
    29
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Was MIS person once now just a student.
    hi pradeep it would be very heklpful if you could explain about this block of code

    if($usr ne '')
    {
    # process the form
    if($usr eq "demo" and $pwd eq "demo")
    {
    $session = new CGI::Session();
    print $session->header(-location=>'index.pl');
    }
    from login.pl ... please help me out ASAP ....
     
  7. venami

    venami New Member

    Joined:
    Dec 26, 2008
    Messages:
    195
    Likes Received:
    10
    Trophy Points:
    0
    Occupation:
    Software Professional
    Location:
    India, Tamil Nadu, Cuddalore
    Home Page:
    Here the value of $usr is populated from the text box(see the entire code of login.pl). So when the user submits to login without entering the username, the condition (part 1) will be FALSE and so again the login page appears.

    Suppose if some username has been typed, then it will be checked for authentication. In this code, the value "demo"(see part 2) is used for an example. In your case, you have to use the value that you get from the MySQL database.

    If the authentication is successful, then a session is created for that user and the page is redirected to the main index page using part 3.
     
  8. sundeep.kumar

    sundeep.kumar New Member

    Joined:
    Dec 20, 2007
    Messages:
    29
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Was MIS person once now just a student.
    Thank you venami .. i am able to run the code the code it's working now ... thanks once again for helping me out
     
  9. sundeep.kumar

    sundeep.kumar New Member

    Joined:
    Dec 20, 2007
    Messages:
    29
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Was MIS person once now just a student.
    friends sorry to bother again i would like to know how one can create a web page where a user log's in and thereafter unless and untill users logs out or session gets expired there should be no login page ... just like in gmail or yahoo .. i would like to know regarding this ..
     
  10. venami

    venami New Member

    Joined:
    Dec 26, 2008
    Messages:
    195
    Likes Received:
    10
    Trophy Points:
    0
    Occupation:
    Software Professional
    Location:
    India, Tamil Nadu, Cuddalore
    Home Page:
    Code:
    if(cond) //Check whether user logged in, using the session variables.
    {
       Display the home page without the "log in" link.
    }
    else //means user has not logged in.
    {
       Display the log in page.
    }
    
    Have this check in the "log in" page also and display the contents accordingly.

    Please see the previous posts in this thread. Pradeep has given you the code itself. :)
     
    Last edited: Jan 9, 2010
  11. sundeep.kumar

    sundeep.kumar New Member

    Joined:
    Dec 20, 2007
    Messages:
    29
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Was MIS person once now just a student.
    thanks pradeep i actually modified the code as follows
    login.pl
    Code:
    #!C:\perl\bin\perl.exe
    
    # Display script errors.
       use CGI;
       use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
       use CGI::Session ( '-ip_match' );
       use DBI;
       use DBD::mysql;
       
       $q = new CGI;
           $usr = $q->param('name');
           $pwd = $q->param('password');
    
    	my $db="disease";
    	my $host="localhost";
    	my $user="root";
    	my $password="mysql1234"; 
    
    	#connect to MySQL database
    	
    	my $dbh = DBI->connect('DBI:mysql:disease;host=localhost','root', 'mysql1234', { RaiseError => 1 } );
    	my $query = new CGI;
    	
    	# matching user input data against database 
    
    	my $sth = $dbh->prepare("select * from user where login_name = '$usr' AND password = '$pwd'")or &dbdie; 
    	$sth->execute() or &dbdie; 
    	my $result = $sth ->execute();
    
    
      if($usr ne '')
      {
       # process the form
          if($result eq 1)
          {
              $session = new CGI::Session();
              print $session->header(-location=>'index.pl');
          }
          else
          {
    		print $q->header(-type=>"text/html",-location=>"http://localhost/database3/");
    		print "Wrong username/password ";
    		print "click here to <a href='http://localhost/cgi-bin/db-cgi/register.cgi'> Register </a>";
          }
       }
      elsif($q->param('action') eq 'logout')
      {
          $session = CGI::Session->load() or die CGI::Session->errstr;
          $session->delete();
          print $session->header(-location=>"http://localhost/database3/");
    	  print "Wrong username/password ";
    	  print "click here to <a href='http://localhost/cgi-bin/db-cgi/register.cgi'> Register </a>";
      }
      else
      {
      
      print $q->header(-type=>"text/html",-location=>"http://localhost/database3/");
      print "Thank you for visiting Bionteq Website";
      }
    

    >>>>>>>>>>>>>>>>>>>>>>>>>>
    and index.pl as follows
    Code:
    #!C:\perl\bin\perl.exe
    
    # Display script errors.
      use CGI::Carp qw(fatalsToBrowser);
      use CGI;
      use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
      use CGI::Session ( '-ip_match' );
      
      #print "Content-type: text/html\n\n";
      
      $session = CGI::Session->load();
      $q = new CGI; 	
      
    # Begin the page.
      print "Content-type: text/html\n\n";
      
      if($session->is_expired)
      {
          print $q->header(-cache_control=>"no-cache, no-store, must-revalidate");
          print "Your session has expired. Please login again.";
     print "<br/><a href='http://localhost/database/login.html'>Login</a>";
      }
      elsif($session->is_empty)
      {
          print $q->header(-cache_control=>"no-cache, no-store, must-revalidate");
          print "You have not logged in";
      }
      else
      {
          my $url="http://localhost/database3/home_page.html";
    	  my $t=1; # time until redirect activates
    	  print "<META HTTP-EQUIV=refresh CONTENT=\"$t;URL=$url\">\n";
      }
      
        
    # End of script.
    
    now the problem that i am facing is even after login in when i click on home in home_page.html i am getting default.html page (one which has login form).

    Please tell me where i am going wrong .. if possible also give me a brief description about it .
     
    Last edited by a moderator: Jan 12, 2010
  12. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    Please check the HTML file home_page.html which might have some META-refresh tag.
     
  13. kkrvicky

    kkrvicky New Member

    Joined:
    Feb 16, 2016
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    The login logic help me lot..thanks Pradeep!
     
  14. kkrvicky

    kkrvicky New Member

    Joined:
    Feb 16, 2016
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Hi Pradeep,

    i have some problem while logout from the target page, my target page has frameset and divided into three part when add the tag ‘print "<a href='login.pl?action=logout'>Logout";’ into any frame then that frame getting cleared (plan frame) and not redirecting to login page. Could you please able suggest on this.

    Thanks,
     

Share This Page