Codeigniter:使用继承控制登录权限

时间:2011-10-26 01:22:37

标签: php codeigniter inheritance login privileges

我希望使用我的codeigniter项目进行登录。

一些注意事项:

1)外面有两个不需要身份验证的控制器。一个用于提供信息(splash_pages等),另一个用于创建登录会话。

2)所有其他控制器都从主控制器继承,作为其构造函数的一部分,要求您登录或者将其踢到登录屏幕。

到目前为止,上述2个适用于登录和退出。

就代码而言:

我正在描述的主控制器2) 它位于Codeigniter的Core文件夹中

class MY_Controller extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('cart');
        $this->load->library('session');
        $this->load->helper('form');
        $this->load->library('form_validation');
        if (!$this->session->userdata('loggedin')){
            redirect('/sessions/log_in/','refresh');
        }
    }

使用登录系统的类:

class Records extends MY_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('some_model');
        $this->load->library('some_library');
    }

这个想法是在对象构造上,它将检查用户是否登录,并正确构造对象或重定向到登录屏幕。

但是,项目的需求有所改变。现在要求规定大约有6个不同的用户组,其权限可以安排到子集中。 A可以做I,B可以做A + II,C可以做B + III,依此类推。有一些轻微的提示,可能存在非严格子集的权限(IE只有B可以执行任务IV),但尚未确认,所以我想保持我的选项开放。

我是如何设想的那样,MY_Controller中有一堆继承自MY_Controller的控制器。

例如在Core文件夹中:

class MY_AsController extends MY_Controller {
    public function __construct(){
        parent::__construct();
        $accountType = $this->session->userdata('accountType');
        if(!($accountType == declaredConstant)){
            redirect('/someController/someMethod','refresh');
        }
    }

然后在controllers文件夹中:

class AControlPage extends MY_AsController {
     //Insert page functions that only As have access to here
}

不幸的是,在实践中应用它不会产生任何错误,只会产生空白页面。 我不知道在那之后该怎么做。

1 个答案:

答案 0 :(得分:1)

结束不更改父构造函数或完全使用更多继承:

在My_Controller中添加了以下内容:

public function allowedToView($userAccountType, $requiredAccountTypes){
    //If user not in allowed userGroup
    if(!(in_array($userAccountType,$requiredAccountTypes))){
        redirect('/sessions/not_allowed/','refresh');
    }
}

将子构造函数更改为:

public function __construct() {
    parent::__construct();
    $accountType = $this->session->userdata('accountType');
    $allowedTypes = array(declaredConstant1,declaredConstant2,...);
    $this->allowedToView($accountType,$allowedTypes);
}

谢谢,约瑟夫的洞察力让我远离了我的疯狂!

相关问题