<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * This class provides the default controller for rendering pages.
 *
 * @package    lnApp
 * @subpackage Page
 * @category   Abstract/Controllers
 * @author     Deon George
 * @copyright  (c) 2010 Deon George
 * @license    http://dev.leenooks.net/license.html
 */
abstract class Controller_lnApp_Default extends Controller {
	/**
	 * The variable that our output is stored in
	 */
	protected $output = NULL;
	/**
	 * @var string page media route as per [Route]
	 */
	protected $mediaroute = 'default/media';
	/**
	 * Controls access to this controller.
	 * Can be set to a string or an array, for example 'login' or array('login', 'admin')
	 * Note that in second(array) example, user must have both 'login' AND 'admin' roles set in database
	 *
	 * @var boolean is authenticate required with this controller
	 */
	protected $auth_required = FALSE;
	/**
	 * If redirecting to a login page, which page to redirect to
	 */
	protected $noauth_redirect = 'login';
	/**
	 * Controls access for separate actions, eg:
	 * 'adminpanel' => 'admin' will only allow users with the role admin to access action_adminpanel
	 * 'moderatorpanel' => array('login', 'moderator') will only allow users with the roles login and moderator to access action_moderatorpanel
	 *
	 * @var array actions that require a valid user
	 */
	protected $secure_actions = array();

	/**
	 * Check and see if this controller needs authentication
	 *
	 * if $this->auth_required is TRUE, then the user must be logged in only.
	 * if $this->auth_required is FALSE, AND $this->secure_actions has an array of
	 * methods set to TRUE, then the user must be logged in AND a member of the
	 * role.
	 *
	 * @return boolean
	 */
	protected function _auth_required() {
		// If our global configurable is disabled, then continue
		if (! Kohana::Config('config.method_security'))
			return FALSE;

		return (($this->auth_required !== FALSE && Auth::instance()->logged_in() === FALSE) ||
			(is_array($this->secure_actions) && array_key_exists($this->request->action(),$this->secure_actions) &&
			Auth::instance()->logged_in($this->secure_actions[$this->request->action()]) === FALSE));
	}

	public function before() {
		parent::before();

		// Check user auth and role
		if ($this->_auth_required()) {
			// For AJAX/JSON requests, authorisation is controlled in the method.
			if (Request::current()->is_ajax() && $this->request->action() === 'json') {
				// Nothing required.

			// For no AJAX/JSON requests, display an access page
			} elseif (Auth::instance()->logged_in(NULL,get_class($this).'|'.__METHOD__)) {
				Request::current()->redirect('login/noaccess');

			} else {
				Session::instance()->set('afterlogin',Request::detect_uri());
				Request::current()->redirect($this->noauth_redirect);
			}
		}
	}

	public function after() {
		parent::after();

		// Generate and check the ETag for this file
		$this->response->check_cache(NULL,$this->request);
	}
}
?>