<?php defined('SYSPATH') or die('No direct script access.');
class Adminauth_Core{
	function __construct(){
		$this->session	=	Session::instance();
		$this->db		=	new Database();
		$this->uri		=	new URI();
	}
	//认证用户
	function authUser(){
		//取得资源
		$allAcl		=	$this->getAllAcl();
		//取得访问默认资源
		$defaultAcl	=	$allAcl['guest'];
		$defaultAcl	=	array_merge($defaultAcl,array("login+index"));
		//取得当前控制器
		$controller	=	$this->uri->segment(1);
		$module		=	$this->uri->module();
		if(!$controller){
			list($controller,$action)	=	explode("/",Kohana::config("routes._default"));
			if(!$action){
				$action	=	"index";
			}
		}
		else{
			$action		=	$this->uri->segment(2)?$this->uri->segment(2):"index";
		}
		$currentUri		=	$controller."+".$action;
		@define("MODULE",$module);
		@define("CONTROLLER",$controller);
		@define("ACTION",$action);
		//取得用户数据
		$user			=	$this->session->get('adminmanager');
		if(@$user->user_id){
			//刷新SESSION数据
			$this->setUserSession($user->user_id);
			$user		=	$this->session->get('adminmanager');
			$userAcl	=	$allAcl[$user->group_id];
		}
		else{
			$userAcl	=	array();
		}
		//合并资源
		$allAcl			=	array_merge($userAcl,$defaultAcl);
		if(!in_array($currentUri,$allAcl)){
			if(!@$user){url::redirect(BASEURI.'login');		}
			if(@$user){	url::redirect(BASEURI.'front/report/group_no_auth/'.base64_encode("admin/main")."/true");		}
		}
	}
	//设置用户数据SESSION
	function setUserSession($user_id=false){
		$sql	=	"
			SELECT u.*,u_g.group_name,u_g.group_value,u_g.group_id  
			FROM ".DBFIX."user as u 
			JOIN ".DBFIX."user_group as u_g ON u.user_role=u_g.group_id 
			WHERE user_id='$user_id'
		";
		$result	=	$this->db->query($sql);
		$this->session->set('adminmanager',$user=$result->current());
	}
	function getAllAcl(){
		$groupacl	=	DATADIR."cache/groupacl.php";
		if(file_exists(DATADIR."cache/groupacl.php")){
			return include($groupacl);
		}
		else{
			$cacheAcl	=	new Auth_Acl_Model();
			$cacheAcl->cache();
			return include($groupacl);
		}
	}
}