Location: PHPKode > projects > Homeless Mangement Information System > hmis/include/authenticate.inc
<?php
session_start();

//*Client Data System, Copyright (C) 2000, 2001, 2002, 2003 Tedd Kelleher.  This is free software, subject to the 
//*GNU GENERAL PUBLIC LICENSE, Version 2, June 1991 (in file named gpl.txt), which should accompany 
//*any distribution of this file.  Tedd Kelleher can be contacted at hide@address.com

include ( $include_root.'initialize.inc' );
include ( $include_root.'db_connection.inc' );
//Utility, Debug, and/or Helper functions.  Contains pretty_var_dump() and MkTime() wrapper function. ~Jeff
include_once($include_root.'utility.inc');

$db_link = db_generic_connect ();

$client_ip = addslashes ( getenv ( 'REMOTE_ADDR' ) );
//don't need to call safe_date() here since we're post 1970 and direct call is more efficient!
$date_stamp = date( 'YmdHi' );
$unix_date = time ();

ban_check();

if ( $_GET['logoff'] == 'yes' )
{
    destroy_session ();
}

if ( $_SESSION['session_timout'] < $unix_date && $_SESSION['session_timout'] > 1 )
{
    destroy_session ();
}
else
{
    if ($_SESSION['user_idB'])
	{
      //Pull-out matches to the login_id, gate_status from the gate table to ensure user is still active
	  $sql_login_test = "
      SELECT user_id, gate_status 
        FROM gate 
        WHERE 
            user_id LIKE '".$_SESSION['user_idB']."' 
            AND gate_status LIKE 'active'
            OR
            user_id LIKE '".$_SESSION['user_idB']."' 
            AND gate_status LIKE 'pending'
      ";
	  
      $login_query = run_query ( $sql_login_test, 'Login system failure' );
      //If the login_id gate_status=active combo matches one in the "gate" table.....
	  if ( num_rows ( $login_query ) == 1 )
	  {
		//echo 'good to go, do nothing...';
	  }
	  else
	  {
	  	//while logged in this account was made inactive so give them the boot...
		destroy_session ();
      }
	}
    $_SESSION['session_timout'] = $unix_date + ( $time_out/1000 ) + 95;
}

//If they try to crack the system by submitting their own $logged-in variable, ban them
if ( $_COOKIE['logged_in'] || $_POST['logged_in'] || $_GET['logged_in'] )
{
	ban ( $client_ip, $user_id, $this_page, '', '', 'Attempt to illegally submit the \$logged_in variable via a cookie, post, or get',
    $date_stamp );
    $_SESSION['logged_inB'] = 'fishswamp';
    exit;
}

//If they are not sucessfully logged-in, reset all the session variables and register them in the session 
if ( $_SESSION['logged_inB'] != $db_name.'yesindeed' )
{
    //Add something to $logged in to make it unique to this instance of database, so there is no cross contamination with other datasystems
    //echo"Unsetting vars<p>";	  
    unset($_SESSION['logged_inB']);
	unset($_SESSION['user_idB']);
	unset($_SESSION['user_nameB']);
	unset($_SESSION['org_idB']);
	unset($_SESSION['org_nameB']);
	unset($_SESSION['group_idB']);
	unset($_SESSION['group_nameB']);
	unset($_SESSION['access_levelB']);
	unset($_SESSION['system_typeB']);
	unset($_SESSION['super_user_idB']);
	unset($_SESSION['super_user_nameB']);
	unset($_SESSION['client_infoB']);
    unset($_SESSION['sess_idB']);
    unset($_SESSION['gate_status']);
    unset($_SESSION['session_timout']);
	unset($_SESSION['matching_clients_identifier_arrayB']);
}

//If we are allowing cookie logins, and the user is logged in, and they have not submitted a login form, check for a cookie
if ( $use_cookie_login == 'yes' && !$_SESSION['logged_inB'] && !$_POST['form_login'] )
{
	echo ' coookiess... ';
    if ( $_COOKIE['val'.$db_name] )
	{
       //There is a cookie, so log them in
       if ( ereg( "[^0-9a-z]", $_COOKIE['val'.$db_name] ) || strlen ( $_COOKIE['val'.$db_name] ) > 40 )
       {
            ban ( addslashes ( $_COOKIE['val'.$db_name] ) , 'Bad cookieA', 'forever' ); 
            exit;
       }
       $sql = "SELECT gate_login, gate_password, gate_status FROM gate WHERE gate_status LIKE 'active' AND gate_cookie_value = '".$_COOKIE['val'.$db_name]."'";
       $result = run_query ( $sql, $error_message );
       if ( num_rows ( $result ) == 1 )
       {
            $creds = fetch_array ( $result, 'Pulling cookie designated vals', 0 );
            $_POST['form_login'] = $creds['gate_login'];
            $_POST['form_password'] = $creds['gate_password'];
       }
       else
	   {
            echo "Bad cookie";
            ban ( addslashes ( $_COOKIE['val'.$unique_seq] ) , 'Bad cookieB', 'forever' );
            exit;
       }
    }
}



if ( !$_SESSION['logged_inB'] && !$_POST['form_login'] )
{
    login_form_html();
	exit;
}



if ( $_POST['form_login'] )
{
	ban_check ();
    //Check login for illegal content or size
	if ( strlen ( $_POST['form_login'] ) > 50 )
	{
        $_POST['form_login'] = 'TOO LONG'; 
        ban ( $_POST['form_login'], 'Login too long', 'forever' );
        exit;
    }
	
    if ( ereg ("[^A-Za-z0-9]\\\\'", $_POST['form_login']) )
    {
		failed_login ( $_POST['form_login'], 'Illegal Login Characters');
        login_form_html(); 
        exit;
	}
	
	//Check password for illegal content or size
	if ( strlen ( $_POST['form_password'] ) > 25)
    {
        $_POST['form_password'] = ''; 
        ban ( $_POST['form_password'], 'Password Too Long', 'forever' ); 
        exit;
    }
	
	if ( ereg ( "[^A-Za-z0-9\)\[:space:]\)\(\.\?\,\!\#\&\$\@\/\=\:\_\>\<\*\}\{\+\-]", $_POST['form_password'] ) )
    {
		failed_login ( $_POST['form_login'], 'Illegal Password Characters' ); 
        login_form_html(); 
        exit;
	}
	
    //Pull-out matches to the login from the gate table
	$sql_login_test = "
    SELECT user_id, gate_status 
        FROM gate 
        WHERE 
            gate_login LIKE '".$_POST['form_login']."' 
            AND gate_password LIKE '".md5 ( $_POST['form_password'] )."'
            AND gate_status LIKE 'active'
            OR
            gate_login LIKE '".$_POST['form_login']."' 
            AND gate_password LIKE '".md5 ( $_POST['form_password'] )."' 
            AND gate_status LIKE 'pending'
    ";
	
    $login_query = run_query ( $sql_login_test, 'Login system failure' );
    //If the login/password combo matches one in the "gate" table.....
	if ( num_rows ( $login_query ) == 1 )
	{
		//Set all the session variables
		//$_SESSION['logged_inB'] = $db_name."yesindeed";
		$login_queryB = fetch_array ( $login_query, 'Gate variables', 0 );
        $z_user_id = 'user_id';
		$_SESSION['user_idB'] = $login_queryB[$z_user_id];
		$_SESSION['gate_status'] = $login_queryB['gate_status'];
		
		$sql = "
        SELECT 
            user_name_first, user_name_last, org_id, user_access_level 
            FROM user_info 
            WHERE user_id = '".$_SESSION['user_idB']."'
        ";
		$query_org = run_query ( $sql, 'No user_info login query' );
		$user_info_query = fetch_array ( $query_org, 'No login user_info', 0 );  
		$_SESSION['user_nameB'] = $user_info_query['user_name_first'].' '.$user_info_query['user_name_last'];
		$_SESSION['org_idB'] = $user_info_query['org_id'];
		$_SESSION['access_levelB'] = $user_info_query['user_access_level'];
		
		$sql_or = "
        SELECT group_id, org_name, org_system_type, account_status 
            FROM organizations 
            WHERE org_id = '".$_SESSION['org_idB']."'
        ";
        $org_in_res = run_query ( $sql_or, 'No org_info login query' );
        $org_info_query = fetch_array ( $org_in_res, 'No login user_info', 0 ); 
		
        //If the group or organization account is no longer active, do not let them in
        $sqlh = "
        SELECT account_status 
            FROM organizations 
            WHERE 
                group_id = '".$org_info_query['group_id']."'
            AND org_type = 'group'
        ";
        $group_status_check_result = run_query ( $sqlh, 'Checking group account status' );
        
        //If the system administrator, don't try and find associated group status
        if ( $user_info_query['user_access_level'] != '10' )   {
        $group_status_check = fetch_array ( $group_status_check_result, 'Fetching group account status', 0 );
            if ( $group_status_check['account_status'] != 'active' )
            {
                session_destroy();
                $login_message = $group_term.' account deactivated. Please contact the system administrator.';
                login_form_html(); 
                exit;
            }
        }
        if ( $org_info_query['account_status'] != 'active' )
        {
            session_destroy();
            $login_message = $organization_term.' account deactivated. Please contact the system administrator.';
            login_form_html();
            exit;
        }
        $_SESSION['org_nameB'] = $org_info_query['org_name'];
		$_SESSION['group_idB'] = $org_info_query['group_id'];
		$_SESSION['system_typeB'] = $org_info_query['org_system_type'];
		
		$sql_grp = "
        SELECT group_name 
            FROM groups 
            WHERE group_id = '".$_SESSION['group_idB']."'
        ";
        $grp_res = run_query ( $sql_grp, 'No group_info login query' );
        $group_info_query = fetch_array ( $grp_res, 'No login user_info', 0 ); 
		$_SESSION['group_nameB'] = $group_info_query['group_name'];
        $_SESSION['logged_inB'] = $db_name.'yesindeed';       
        $_SESSION['session_timout'] = $unix_date + ( $time_out/1000 ) + 95;
        
		//Log the successful login in "logged_in_log" table
		$log_sql = "
        INSERT INTO logged_in_log ( log_user_id, 
						            log_user_name, 
						            log_org_id, 
						            log_org_name, 
						            log_group_id, 
						            log_group_name,
						            log_ip, 
						            log_date_stamp, 
						            log_unix_date )
        VALUES (
            '".addslashes($_SESSION['user_idB'])."', 
            '".addslashes($_SESSION['user_nameB'])."',
            '".addslashes($_SESSION['org_idB'])."', 
            '".addslashes($_SESSION['org_nameB'])."', 
            '".$_SESSION['group_idB']."', 
            '".addslashes($_SESSION['group_nameB'])."', 
            '".$client_ip."', 
            '".$date_stamp."', 
            '".$unix_date."'
            
        )";
		run_query ( $log_sql, 'User info not inserted into login log. ' );
        
        $log_sqlb = "SELECT log_rowid 
            FROM logged_in_log WHERE log_user_id = '".$_SESSION['user_idB']."' AND log_unix_date = '".$unix_date."'";
        $log_res = run_query ( $log_sqlb, 'Find log rowid' );
        $sess_id = fetch_result ( $log_res, 'Lg id' );
        $log_sqlc = "UPDATE logged_in_log SET log_session_id = '".$sess_id."' WHERE log_rowid = '".$sess_id."'";
        run_query ( $log_sqlc, 'Log sid' );
        $_SESSION['sess_idB'] = $sess_id;   
        
        if ( $use_cookie_login == 'yes' )   {
            $rand_val = md5 ( uniqid ('') );
            $sql = "
            UPDATE gate 
                SET gate_cookie_value = '".$rand_val."' 
                WHERE user_id = '".$_SESSION["user_idB"]."'";
            run_query ( $sql, "Setting gate cookie value" );
            setcookie ( 'val'.$db_name, $rand_val, time() + ( 60 * 60 * 24 * 365 ) );
        }
        
	}
	
	//There are no matching logins 
	else	{
        failed_login ( $_POST['form_login'], 'Bad Login or Password' ); 
        login_form_html(); 
        exit;
    }
	
}

if ($_SESSION['gate_status'] == 'pending' && $page_id != 'edit_user_login')
{
        header("Location: edit_user_login.php"); 
        exit;
}



//Convert the session variables into normal variables

$logged_in = $_SESSION['logged_inB'];
$user_id = $_SESSION['user_idB'];
$user_name = $_SESSION['user_nameB'];
$org_id = $_SESSION['org_idB'];
$org_name = $_SESSION['org_nameB'];
$group_id = $_SESSION['group_idB'];
$group_name = $_SESSION['group_nameB'];
$access_level = $_SESSION['access_levelB'];
$system_type = $_SESSION['system_typeB'];
$client_info = $_SESSION['client_infoB'];
$message = $_SESSION['messageB'];
$message_type = $_SESSION['message_typeB'];
$matching_clients_identifier_array = $_SESSION['matching_clients_identifier_arrayB'];

//Convert commonly used posted variables to regular variables
convert_post_and_get_variable ( 'form_submitted' );
$form_answer = $_POST['form_answer'];


//echo "Access level is ".$access_level." -- page level is ".$page_access_levels."<p>";
//Check to see if the user is at the right level to visit the page
page_access_level_check ( $page_access_levels, $access_level );

//Timout
//Removed warning because if the "ok" is never pressed the screen will be displayed forever
$head_dynamic_ecma[0] .= "
function ta () {
    document.getElementById('message').style.zIndex='2';
    document.getElementById('message').style.textAlign='right';
    document.getElementById('message').style.color = \"#FF7A02\";
    document.getElementById('message').style.background = \"#FFFE93\";
    document.body.style.background = \"#FFFFCC\";
    tb ( 91, 1 );
        
}

function tb ( cnt, cli )
{
    cnt = cnt - 1;
    
    if ( cli == 1 )
    {
        cli = 2;
        cl = '#FF026A';
    }
    else
    {
        cli = 1
        cl = '026AFF';
    }
    
    document.getElementById('message').style.color = cl;
    document.getElementById('message').innerHTML = '<br/>Auto logoff in ' + cnt + ' seconds';    
    sty = 'tb(' + cnt + ', ' + cli + ')';
    
    if ( cnt > 1 )
    {
        setTimeout(sty, 1000 );
    }
    else
    {
        document.location='index.php?logoff=yes';
    }
}

function confirm_action( msg, qstr_action)
{
    if (confirm(msg))
    {
        document.location=qstr_action;
    }
}
";


$head_dynamic_ecma[1] .= "\nsetTimeout(\"ta()\", ".$time_out.");\n";


////Beginging of Authentication of Functions *********************************
///////////////////////////////////////////////////////////////////////////

function login_form_html ()
{
	GLOBAL $this_page, $_POST, $login_message, $system_title;
	//ban_check (); Redundent with first check
	
    //Submit the form to the uir unless a logoff request
    if ( $_GET['logoff'] ) {
        $uri = $this_page;
    }
    else {
        $uri = $_SERVER['REQUEST_URI'];
    }
    
    
	echo	"
    <html><body>
    
    <h1 align=center><FONT size=\"+4\" color=\"#000066\">".$system_title."</FONT></h1>
    <h1 align=center>WARNING</h1>

	<p align=center>This is a proprietary system and is for use by authorized individuals only.
	</p>
	<p>
	The information in this system is confidential. 
	Confidential information is sensitive or secret information, or information whose unauthorized disclosure could be harmful or prejudicial.  
	Only those who have been explicitly granted their own userid and password may access this system beyond this point of entry.  
	Any printed information obtained from this system must also be treated as confidential.
	</p>
	Use of this system constitutes an express consent to monitoring at all times.  
	If monitoring reveals possible violations of criminal statutes, all relevant information will be provided to law enforcement officials.  
	Anyone using this computer system or related information without proper authorization or in violation of the 
	Agency User Security Policy may be subject to possible internal disciplinary actions, civil and/or criminal prosecution.
	<p align=center>
	By proceeding beyond this screen you are acknowledging that you understand and accept the content of this notice.
	</p>
	<p align=center>
    
    ".$login_message."
	<form method=\"post\" action=\"".$uri."\">	
	<table width=300 cellpadding=0 cellspacing=0 border=1 bordercolor=#993300><tr><td>
	<table width=300 cellpadding=5 cellspacing=0 border=0><tr><td>
	Enter Login:
	</td><td>
	<input type=\"text\" name=\"form_login\" value=\"".stripslashes($_POST["form_login"])."\" size=20 maxlength=50>
	</td></tr><tr><td>
	Enter Password:
	</td><td>
	<input type=\"password\" name=\"form_password\" size=20 maxlength=50>
	</td></tr>
	<tr><td align=right colspan=2>
	<input type=submit name=submit value=\"Submit\">
	</td></tr></table>
	</td></tr></table>
	</form>
	</p>
	</body>
	</html>
			";
	exit;
}



function failed_login ($login, $message)
{
    GLOBAL $client_ip, $date_stamp, $unix_date, $login_message;
	$login_message .= "Bad Login and/or Password";
    $login = addslashes ($login);
	$sql = "INSERT INTO failed_logins (failed_ip, failed_login, failed_message, failed_date_stamp, failed_unix_date) VALUES ('".$client_ip."', '".$login."', '".$message."', '".$date_stamp."', '".$unix_date."')";
	run_query ($sql, "failed_login");
    
}



function ban ($bad_login, $ban_message, $ban_type)
{
	GLOBAL $client_ip, $user_id, $this_page, $date_stamp, $unix_date; 
	
	echo "<html><body>You are Banned</body></html>";
	$client_ip = addslashes ($client_ip);
    $user_id = addslashes ($user_id);
    $this_page = addslashes ($this_page);
    $login = addslashes ($bad_login);
    $ban_message = addslashes ($ban_message);
    $ban_type = addslashes ($ban_type);
    $date_stamp = addslashes ($date_stamp);
    $unix_date = addslashes ($unix_date);
        	
    if(strlen ($bad_login) > 25){$login="TOO LONG";}
	$sql = "INSERT INTO ban (ban_ip, ban_user_id, ban_this_page, ban_bad_login, ban_message, ban_type, ban_date_stamp, ban_unix_date)
    VALUES ('".$client_ip."', '".$user_id."', '".$this_page."', '".$login."', '".substr( addslashes($ban_message), 0, 34 )."', '".$ban_type."', '".$date_stamp."','".$unix_date."')";
	run_query ($sql, "ban");
	exit;
}



function time_add ($interval, $number, $date)
{
	$date_time_array  = safe_getdate($date);
	
	$hours =  $date_time_array["hours"];
	$minutes =  $date_time_array["minutes"];
	$seconds =  $date_time_array["seconds"];
	$month =  $date_time_array["mon"];
	$day =  $date_time_array["mday"];
	$year =  $date_time_array["year"];
    
    switch ($interval)
    {
        case 'Y':
            $add = $number * 31536000;
            break;        
        case 'quarter':
            $add = $number * 7776000;
            break;        
        case 'm':
            $add = $number * 2592000;
            break;        
        case 'd':
            $add = $number * 86400;
            break;        
        case 'week':
             $add = $number * 604800;
            break;        
        case 'H':
             $add = $number * 3600;
            break;        
        case 'i':
             $add = $number * 60;
            break;        
        case 's':
            $add = $number;
            break;
	}
    
   	//$result_time =  safe_mktime($hours, $minutes, $seconds, $month, $day, $year);
    $result_time = $add + $date;
    
    return $result_time;
}



function ban_check ()
{
	GLOBAL $unix_date;
	GLOBAL $client_ip;
	$client_ip = addslashes ( $client_ip );	
	//Check to see if they are banned
	$one_hour_ago = time_add ( 'H', -1, $unix_date );
	$sql = "
    SELECT * 
        FROM ban 
        WHERE 
            ban_ip LIKE '".$client_ip."' 
            AND (
                 ban_unix_date > '".$one_hour_ago."' 
                 OR ban_type LIKE 'forever'
            )";
    $query_result = run_query ( $sql, 'Check on bans' );
	$result_rows = num_rows ( $query_result );
	if ( $result_rows > 0 ){ 
        echo 'You are banned'; 
        exit;
    }
    
	//Check to see if there are too many failed logins overall. If so, "TURTLE."
	$sql = "
    SELECT * 
        FROM failed_logins 
        WHERE failed_unix_date > '".$one_hour_ago."'
    ";
	$query_result = run_query ( $sql, 'Check on TURTLE' );
	$result_rows = num_rows ( $query_result );
	if ( $result_rows > 9 )
    {
        echo 'TURTLE';
        exit;
    }
    
	//Check to see if the user has failed to login too many times. If yes, ban them
	$sql = "
    SELECT * 
        FROM failed_logins 
        WHERE 
            failed_ip LIKE '".$client_ip."' 
            AND failed_unix_date > '".$one_hour_ago."'
    ";
	$query_result = run_query ( $sql, 'Check on bans' );
	$result_rows = num_rows ( $query_result );
	if ( $result_rows > 3 ) {
        ban ( $_POST['form_login'], 'Too Many Failed Logins', '1' ); 
        exit;
    }
}



function page_access_level_check ( $page_access_levels, $user_access_level )
{
	GLOBAL $this_page;
	GLOBAL $page_id;
	GLOBAL $user_id;
	
    //Added quotes to convert varibles to string, was causing me problems otherwise
    if ( !strpos ( "$page_access_levels", "$user_access_level" ) && $page_access_levels != 'all' )
    {
        redirect ( "You are not logged in as a user type that can access the page you requested." );
        exit;
    }
}



//Converts variables received by either post or get into normal variables
function convert_post_and_get_variable ($variable_name)
{
    //In case the "register_globals" variable in "php.ini" is accidentially left "On", unset the variable
    unset($$variable_name);
    
    GLOBAL $$variable_name;
    
    if ( isset ( $_POST[$variable_name] ) )
    {
    
        $$variable_name = $_POST[$variable_name];
    
    }
    
    if ( isset ( $_GET[$variable_name] ) )
    {
    
        $$variable_name = $_GET[$variable_name];
    
    }
}



function destroy_session ()
{
    GLOBAL $logged_in, $use_cookie_login, $unique_seq;
    session_destroy();
	unset($_SESSION['logged_inB']); 
	$logged_in = 'fishswamp';
    $_SESSION['logged_inB'] = 'fishswamp';
    
    if ( $use_cookie_login == 'yes' )   {
        //setcookie ( "val".$unique_seq );
        setcookie ( 'val'.$db_name, '', time() - ( 60 * 60 * 24 * 365 ) );
        $_COOKIE['val'.$db_name] = '';
        //echo "erasing cookie";
    }
}



function redirect ( $err_message )
{
    GLOBAL $system_directory, $message;
    echo "<html><head><meta http-equiv=\"Refresh\" content=\"2;URL=".$system_directory."index.php\"
    /></head><body>".htmlentities( $err_message )."</body></html>";
    //header ( 'Location: '.$system_directory.'index.php' );
    //$message = $err_message;
}


/*
// Debug Session Variables
	
	echo $user_id."<br>";
	echo $user_name."<br>";
	echo $org_id."<br>";
	echo $org_name."<br>";
	echo $group_id."<br>";
	echo $group_name."<br>";
	echo $access_level."<br>";
	echo $system_type."<br>";
*/



?>
Return current item: Homeless Mangement Information System