Auth认证类通用认证代码

jerry thinkphp 2015年11月19日 收藏
使用Auth.class.php对系统进行认证,其中频繁用到认证,在前面的基础上做了改进。
登陆成功后,将当前用户的id存入:session('uid',$curUserId);
在Config.php中配置:
  1. 'NOT_AUTH_MODULE'        =>'Public,Index,Test',    // 默认无需认证模块
  2.     'NOT_AUTH_ACTION'        =>'',        // 默认无需认证操作
  3.     'SUPERADMIN_UID'=>array(1,2),
  1. function authcheck($url,$relation='or'){

  2.     $linkArr=explode('/',$url);
  3.     if(!(count($linkArr)==2||count($linkArr)==3))return;
  4.                     
  5.     if(count($linkArr)==2){
  6.         $CUR_MODULE_NAME=$linkArr[0];
  7.         $CUR_ACTION_NAME=$linkArr[1];
  8.     }else{
  9.         $CUR_MODULE_NAME=$linkArr[1];
  10.         $CUR_ACTION_NAME=$linkArr[2];
  11.     }        
  12.     $notAuth=in_array($CUR_MODULE_NAME, explode(",", C("NOT_AUTH_MODULE"))) || in_array($CUR_ACTION_NAME, explode(",", C("NOT_AUTH_ACTION")));
  13.         
  14.     $AUTH_CONFIG=C('AUTH_CONFIG');
  15.     if(!$AUTH_CONFIG['AUTH_ON']||$notAuth)return true;
  16.     else{
  17.         if(!session("?uid"))return false;

  18.         if(in_array(session('uid'),C('SUPERADMIN_UID')))return true;
  19.         else{
  20.             import('ORG.Util.Auth');
  21.             $auth=new Auth();
  22.             if($auth->check($CUR_MODULE_NAME.'/'.$CUR_ACTION_NAME,session('uid'),$relation))return true;
  23.             else return false;
  24.         }
  25.     }
  26. }
所有的Action均需要继承CommonAction.class.php,在Common的 _initialize()方法中使用:
  1. if(!authcheck(MODULE_NAME.'/'.ACTION_NAME))$this->error('你没有权限',U('Index/index'));
在后台中对think_auth_rule数据表中在name字段存入操作的url,如:User/index,User/addRecord......

有不明白的地方有问必答,欢迎大家探讨。