有什么办法可以简化 codeigniter 中的全局身份验证吗?

Is there any way to simplify this global authentication in codeigniter?

我正在尝试使用 Codeigniter 中的 _remap 方法创建全局身份验证。以下是访问controller/method的网站条件:

  1. 方法必须存在。
  2. 某些控制器只有在 user/admin 已登录后才能访问。
  3. 有些控制器只能由管理员访问。

写在MY_Controller中的_remap方法会被所有controller继承。这是我的代码:

protected $must_login;
protected $must_admin;

public function _remap($method, $param = array())
{
  # Check if method exist
  if (method_exists($this, $method)) 
  {
    # Check whether the user has to be login to access it
    if ($this->must_login)
    {
      # Check whether the user has logged in
      if ($this->auth->is_loggedin()) 
      {
        # Check whether it has to be admin to access it
        if ($this->must_admin) 
        {
          # Check whether it is admin
          if ($this->auth->is_admin()) 
          {
            # Run the method
            return call_user_func_array(array($this, $method), $param);
          }
          else
          {
            # Redirecting to login form
            $this->go('auth');
          }
        }
        else
        {
          return call_user_func_array(array($this, $method), $param);
        }
      }
      else
      {
        $this->go('auth');
      }
    }
    else
    {
      return call_user_func_array(array($this, $method), $param);
    }
  }
  else
  {
    $this->go('auth');
  }
}

代码有效,但我觉得它可以简化。我已经尝试过,但它总是以无限重定向结束。有没有什么办法可以简单的用这个方法?

提前致谢。

我的偏好通常是将检查放在构造函数中,然后 return 用户或管理员使用 $this->

function __construct()
{

    parent::__construct();

    if (!$this->user = $this->users->returnUser())
    {
        redirect("userlogin");
    }

} 

然后 $this->user 现在可用于您的控制器调用的所有内容 - 模型和视图:

echo 'Hello ' . $this->user->first_name . ' ' . $this->user->last_name ; 

那么假设您有管理员和超级管理员。您不必检查 - 此管理员是否有权访问此控制器?您可以在每个控制器构造函数中使用单独的检查:

    if (!$this->admin = $this->admins->returnAdmin())
    {
        redirect("adminlogin");
    }

// Or 
    if (!$this->superAdmin = $this->superadmins->returnSuperAdmin())
    {
        redirect("superadminlogin");
    }

这也清楚地将您重定向到的位置分开,以便他们可以转到正确的登录页面。最后,当您查看控制器代码时,它会让您快速提神——在页面顶部,您将立即知道什么样的用户应该有权访问它。需要考虑的事情 - 强烈建议您不要在视图文件中检查登录或管理员状态。多创建几个视图文件就安全多了。您的视图文件不应该负责确定某人是否登录。所以基本上一旦你确定了构造函数中观众的状态 - 就是这样,你不需要再次检查直到下一次控制器调用。