<?php
/*
 *
 * sflog!
 * Copyright (C) 2005 Alberto Sfolcini <a.sfolcini@gmail.com>
 *
 * This file is a part of sflog!.
 *
 * sflog! is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * sflog! is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 */
	
/**
 * @title			: Auth
 * @description		: Check for authorizations   
 * @date			: 20-Oct-2005   
 * @author			: Alberto Sfolcini  <a.sfolcini@gmail.com>
 */
class Auth {

	/**
	 * Constructor
	 */
	function Auth(){
		session_start();
	}
	
	
	/**
	 * Unsets current authorization by disable session
	 */
	function unsetAuthorizations(){
		$_SESSION['userID'] = "";
		$_SESSION['login']	= false;
	}
	
	/**
	 * Returns true if given $userID and $password are valid
	 * @return boolean
	 */
	function authorize($userID,$password){
		$rightUserID 	= "admin";
		if ((strcmp(trim($userID),$rightUserID)==0)&&($this->checkPasswd($password))){
			// set sessions
			$_SESSION['userID'] = $userID;
			$_SESSION['login'] 	= true;
			return true;
		} else
			return false;
	}
	
	/**
	 * Return boolean, check if $password is right
	 * @param $password string
	 * @return boolean
	 */
	function checkPasswd($password){
		$pfile  = dirname(__FILE__).'/../admin/passwd';
  		if (file_exists($pfile))
  			$rightPassword	= trim(file_get_contents($pfile));
  		else
  			$rightPassword 	= "";
		$password = crypt($password,$rightPassword);	
		if (strcmp(trim($password),$rightPassword)==0){
			return true;
		} else
			return false;		
	}
	
	/**
	 * is authorized?
	 * @return boolean
	 */
	function isAuth(){
		if (isset($_SESSION['login'])){
			if ($_SESSION['login']) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * Manage authorization
	 * if no authorization is found, redirect to login form
	 */
	function checkAuth(){
		if (!$this->isAuth()){
			// redirect to first page
			$this->goHome("/login.php");
		}
	}
	
	/**
	 * Redirect to HomePage
	 */
	function goHome($relative_url){
		header ("Location: http://".$HTTP_SERVER_VARS['HTTP_HOST'] .dirname($HTTP_SERVER_VARS['PHP_SELF']) ."/".$relative_url);					
	}
	
	
} // end class
?>