最近在写个php SMS的练手项目,遇到了权限管理方面的问题
权限校验用到了钩子,这个能一定程度减少对其他页面代码的入侵,减少耦合和java的切面编程有类似的设计思路。
前台和后台的权限校验是有区别的。
前台只需要判断用户是否有登录即可
后台则需要根据配置文件,对每个模块的权限和用户的权限做对比,
其实前台权限校验也可以参考后台的方式,只是略复杂,这就两种方式分开来说明
一、通用步骤
1、开启狗子
$config['enable_hooks'] = TRUE;
2、新建一个钩子
在config目录下的hooks.php文件中定义一个新的钩子;
$hook['post_controller_constructor'] = array(
'class' => 'Login_check',//希望添加动作的类名,可以为空
'function' => 'user_check',//希望添加动作的方法名
'filename' => 'Login_check.php',//文件名
'filepath' => 'hooks',//文件所在路径,如果文件放在application目录下,则路径微'hooks',如果文件在hooks目录下temp目录,那么路径就应该为hooks/temp
'params' => array();//传递的参数,可以为空
);
创建执行的权限脚本,只需要判断是否登录即可
<?php
/**
* 用户登录验证,所有不是以login开头的路由都要先登录
*/
class Login_check{
private $CI;
public function __construct()
{
$this->CI = &get_instance();
}
public function user_check()
{
$this->CI->load->helper('url');
if (!preg_match("/login.*/i", uri_string()))
{
if(!$this->CI->session->userdata('username'))
{
redirect('login/index');
}
}
}
}
三、后台校验
1.配置hooks文件如下:
/*
| -------------------------------------------------------------------------
| Hooks
| -------------------------------------------------------------------------
| This file lets you define "hooks" to extend CI without hacking the core
| files. Please see the user guide for info:
|
| http://codeigniter.com/user_guide/general/hooks.html
|
*/
$hook['post_controller_constructor'] = array(
'class' => 'Acl',
'function' => 'auth',
'filename' => 'acl.php',
'filepath' => 'hooks'
);
2.编写权限配置文件acl.php放在config目录下
它是个公共配置,按照模块-》模块下的权限这样存放
$config['AUTH'] = array(
SUPER_ADMIN => array(
'admin' => array('index', 'logout'),
),
ADMIN => array(
'admin' => array('index', 'logout'),
),
GUEST => array(
'admin' => array('index', 'logout'),
),
);
2.钩子代码,它是拿到url后,拿用户的权限和url模块对应的权限做对比的,如果没有,就提示错误
class Acl {
private $url_model;
private $url_method;
private $CI;
function Acl()
{
$this->CI =& get_instance();
$this->CI->load->library('session');
$this->url_model = $this->CI->uri->segment(1);
$this->url_method = $this->CI->uri->segment(2);
}
function auth()
{
$user = $this->CI->session->userdata('USER');
if(empty($user))
$user->status = 0;
$this->CI->load->config('acl');
$AUTH = $this->CI->config->item('AUTH');
if(in_array($user->status, array_keys($AUTH))){
$controllers = $AUTH[$user->status];
if(in_array($this->url_model, array_keys($controllers))){
if(!in_array($this->url_method, $controllers[$this->url_model])){
show_error('您无权访问该功能,该错误已经被记录!点击<a href="'. site_url('admin/logout') .'">返回</a>');
}
}else{
show_error('您无权访问该模块,该错误已经被记录!点击<a href="'. site_url('admin/logout') .'">返回</a>');
}
}
else
show_error('错误的用户类型,该错误已经被记录!点击<a href="'. site_url('admin/logout') .'">返回</a>');
}
}
文章参考: