<?php

include 'db.php';
include 'error.php';


function authenticateUser($connection,$username,$password)
{
	//username and pass both set
	if(!isset($username) || !isset($password))
		return false;
	$salt=substr($username,0,2);
	$crypted_password=crypt($password,$salt);
	$query="SELECT password FROM users WHERE user_name='$username' AND password='$crypted_password'";

	if(!($result = @mysql_query($query,$connection)))
		showerror();
	if(mysql_num_rows($result)!=1)
		return false;
	else
		return true;
}


//Main
session_start();
$authenticated=false;

$appUsername=clean($_POST["formUsername"],15);
$appPassword=clean($_POST["formPassword"],15);

if(!($connection=@mysql_connect($hostName, $dbUsername, $dbPassword)))
	die("Could not connect to DB");

if(!(mysql_select_db ($databaseName, $connection)))
	showerror();

$authenticated=authenticateUser($connection,$appUsername,$appPassword);

if($authenticated==true)
{
	//register user and ip
	session_register("authenticatedUser");
	$_SESSION["authenticatedUser"]=$appUsername;

	session_register("loginIpAddress");
	$_SESSION["loginIpAddress"]=$_SERVER["REMOTE_ADDR"];

	header("Location:admin.php");
}else{
	//auth failed
	session_register("loginMessage");
	$_SESSION["loginMessage"]="Could not connect as \"$appUsername\"";
	header("Location:admin_login.php");

}

?>