#!/usr/bin/perl

# ezpdbi.cgi
# (c) 2001 Useful Utilities
# http://www.usefulutilities.com

# This script demonstrates how you can leverage an existing MySQL
# database using DBI

# ezpauth.pl really should be moved to a directory other than your
# CGI directory.  If you do this, be sure to change the following
# line to reflect this new directory
require "ezpauth.pl";

use DBI;

sub ShowForm;
sub ExpiredID;

# To link EZproxy to this script, you need to make an entry in ezproxy.usr
# that looks like:
#
#     cgiuser:cgipass:cgi=http://auth.mylib.org/cgi-bin/ezpiii.cgi?
#
# This line indicates that all new authentication requests should be
# handed off to the specified CGI script.  The ? at the end is required
# since EZproxy will then append &url= followed by the web site the
# user wants to visit.
#
# $ezpuser and $ezppass have to be set to match the username and password
# from the ezproxy.usr entry.  $ezphost must be your EZproxy server's
# host name.
$ezpuser = "cgiuser";
$ezppass = "cgipass";
$ezphost = "ezproxy.mylib.org";


ParseFields();

# If the user field is undefined, show the main form
if (! defined $in{"user"}) {
  ShowForm(0);
  exit(1);
}

# Change dbname, dbhost, dbuser and dbpass as appropriate

$dbh = DBI->connect("dbi:mysql:database=dbname;host=dbhost", "dbuser", "dbpass") ||
  Down "Database unavailable, please try again later<p>$DBI::errstr";

# Change SQL query to retrieve appropriate field(s), then the if that
# follows based on your own authentication needs
$sth = $dbh->prepare(<<SQL) || Down "prepare $DBI::errstr";
select password
  from dbtable
  where
    username = ?
SQL

$sth->execute($in{"user"});

if (($checkpassword) = $sth->fetchrow_array) {
  if ($checkpassword eq $in{"pass"}) {
# If you want EZproxy to log this username, add "O LOGUSER" to ezproxy.cfg
# and uncomment the next line
#   $ezploguser = $in{"user"};
    StartSession();
    exit(0);
  }
}

# Username did not appear, or password wrong, so login failed page  
ShowForm(1);

sub ShowForm
{
  print <<EOF;
Content-Type: text/html
Cache-control: no-cache
Cache-control: no-store
Pragma: no-cache

<html>
<head>
<title>User Authentication</title>
</head>
<body>
<h1>User Authentication</h1>
<p>
EOF

  if ($_[0]) {
    print <<EOF;
The information you entered was invalid, please try again.<p>
EOF
  }

  $encurl = FormEncode($in{"url"});

  print <<EOF;
<form action="$action" method="post">
Please enter your username: <input name="user" type="text"><br>
Please enter your password: <input name="pass" type="password"><br>
<input type="hidden" name="url" value="$encurl">
<p>
<input type="submit" value="Login">
</form>
</body>
</html>
EOF
}
