ThinkPHP权限问题

 1 <?php
 2 namespace Common\Controller;
 3 use Think\Controller;
 4 use Think\Auth;
 5 
 6 class AuthController extends Controller {
 7     //判断用户是否有该操作的权限,并判断是否要将这个权限插入规则表
 8     private function checkAuth() {
 9         $user = session('result.username');
10         $uid = session('result.id');
11         $controllerIndex = MODULE_NAME."/".CONTROLLER_NAME."/".ACTION_NAME;
12         $dbAuthRule = M('auth_rule');
13         $map['name'] = $controllerIndex;
14         $rule = $dbAuthRule->where($map)->select();
15         
16         //如果权限表中没有这个操作,就将其插入表中
17         if(!$rule) {
18             $data['name'] = $controllerIndex;
19             $data['status'] = '1';
20             $data['type'] = MODULE_NAME;
21             $dbAuthRule->add($data);
22         }
23         
24         //判断当前用户是否在登录状态
25         if (empty($user)) {
26             $this->error("请重新登录");
27             die;
28         }
29         
30         //实例化权限类,检查用户的访问权限
31         $auth = new Auth();
32         //$test = $auth->check($controllerIndex, $uid);
33         if (!$auth->check($controllerIndex, $uid)) {
34             $this->error('您没有权限访问,请联系管理员');
35         }
36     }
37     //实例化AuthController时,会自动调用_initialize函数
38     protected function _initialize() {
39         $this->checkAuth();
40     }
41 }

使用ThinkPHP框架时,在公共模块Common的Controller 建立AuthController类。之后无论是在前台模块或者后台模块中,在编写接口时,首先实例化AuthController,如果没有访问权限,会自动判断。当然前提是数据库中已建立Think/Auth中指定的表。

 

posted @ 2017-03-15 10:52  鲁山人  阅读(870)  评论(0编辑  收藏  举报