<?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 $_authedUser = null;

	public function __construct() {
		$allReqPC = new AOWP_RequestPointcut('.*');
//		$allReqPC = new AOWP_RequestPointcut('^html/.*');
		
		/* Advice for access control based on the authentication */
		$loginChkIfPC = new AOWP_IfPointcut('$aspect->getUser() == null');
		$checkAdv = new AOWP_BeforeAdvice();
		$checkAdv->setPointcut($allReqPC->opAnd($loginChkIfPC));
		$checkAdv->setAdviceBody('_chk');
		$this->addAdvice($checkAdv);

		/* Advice for the authentication */
		$authAdvice = new AOWP_BeforeAdvice();
		$authAdvice->setPointcut($allReqPC);
		$authAdvice->setAdviceBody('_auth');
		$this->addAdvice($authAdvice);

	}
	
	public function getUser() {
		return $this->_authedUser;
	}
	
	protected function _chk(AOWP_JoinPoint $jp) {
		/* Display an authentication page to a not authenticated user. */
		include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'login.php';
		AOWP_AspectInstanceManager::releaseInstance($this);
		exit();
	}
	protected function _auth(AOWP_JoinPoint $jp) {
		$id = $jp->getFormData('id');
		$passwd = $jp->getFormData('passwd');
		if ($id != null && $passwd != null) {
			/* Save the authentication result in this aspect instance. */
			$this->_authedUser = AccessManager::auth($id, $passwd);
		}
	}
	
}
?>