Link to home
Start Free TrialLog in
Avatar of bigbong00
bigbong00Flag for United Kingdom of Great Britain and Northern Ireland

asked on

Perl Images/Redirection and Javascript

I have this script below. I'm new to perl so this is pretty basic. Its a simple login

#!\xampp\perl\bin\perl.exe
# Academics are us Admin Login

use CGI;

$upload_form = new CGI;
print $upload_form->header,
        $upload_form->start_html('Login');

print $upload_form->start_form();

## for testing purpose
print $upload_form->param, $upload_form->p();
print $upload_form->param_fetch('username')->[0],
                                 $upload_form->p();
print $upload_form->param_fetch('passwd')->[0],
                                 $upload_form->p();


$upload_form->import_names('upload_form_names');

if (!$upload_form_names::username or
            !$upload_form_names::passwd) {
    printLogin();
    }
elsif ($upload_form_names::username eq 'User'
        and $upload_form_names::passwd  eq 'password') {
    # The below line is where you would have this script
    # set a cookie and forward the user to the admin area.
    print 'Authorised Login';  }
else {
    # The below line where you would put
    # whatever you want for bad user/pass
    # combinations.
    print 'unAuthorised Login'; }

print $upload_form->end_html;

sub printLogin
{
    print 'username: ',
        $upload_form->textfield({-name=>'username',
               # -default=>'nunya',
                -size=>20,
                -maxlength=>20});

    print $upload_form->p();

    print 'password ',
        $upload_form->password_field({-name=>'passwd',
                #-value=>'nunya',
                -size=>20,
                -maxlength=>20});
    print $upload_form->p();
    print $upload_form->submit({-name=>'login_btn',
                -value=>'Login'});

    print $upload_form->end_form();

    print $upload_form->end_html;
}


My first question is. I have an image on the cgi folder within the server called 'adminLogin.jpg'. I tried lots of different ways of adding this image and looked at a few solutions throughout the web but I still wasn't able to get it working. Could anyone tell me the line I am supposed to add in

Second question is. I want the user to be redirected to 'adminLogin.pl' if he or she enters in the correct user name and password

Lastly. Is it possible to use javascript within perl
Avatar of FishMonger
FishMonger
Flag of United States of America image

1)  The cgi-bin directory is where your scripts are placed, not .jpg files.  Move your images to a folder under your public_html directory (or whatever name is being used by the web server).

2)  You need to hold off printing any output until you've verified the username/password.  If authentication fails, then do a redirect to the login page.
http://search.cpan.org/~lds/CGI.pm-3.29/CGI.pm#GENERATING_A_REDIRECTION_HEADER

3)  Yes, you can output javascript code with Perl.  If you want it in the head section, you'd use the -script attribute in the start_html() method, otherwise you'd output it afterwards.

The documentation for the CGI module gives examples on how to handle each of your questions.
Avatar of bigbong00

ASKER

So i added in the image like so but I'm still getting the error
#!\xampp\perl\bin\perl.exe
# Academics are us Admin Login

use CGI;

print <html><img src="http://php.infc.ulst.ac.uk/com851c1/tis07sa6/adminLogin.jpg"></html>;

$upload_form = new CGI;
print $upload_form->header,
        $upload_form->start_html('Login');

print $upload_form->start_form();

## for testing purpose
print $upload_form->param, $upload_form->p();
print $upload_form->param_fetch('username')->[0],
                                 $upload_form->p();
print $upload_form->param_fetch('passwd')->[0],
                                 $upload_form->p();

$upload_form->import_names('upload_form_names');

if (!$upload_form_names::username or
            !$upload_form_names::passwd) {
    printLogin();
    }
elsif ($upload_form_names::username eq 'User'
        and $upload_form_names::passwd  eq 'password') {
    # The below line is where you would have this script
    # set a cookie and forward the user to the admin area.
    print 'Authorised Login';  }
else {
    # The below line where you would put
    # whatever you want for bad user/pass
    # combinations.
    print 'unAuthorised Login'; }

print $upload_form->end_html;

sub printLogin
{
    print 'username: ',
        $upload_form->textfield({-name=>'username',
               # -default=>'nunya',
                -size=>20,
                -maxlength=>20});

    print $upload_form->p();

    print 'password ',
        $upload_form->password_field({-name=>'passwd',
                #-value=>'nunya',
                -size=>20,
                -maxlength=>20});
    print $upload_form->p();
    print $upload_form->submit({-name=>'login_btn',
                -value=>'Login'});

    print $upload_form->end_form();

    print $upload_form->end_html;
}

I've also looked through the submit re-direct thing. Can't pick anyhting out to help me
> print <html><img src="http://php.infc.ulst.ac.uk/com851c1/tis07sa6/adminLogin.jpg"></html>;
please remove this line 'cause it breaks your html structure
Use something like:
 print start_html(), img(-src=>"http://php.infc.ulst.ac.uk/com851c1/tis07sa6/adminLogin.jpg");

# where I highliy recommend that you omiz the http:... part and just use the path on the webserver, also keep the suggestion about the images directory in mind

> Second question is. ...
depending on your logic use this code to redirect the user

print CGI::header(-location=>"/adminLogin.pl");


> Is it possible to use javascript within perl
if you mean that perl writes javascript as output to the client, yes
if you mean that you write javascript code which is used/done by perl, no

I've made a few adjustments to get you started, but there are number of things that could/should be fixed and/or better implemented.
use CGI::Carp qw(fatalsToBrowser);
use CGI;
 
 
$upload_form = new CGI;
 
 
## for testing purpose
#print $upload_form->param, $upload_form->p();
#print $upload_form->param_fetch('username')->[0],
#                                 $upload_form->p();
#print $upload_form->param_fetch('passwd')->[0],
#                                 $upload_form->p();
 
$upload_form->import_names('upload_form_names');
 
if (!$upload_form_names::username or
            !$upload_form_names::passwd) {
    printLogin();
    }
elsif ($upload_form_names::username eq 'User'
        and $upload_form_names::passwd  eq 'password') {
    # The below line is where you would have this script
    # set a cookie and forward the user to the admin area.
    print $upload_form->header,
          $upload_form->start_html('Authorized Login');
    print 'Authorised Login';  }
else {
    # The below line where you would put
    # whatever you want for bad user/pass
    # combinations.
 
 # this is only 1 of several methods to redirect
    print $upload_form->redirect($upload_form->url()); }
 
print $upload_form->end_html;
 
sub printLogin
{
    print $upload_form->header,
          $upload_form->start_html('Login');
    print $upload_form->img({src=>"http://php.infc.ulst.ac.uk/com851c1/tis07sa6/adminLogin.jpg"});
    print $upload_form->start_form();
    print 'username: ',
        $upload_form->textfield({-name=>'username',
               # -default=>'nunya',
                -size=>20,
                -maxlength=>20});
 
    print $upload_form->p();
 
    print 'password ',
        $upload_form->password_field({-name=>'passwd',
                #-value=>'nunya',
                -size=>20,
                -maxlength=>20});
    print $upload_form->p();
    print $upload_form->submit({-name=>'login_btn',
                -value=>'Login'});
 
    print $upload_form->end_form();
 
}

Open in new window

Sorry it has taken me so long to reply. I'm havinbg problems with these lines you have created
I don't want to redirect the user anywhere if he enters in a bad password. Just would like some javascript (which I plan to do later) but he should be redirected when the password and username match

elsif ($upload_form_names::username eq 'User'
        and $upload_form_names::passwd  eq 'password') {
    # The below line is where you would have this script                   ###### how do i do this?
    # set a cookie and forward the user to the admin area.
    print $upload_form->header,
          $upload_form->start_html('Authorized Login');
    print 'Authorised Login';  }
else {
    # The below line where you would put
    # whatever you want for bad user/pass                        #########Don't want to redirect user here
    # combinations.
 
 # this is only 1 of several methods to redirect
    print $upload_form->redirect($upload_form->url()); }
 
print $upload_form->end_html;
Never use javascript for username/password verification!  Why, you ask?  Because that requires you to provide the username and password in the javascript and all the user has to do is "view source" to see what username/password they need to enter.  Javascript can be used as a preliminary check to see if the username and/or password is correctly formatted.  However, since users can disable javascript, you should never rely on those tests.  All authorization checks should be handled by the perl script.

If the authentication fails, you need to redirect back to the login page.

Creating and sending the cookie could be handled with either the CGI or CGI::Cookie module.
http://search.cpan.org/~lds/CGI.pm-3.31/CGI.pm#HTTP_COOKIES
http://search.cpan.org/~lds/CGI.pm-3.31/CGI/Cookie.pm

Another option, which I think is better, is to use CGI::Session.
http://search.cpan.org/~markstos/CGI-Session-4.20/lib/CGI/Session.pm
I think you misunderstood me. When the user fails to enter the correct username and password some red writting will appear above the input box to say there has been an error. Thats all. I don't plan to validate anything with javascript. I've read through all the cookie information you sent

expiration time
name
value
path
domain
secure

I take it I am supposed to send this information but what info do i send? How do I send it. Who do I send it to? I'm completely new to perl and fairly new to website design
> When the user fails to enter the correct  ..
you have to send the entered data to the server (your perl/CGI script) which then needs to return the same page with the additional info you want to be shown.
It appears that you're having a hard time understanding the documentation that I pointed to as well as the overall process that you need to accomplish.

Rather than cleaning-up and fixing your script, I'll post one of my login scripts that I've adjusted to include the javascript that you asked about.  I'm pulling my user info from a database, but the combination of this script and the documentation should be enough for you to figure out how to modify it to your needs.

I'm also hoping that I'm not providing you with the answer to a homework assignment.
#!/usr/bin/perl
 
use strict;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use CGI::Session;
use Crypt::PasswdMD5;
use DBI;
 
my $hostname = `hostname`;
my $cgi = new CGI;
my $self = $cgi->url;
my %login = $cgi->Vars;
my $session = new CGI::Session or die CGI::Session->errstr;
my $title = 'Email Administration Login';
my $alert;
 
my $css = <<CSS;
body {
      background-image: url(/images/left-logo.gif);
      background-repeat: no-repeat;
      background-position: 5px 5px;
      background-color: #cccccc;
      font-family: times;
      text-align: center;
      font-size: small
     }
 
.host {
         position: absolute;
         z-index: auto;
         top: 30px;
         left: 10px;
         font-size: 8;
        }
 
CSS
 
 
if ( $cgi->param('logout') ) {
   $session->clear(['admin', 'logged_in']);
}
 
if( $cgi->param('Login') ) {
 
   my $home_page = 'http://mydomain.com/cgi-bin/home_page.pl';
   my $authenticated = authenticate_user();
   print $cgi->redirect($home) if $authenticated;
}
 
login_page();
 
 
sub login_page {
 
   print $session->header;
 
   if($alert) {
      print $cgi->start_html(-title=>$title,
                             -style=>{-code=>"$css"},
                             -script=>{-type=>'text/javascript',
                                       -code=>$alert},
                             -onLoad=>'failed();'
                            );
   }
   else {
      print $cgi->start_html(-title=>$title,
                             -style=>{-code=>"$css"}
                            );
   }
 
   print $cgi->h1($title),
         $cgi->start_form(-name=>'login'),
         $cgi->p('Username: ', $cgi->textfield('username')),
         $cgi->p('Password: ', $cgi->password_field('password', '')),
         $cgi->p($cgi->submit('Login', 'Login')),,
         $cgi->end_form;
 
   print $login{'failed'} if defined $login{'failed'};
   print $cgi->end_html;
}
 
 
sub authenticate_user {
 
   if ( defined $login{'username'} && defined $login{'password'} ) {
 
      my ($encrypted_pass, $roll, $name) = queryDB($login{'username'});
 
      if ( $encrypted_pass ) {
 
         my $salt = substr($encrypted_pass, 3,8);
         my $password = unix_md5_crypt( $login{'password'}, $salt );
 
         if ( $password eq $encrypted_pass ) {
            $session->param('logged_in', 1);
            $session->param('user', $login{'username'});
            $session->param('admin', $name);
            $session->param('roll', $roll);
            return 1;
         }
      }
   }
   $login{'failed'} = 'Invalid username, or password...Please try again';
   $alert = qq/function failed() { alert("$login{'failed'}"); }/;
   return 0;
}
 
 
sub queryDB {
 
   my $user = shift;
   my %db = (
             server   => 'dbserver.mydomain.com',
             name     => 'users',
             username => 'username',
             password => 'password'
            );
 
 
   my $dbh = DBI->connect("DBI:mysql:$db{'name'}:$db{'server'}",
                           $db{'username'}, $db{'password'},
                         {'RaiseError' => 1, 'PrintError' => 0 })
                  or die "Connection Failed: $iso_db{'name'} DB on " .
                         "$db{'server'}\n\t$DBI::errstr\n";
 
   my $sth = $dbh->prepare("SELECT password, roll, name
                            FROM users
                            WHERE id = '$user' and status = 'active' limit 1")
                   or die "prepare statemnet failed: $DBI::errstr\n";
   $sth->execute;
   my ($password, $roll, $name) = $sth->fetchrow_array;
 
   $sth->finish;
   $dbh->disconnect;
   return ($password, $roll, $name);
}

Open in new window

My server seems to be down. I'll check that out.

Yeah it was understanding perl in general I was having difficulty with. Never done it defore so I've just been looking at examples throihjout the web.

Thanks
Still having problems. It seems to have problems with lines 102 and 107 which are my authentication. I'm not using a database

#!\xampp\perl\bin\perl.exe
# Academics are us Admin Login

use CGI::Carp qw(fatalsToBrowser);
use CGI;

my $cgi = new CGI;
my $self = $cgi->url;
my %login = $cgi->Vars;
my $session = new CGI::Session or die CGI::Session->errstr;
my $alert;
 
$cgi->import_names('cgi_names');
 
my $css = <<CSS;
body {

      background-color:white;
      font-family:arial;
      text-align: center;
      font-size: small
     }
 
.host {
         position: absolute;
         z-index: auto;
         top: 30px;
         left: 10px;
         font-size: 8;
        }
 
CSS
 
 
if ( $cgi->param('logout') ) {
   $session->clear(['admin', 'logged_in']);
}
 
if( $cgi->param('Login') ) {
 
   my $admin_page = 'http://php.infc.ulst.ac.uk/cgi-bin/com851c1/tis07sa6/AdminArea.pl';
   my $authenticated = authenticate_user();
   print $cgi->redirect($home) if $authenticated;
}
 
login_page();
 
sub printLogin
{
   print $session->header;
 
   if($alert) {
      print $cgi->start_html(-title=>$title,
                             -style=>{-code=>"$css"},
                             -script=>{-type=>'text/javascript',
                                       -code=>$alert},
                             -onLoad=>'failed();'
                            );
   }
   else {
      print $cgi->start_html(-title=>$title,
                             -style=>{-code=>"$css"}
                            );
   }
   
    print $cgi->header,
          $cgi->start_html('Login');
    print $cgi->img({src=>"http://php.infc.ulst.ac.uk/com851c1/tis07sa6/adminLogin.jpg"});
    print $cgi->start_form();
    print 'username: ',
        $cgi->textfield({-name=>'username',
               # -default=>'nunya',
                -size=>20,
                -maxlength=>20});
 
    print $cgi->p();
 
    print 'password ',
        $cgi->password_field({-name=>'passwd',
                #-value=>'nunya',
                -size=>20,
                -maxlength=>20});
    print $cgi->p();
    print $cgi->submit({-name=>'login_btn',
                -value=>'Login'});
 
    print $cgi->end_form();
      
         print $login{'failed'} if defined $login{'failed'};
   print $cgi->end_html;
 
}

sub authenticate_user {
 
if (!$cgi_names::username or
            !$cgi_names::passwd) {
    printLogin();
    }
else ($cgi_names::username eq 'User'
        and $cgi_names::passwd  eq 'password') {

    print 'Authorised Login';  }
            return 1;
         }
   $login{'failed'} = 'Invalid username, or password...Please try again';
   $alert = qq/function failed() { alert("$login{'failed'}"); }/;
   return 0;
}
Change line 43 from:
print $cgi->redirect($home) if $authenticated;

To:
print $cgi->redirect($admin_page) if $authenticated;

The else clause on line 100 is missing the opening brace and 'if' keyword, change it from:
else ($cgi_names::username eq 'User'

to:
else {
    if ($cgi_names::username eq 'User'
Change:
$cgi_names::username

to:
$login{'username'}

and change:
$cgi_names::password

to:
$login{'password'}

Add the strict pragma and you'll find a couple more items that need to be fixed.
use strict;
THANKS MR FISHMONGER THOUGH I AM NOW GETTING THE ERROR

Can't locate object method "new" via package "CGI::Session" (perhaps you forgot to load "CGI::Session"?) at D:/xampp/htdocs/com851c1/tis07sa6/login.pl line 10.

I'VE LOOKED AT SOME FIX ITS THROUGHOUT THE WEB AND I AM NOT UNDERSTANDING THE QUESTION TOO WELL. LIKE THIS ONE BELOW

http://www.dbforums.com/archive/index.php/t-766555.html
You're receiving the error because you removed the line that loads the CGI::Session module.
use CGI::Session;

Depending on your requirements, you may not need that that module.  If you don't need/want to use that module, then make the following changes.

1) remove this line:
my $session = new CGI::Session or die CGI::Session->errstr;

2) change:
print $session->header;

to:
print $cgi->header;
sorry it has taken me so long to write back. Still getting the same error message

#!\xampp\perl\bin\perl.exe
# Academics are us Admin Login

use CGI::Carp qw(fatalsToBrowser);
use CGI;
use strict;
use CGI::Carp qw(fatalsToBrowser);

my $cgi = new CGI;
my $self = $cgi->url;
my %login = $cgi->Vars;
my $alert;
 
$cgi->import_names('cgi_names');
 
my $css = <<CSS;
body {

      background-color:white;
      font-family:arial;
      text-align: center;
      font-size: small
     }
 
.host {
         position: absolute;
         z-index: auto;
         top: 30px;
         left: 10px;
         font-size: 8;
        }
 
CSS
 
 
if ( $cgi->param('logout') ) {
   $session->clear(['admin', 'logged_in']);
}
 
if( $cgi->param('Login') ) {
 
   my $admin_page = 'http://php.infc.ulst.ac.uk/cgi-bin/com851c1/tis07sa6/AdminArea.pl';
   my $authenticated = authenticate_user();
   print $cgi->redirect($home) if $authenticated;
}
 
login_page();
 
sub printLogin
{
   print $cgi->header;
 
   if($alert) {
      print $cgi->start_html(-title=>$title,
                             -style=>{-code=>"$css"},
                             -script=>{-type=>'text/javascript',
                                       -code=>$alert},
                             -onLoad=>'failed();'
                            );
   }
   else {
      print $cgi->start_html(-title=>$title,
                             -style=>{-code=>"$css"}
                            );
   }
   
    print $cgi->header,
          $cgi->start_html('Login');
    print $cgi->img({src=>"http://php.infc.ulst.ac.uk/com851c1/tis07sa6/adminLogin.jpg"});
    print $cgi->start_form();
    print 'username: ',
        $cgi->textfield({-name=>'username',
               # -default=>'nunya',
                -size=>20,
                -maxlength=>20});
 
    print $cgi->p();
 
    print 'password ',
        $cgi->password_field({-name=>'passwd',
                #-value=>'nunya',
                -size=>20,
                -maxlength=>20});
    print $cgi->p();
    print $cgi->submit({-name=>'login_btn',
                -value=>'Login'});
 
    print $cgi->end_form();
     
         print $login{'failed'} if defined $login{'failed'};
   print $cgi->end_html;
 
}

sub authenticate_user {
 
if (!$login{'username'} or
            $login{'password'}) {
    printLogin();
    }
else{
      if ($login{'username'}eq 'user'
        and $login{'password'}  eq 'password') {

    print 'Authorised Login';  }
            return 1;
         }
   $login{'failed'} = 'Invalid username, or password...Please try again';
   $alert = qq/function failed() { alert("$login{'failed'}"); }/;
   return 0;
}
ASKER CERTIFIED SOLUTION
Avatar of FishMonger
FishMonger
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
It works. I'm well pleased. Thanks also for writting out the errors