<?php
require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'AccessManager.class.php';
require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'User.class.php';

class AuthAspect extends AOWP_PerSessionAspect {
	
	/* Keep the ID of the authenticated user. */
	private $_authenticatedUser = null;
	
	public function __construct() {

		/* Advice for access control based on the authentication */
		$accessCheckPC = new AOWP_RequestPointcut('.*'); 
		$accessCheckAdvice = new AOWP_BeforeAdvice();
		$accessCheckAdvice->setPointcut($accessCheckPC);
		$accessCheckAdvice->setAdviceBody('accessCheck');
		$this->addAdvice($accessCheckAdvice);

		/* Advice for the authentication */
		$authenticatePC = new AOWP_RequestPointcut('.*', array('action' => 'authentication'));
		$authenticateAdvice = new AOWP_BeforeAdvice();
		$authenticateAdvice->setPointcut($authenticatePC);
		$authenticateAdvice->setAdviceBody('authenticate');
		$this->addAdvice($authenticateAdvice);

		/* Advice for invalidating the authentication result. */
		$logoutPC = new AOWP_RequestPointcut('.*', array('action' => 'logout'));
		$logoutAdvice = new AOWP_BeforeAdvice();
		$logoutAdvice->setPointcut($logoutPC);
		$logoutAdvice->setAdviceBody('logout');
		$this->addAdvice($logoutAdvice);
		
	}
	
	public function accessCheck(AOWP_JoinPoint $joinPoint) {
		/* Display an authentication page to a not authenticated user. */
		if ($this->_authenticatedUser === null) { 
			include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'login.php';
			exit();
		}
	}
	
	public function authenticate(AOWP_JoinPoint $joinPoint) {
		if (isset($_POST['id']) && isset($_POST['passwd'])) {
			/* Save the authentication result in this aspect instance. */
			$this->_authenticatedUser = AccessManager::authentication($_POST['id'], $_POST['passwd']);
		}
	}
	
	public function logout(AOWP_JoinPoint $joinPoint) {
		$this->_authenticatedUser = null;
	}	
}
?>