<?php

class Auth extends PhpObject
{
	const ALGO = PASSWORD_DEFAULT;
	const COST = 12;
	const TOKEN_SEP = '|';
	const USER_COOKIE_PASS = 'checksum';
	
	const MEMBER_INACTIVE = 0;
	const MEMBER_ACTIVE = 1;
	const CLEARANCE_MEMBER = 1;
	const CLEARANCE_ADMIN = 9;
	
	/**
	 * Database Connection
	 * @var MySqlManager
	 */
	private $oMySql;
	private $iUserId;
	private $sApiKey;
	
	public function __construct(MySqlManager $oMySql, $sApiKey='', $bAutoLogin=true)
	{
		$this->oMySql = $oMySql;
		$this->setUserId(0);
		$this->sApiKey = $sApiKey;
		if($bAutoLogin) $this->autoLogIn();
	}
	
	private function setUserId($iUserId)
	{
		$this->iUserId = $iUserId;
	}
	
	public function getUserId()
	{
		return $this->iUserId;
	}
	
	public function isLoggedIn()
	{
		return ($this->getUserId() > 0);
	}
	
	public function logMeIn($sToken)
	{
		$this->oMySql->setTrace(true);
		$sDesc = '';
		if($sToken!='')
		{
			$sLoginToken = addslashes(strstr($sToken, self::TOKEN_SEP, true));
			$sPassToken = substr(strstr($sToken, self::TOKEN_SEP), strlen(self::TOKEN_SEP));
			if($sLoginToken!='' && $sPassToken!='')
			{
				$asEmpl = $this->oMySql->selectRow(Pedidor::USER_TABLE, array("MD5(".MySqlManager::getText(Pedidor::USER_TABLE).")"=>$sLoginToken));
				if(!empty($asEmpl))
				{
					if(self::CheckPassword($sPassToken, $asEmpl['pass']))
					{
						$this->setUserId($asEmpl[MySqlManager::getId(Pedidor::USER_TABLE)]);
						$this->resetAuthCookie($this->getUserId());
					}
					else $sDesc = 'wrong password';
				}
				else $sDesc = 'unknown nickname';
			}
			else $sDesc = 'corrupted token, please login again';
		}
		else $sDesc = 'no credentials has been received by the server';
		
		return Pedidor::getJsonResult($this->isLoggedIn(), $sDesc);
	}
	
	public function autoLogIn()
	{
		if(isset($_COOKIE[self::USER_COOKIE_PASS]))
		{
			$sCookie = $_COOKIE[self::USER_COOKIE_PASS];
			$iUserId = addslashes(strstr($sCookie, self::TOKEN_SEP, true));
			$sCookie = substr(strstr($sCookie, self::TOKEN_SEP), strlen(self::TOKEN_SEP));
		
			$asEmpl = $this->oMySql->selectRow(Pedidor::USER_TABLE, array(MySqlManager::getId(Pedidor::USER_TABLE)=>$iUserId));
			if(!empty($asEmpl))
			{
				if($sCookie==$asEmpl['cookie'])
				{
					$this->setUserId($asEmpl[MySqlManager::getId(Pedidor::USER_TABLE)]);
		
					//Reset pass once a day
					if(mb_substr($asEmpl['led'], 0, 10) != date('Y-m-d')) $this->resetAuthCookie($this->getUserId());
				}
				else $this->addError('token corrompu pour le user '.$asEmpl[MySqlManager::getId(Pedidor::USER_TABLE)]);
			}
			else $this->addError('Utilisateur '.$iUserId.' inconnu');
		}
	}
	
	public function addUser($sSafeNickName, $sNickName, $bLogMeIn=false)
	{
		$sPass = self::HashPassword(self::getLoginToken($sSafeNickName));
		$bExist = $this->oMySql->pingValue(Pedidor::USER_TABLE, array(MySqlManager::getText(Pedidor::USER_TABLE)=>$sSafeNickName));
		if($bExist) return -1;
		else
		{
			$asUserInfo = array(MySqlManager::getText(Pedidor::USER_TABLE)=>$sSafeNickName, 'active'=>self::MEMBER_ACTIVE, 'clearance'=>self::CLEARANCE_MEMBER);
			$iUserId = $this->oMySql->insertRow(Pedidor::USER_TABLE, $asUserInfo);
			if($iUserId>0)
			{
				$this->resetPass($iUserId);
				if($bLogMeIn) $this->logMeIn(md5($sSafeNickName).self::TOKEN_SEP.$this->getLoginToken($sSafeNickName));
			}
		}
		return $iUserId;
	}
	
	//TODO integrate with logMeIn()
	public function checkApiKey($sApiKey)
	{
		return ($this->sApiKey!='' && $sApiKey==$this->sApiKey);
	}
	
	private function resetPass($iUserId=0)
	{
		$sUserIdCol = MySqlManager::getId(Pedidor::USER_TABLE);
		$sUserTextCol = MySqlManager::getText(Pedidor::USER_TABLE);
		
		$asInfo = array('select'=>array($sUserIdCol, $sUserTextCol), 'from'=>Pedidor::USER_TABLE);
		if($iUserId>0) $asInfo['constraint'] = array($sUserIdCol=>$iUserId);
		
		$asUsers = $this->oMySql->selectRows($asInfo);
		foreach($asUsers as $asUser)
		{
			$sToken = self::HashPassword(self::getLoginToken($asUser[$sUserTextCol]));
			$this->oMySql->updateRow(Pedidor::USER_TABLE, array(MySqlManager::getId(Pedidor::USER_TABLE)=>$asUser[$sUserIdCol]), array('pass'=>$sToken));
		}
	}
	
	private static function getLoginToken($sPass)
	{
		//Add Server Name
		$sServerName = array_key_exists('SERVER_NAME', $_SERVER)?$_SERVER['SERVER_NAME']:$_SERVER['PWD'];
		$sAppPath = $_SERVER['REQUEST_SCHEME'].'://'.str_replace(array('http://', 'https://'), '', $sServerName.dirname($_SERVER['SCRIPT_NAME']));
		$_GET['serv_name'] = $sAppPath.(mb_substr($sAppPath, -1)!='/'?'/':'');
		return md5($sPass.$_GET['serv_name']);
	}
	
	private function resetAuthCookie($iUserId)
	{
		$sNewPass = self::getAuthCookie($iUserId);
		$iTimeLimit = time()+60*60*24*30;
		$this->oMySql->updateRow(Pedidor::USER_TABLE, array(MySqlManager::getId(Pedidor::USER_TABLE)=>$iUserId), array("cookie"=>$sNewPass));
		setcookie(self::USER_COOKIE_PASS, $iUserId.self::TOKEN_SEP.$sNewPass, $iTimeLimit);
	}
	
	private static function getAuthCookie()
	{
		return self::HashPassword
		(
			$_SERVER['HTTP_USER_AGENT'].
			$_SERVER['REMOTE_ADDR'].
			$_SERVER['REQUEST_TIME'].
			mb_strstr(microtime(), ' ', true).
			$_SERVER['SERVER_SIGNATURE'].
			$_SERVER['SERVER_ADMIN']
		);
	}
	
	private static function HashPassword($sPass)
	{
		return password_hash($sPass, self::ALGO, array('cost'=>self::COST));
	}

	private static function CheckPassword($sPass, $sHash)
	{
		return password_verify($sPass, $sHash);
	}
}

?>