<?php
#
#   Start unique session
#
if (session_id() == "")
  session_start();

#
#   Set constants
#
$authfile = "account";
$sitename = "CH5M3D Computational Chemistry Interface";
$errmsg   = "<html><head><title>Unauthorized</title></head>
             <body><h1>Access Denied</h1>
             <p>An account is required to use this site.</p>
             </body></html>";


#
#   Function for failed authorization attempts
#
function auth_reject() {
  global $sitename, $errmsg;

  Header("HTTP/1.0 401 Unauthorized");
  Header("WWW-Authenticate: Basic realm=\"$sitename\"");
  session_destroy();
  echo $errmsg;
  exit();
  }


#
#   If no username/password sent, reject
#
if ( !isset($_SERVER['PHP_AUTH_USER'])  ||  !isset($_SERVER['PHP_AUTH_PW'])) {
  auth_reject();
  }
$user = $_SERVER['PHP_AUTH_USER'];
$pass = sha1($_SERVER['PHP_AUTH_PW']);

#
#   Verify username/password against data in account file.
#
$_SESSION['authorized'] = 0;
$fh = fopen($authfile,'r') or die("Unable to open authorization file.");
while ( !feof($fh)) {
  $line = fgets($fh);
  $info = split(",",$line);
  if ( ($user == trim($info[0]))  &&  ($pass == trim($info[1])) ) {
    $_SESSION['authorized'] = 1;
    }
  }
fclose($fh);
if ( $_SESSION['authorized'] != 1) {
  auth_reject();
  }

?>
