1

我想检查用户是否有权访问 URL(控制器/方法)组合。它应该在被调用的控制器中调用的任何方法和方法属于它之前检查。

据我了解,钩子应该用于上面的逻辑,但是当我使用它时,我认为它与下面显示pre_controller的冲突。post_controller_constructor如果我改用post_controller它,那么它会起作用,但这次逻辑会受到影响。

我怎么解决这个问题?

谢谢

配置/挂钩

//Used to authenticate user session to decide whether to authenticate site or not
$hook['post_controller_constructor'] =
array(
'class'    => 'site_authentication',
'function' => 'authenticate',
'filename' => 'site_authentication.php',
'filepath' => 'hooks',
'params'   => null
);


//Used to authenticate permitted controllers
$hook['pre_controller'] =
array(
'class'    => 'permitted_controllers',
'function' => 'authenticate',
'filename' => 'permitted_controllers.php',
'filepath' => 'hooks',
'params'   => null
);

应用程序/挂钩

//This works fine
class site_authentication
{
    private $CI;

    public function __construct()
    {
        $this->CI =& get_instance();
    }

    public function authenticate()
    {
        if (! $this->CI->session->userdata('site'))
        {
            redirect('to error page');
        }

        $user_session = $this->CI->session->userdata('site');
        //Some more stuff here
    }
}



//This doesn't work with pre_controller
class permitted_controllers
{
    private $CI;

    public function __construct()
    {
        $this->CI =& get_instance();
    }

    public function authenticate()
    {
        $user_session = $this->CI->session->userdata('site');

        //Url is set here, ignore syntax error below
        $url = $this->CI->uri->segment(1) . 2 . 3;

        if (! in_array($url, $user_session['controllers']))
        {
            redirect('to error page');
        }
    }
}

如果我将它们两个结合起来,它们可以正常工作,post_controller_constructor但不能单独工作?

$hook['post_controller_constructor'] [] =
array(
'class'    => 'site_authentication',
'function' => 'authenticate',
'filename' => 'site_authentication.php',
'filepath' => 'hooks',
'params'   => null
);

$hook['post_controller_constructor'] [] =
array(
'class'    => 'permitted_controllers',
'function' => 'authenticate',
'filename' => 'permitted_controllers.php',
'filepath' => 'hooks',
'params'   => null
);
4

2 回答 2

2

pre_controllerhook 在构建超级对象之前运行,因此它不是挂钩到 CI 的正常语法(例如$this->db->query())的可行选项。

我建议创建一个基本控制器(又名 MY_Controller 或其他名称)并将权限检查添加到其构造函数中。然后,每个应该运行权限检查的控制器将扩展 MY_Controller 而不是 CI_Controller。这是 Phil Sturgeon 关于基本控制器的经典文章。

每次页面加载都会调用钩子。如果您不需要在某处检查权限,则需要将该逻辑添加到您的钩子中,或者在其他地方添加逻辑以尝试禁用它。不是很可扩展。使用基本控制器,添加权限检查就像扩展不同的类一样简单。

于 2013-03-13T06:55:16.123 回答
0

pre_controller 钩子在超级对象完全构造之前执行阅读更多here

于 2013-03-12T18:04:55.710 回答