我试图在Codeigniter中使用_remap方法创建一个全局身份验证。以下是访问控制器/方法的网站条件:
- 方法必须存在。
- 某些控制器只能在admin用户登录后才能访问。
- 部分控制器只能由admin访问。
_remap方法写在MY_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');
}
}
代码是工作的,但我觉得它可以简化。我试过了,但它总是以无限重定向告终。有没有办法简化这个方法?
提前感谢。
我的偏好通常是将检查放在构造函数中,然后用$this->
返回user或adminfunction __construct()
{
parent::__construct();
if (!$this->user = $this->users->returnUser())
{
redirect("userlogin");
}
}
那么$this->user现在可以用于控制器调用的所有内容-模型和视图:
echo 'Hello ' . $this->user->first_name . ' ' . $this->user->last_name ;
假设你有Admins和Superadmin。你不需要检查这个管理员是否有访问这个控制器的权限?你可以在每个控制器构造函数中使用单独的检查:
if (!$this->admin = $this->admins->returnAdmin())
{
redirect("adminlogin");
}
// Or
if (!$this->superAdmin = $this->superadmins->returnSuperAdmin())
{
redirect("superadminlogin");
}
这也清楚地区分了你要重定向到的地方,这样他们就可以转到正确的登录页面。最后,当你查看控制器代码时,它会给你一个快速的提示——在页面的顶部,你会立即知道什么样的用户应该有权访问它。需要考虑的事情-强烈建议您不要在视图文件中检查登录或管理状态。创建更多的视图文件要安全得多。视图文件不应该负责确定某人是否已登录。基本上一旦你在构造函数中确定了查看器的状态——就这样了,你不需要再检查,直到下一次控制器调用。