首页 > 代码库 > Bootstrap+Thinkphp3.2+Auth认证+jquery-validator后台

Bootstrap+Thinkphp3.2+Auth认证+jquery-validator后台

Auth权限认证

本例采用auth权限认证,用户和用户组采用多对多关系处理,自动添加rule规则,带有jquery-validator插件,自动控制菜单显示或隐藏。

 

config.php中的配置

 

‘AUTH_CONFIG‘=>array(

   ‘AUTH_ON‘ => true, //认证开关

   ‘AUTH_TYPE‘ => 1, // 认证方式,1为时时认证;2为登录认证。

   ‘AUTH_GROUP‘ => ‘think_auth_group‘, //用户组数据表名

   ‘AUTH_GROUP_ACCESS‘ => ‘think_auth_group_access‘, //用户组明细表

   ‘AUTH_RULE‘ => ‘think_auth_rule‘, //权限规则表

   ‘AUTH_USER‘ => ‘think_user‘//用户信息表

 )

 

第一步、Thinkphp3.2中的library下有Auth.class.php有所需的三个表及注释。创建数据表。自己还需建一张用户表。

n       think_auth_rule,规则表(存放所有的权限规则)

n       think_auth_group 用户组表(存放一个用户组有哪些权限)

n       think_auth_group_access 用户组明细表(其实就是叫用户表和用户组的中间表)

n       think_user 用户表(需自建)

 

 

第二步、config.php中配置auth认证。

‘AUTH_CONFIG‘=>array(

   ‘AUTH_ON‘ => true, //认证开关

   ‘AUTH_TYPE‘ => 1, // 认证方式,1为时时认证;2为登录认证。

   ‘AUTH_GROUP‘ => ‘think_auth_group‘, //用户组数据表名

   ‘AUTH_GROUP_ACCESS‘ => ‘think_auth_group_access‘, //用户组明细表

   ‘AUTH_RULE‘ => ‘think_auth_rule‘, //权限规则表

   ‘AUTH_USER‘ => ‘think_user‘//用户信息表

 )

 

第三步、需要验证的类都继承CommonController。创建CommonController.class.php文件。(此类针对多入口的情况)

<?php

namespace Admin\Controller;

use Think\Controller;

class CommonController extends Controller {

  public function _initialize () {

      if(!isset($_SESSION[C(‘USER_AUTH_KEY‘)])){ //判断是否有uid

            $this->redirect("Public/login");

        }

      $Auth = new \Think\Auth();

      $module_name=CONTROLLER_NAME.‘/‘.ACTION_NAME;

      if($_SESSION[‘uname‘]==C(‘ADMIN_AUTH_KEY‘)){  //以用户名来判断是否是超级管理员,绕过验证,不用用户组来判断的原因是用户组有时候是中文  ,而且常删除或更改。

          return true;

      }

      if(!$Auth->check($module_name,$_SESSION[C(‘USER_AUTH_KEY‘)])){

          $this->error(‘没有权限‘);

      }

  }

}

 

 

第四步、登录验证的PublicController和以前都差不多。创建PublicController.class.php

 

<?php

namespace Admin\Controller;

use Think\Controller;

class PublicController extends Controller {

    public function index(){

        $this->display();

    }

 

    //登录页

    public function login(){

        $this->display();

    }

 

    //登出

    public function logout(){

        if($_SESSION[C(‘USER_AUTH_KEY‘)]) {

            session_destroy();

            $this->redirect("Public/login");

        }else {

            $this->error(‘已经登出!‘);

        }

    }

 

    //验证登陆表单

    public function checkLogin(){

       $username=I(‘username‘,‘‘);

        $password=I(‘password‘,‘‘);

        $verify_code=I(‘verify‘,‘‘);

        if($username==‘‘||$password==‘‘||$verify_code==‘‘){

            $this->redirect("Public/login");

        }

        if(!$this->_verifyCheck($verify_code)){

            $this->error("验证码错误!!!");

        }

        $user=M(‘user‘)->where(array(‘username‘=>$username))->find();

        if(!$user||md5($password)!=$user[‘password‘]){

            $this->error("用户名或密码错误!!!");

        }

        if(!$user[‘status‘]){   //status为0时表示锁定

            $this->error("用户被锁定!!!");

        }else{

           $data[‘login_ip‘] =  get_client_ip();

            $data[‘last_login_time‘]=time();

            if(M("user")->where(array(‘id‘=>$user[‘id‘]))->save($data)){

                M("user")->where(array(‘id‘=>$user[‘id‘]))->setInc("login_num");

            }

            session(C(‘USER_AUTH_KEY‘),$user[‘id‘]);

            session(‘uname‘,$user[‘username‘]);

            $this->success("登录成功...",U("Index/index"));

        }

    }

 

    //验证码

    public function verify(){

        $config = array(   

            ‘fontSize‘    =>    20,     // 验证码字体大小   

            ‘length‘      =>    1,      // 验证码位数   

            ‘useNoise‘    =>   false,  // 关闭验证码杂点

            ‘imageH‘    =>  50,          // 验证码图片高度

            ‘imageW‘    =>  200,          // 验证码图片宽度

        );

        $Verify =new \Think\Verify($config);

        $Verify->entry();

    }

 

    //验证验证码

    private function _verifyCheck($code, $id = ‘‘){

        $verify = new \Think\Verify();

        return $verify->check($code, $id);

    }

}

到这里,auth的权限认证就基本完成

第五步、创建AuthController.class.php(逻辑代码如下,就是一些CURD),多加了一个register方法,用来自动把规则的放入数据库中.本人把register放在function.php中方便其他类调用。用户和用户组采用多对多的关系处理,方便权限更为精细。

 

<?php

namespace Admin\Controller;

use Think\Controller;

class AuthController extends CommonController {

 

    //Auth认证管理

    public function index(){

        //获取用户信息

        $user=D("user")->relation(true)->field("password",true)->select();

        $this->user=$user;

        //获取用户组信息

        $group=M("auth_group")->select();

        $obj=M("auth_rule");

        foreach($group as $k=>$v){

            $map[‘id‘] = array(‘in‘,$group[$k][‘rules‘]);

            $group[$k][‘group‘]=$obj->where($map)->select();

        }

        $this->group=$group;

        //获取rule规则

        $this->rule=M("auth_rule")->select();

        //$ip = new \Org\Net\IpLocation("UTFWry.dat");

        //$location=$ip->getlocation();

        //p($location);die;

        //p($group);die;

        $this->display();

    }

 

    //添加后台用户及表单处理

    public function user(){

        if(IS_POST){

            $data=http://www.mamicode.com/array(

                ‘username‘=>I(‘username‘,‘‘,‘trim‘),

               ‘remark‘=>I(‘remark‘,‘‘,‘trim‘),

               ‘password‘=>I(‘password‘,‘‘,‘md5‘),

               ‘status‘=>I(‘status‘,0,‘intval‘),

               ‘rsgtime‘=>$_SERVER[‘REQUEST_TIME‘],

                ‘login_num‘=>0

          );

            if(!isset($_POST[‘role_id‘])){

                $this->error("请选择用户组...");

            }

            if($data[‘password‘]!=md5($_POST[‘repassword‘])){

                $this->error("两次密码不一致...");

            }

            if(M("user")->where(array(‘username‘=>$data[‘username‘]))->find()){

                $this->error("用户名已存在...");

            }

            if($lastInsertId=M("user")->add($data)){

                foreach($_POST[‘role_id‘] as $k=>$v){

                    $arr=array(

                        ‘uid‘=>$lastInsertId,

                        ‘group_id‘=>$_POST[‘role_id‘][$k]

                    );

                    M("auth_group_access")->add($arr);

                }

                M("auth_group_access")->add($arr);

                $this->success("添加成功...",U("Auth/index"));

            }else{

                $this->error("添加失败...");

            }

       }else{

            $this->group=M("auth_group")->field("id,title")->select();

           $this->display();

       }

      

    }

 

    //添加后台用户组及表单处理

    public function group(){

       if(IS_POST){

           $data=http://www.mamicode.com/array(

               ‘title‘=>I(‘title‘,‘‘,‘trim‘),

               ‘status‘=>I(‘status‘,0,‘intval‘)

               );

            if(M("auth_group")->where(array(‘title‘=>$data[‘title‘]))->find()){

                $this->error("用户组名称已存在...");

            }

           if(M("auth_group")->add($data)){

               $this->success("添加成功...",U("Auth/index"));

           }else{

               $this->error("添加失败...");

           }

       }else{

           $this->display();

       }

    }

 

    //添加后台权限及表单处理

    public function auth(){

       if(IS_POST){

           $data=http://www.mamicode.com/array(

               ‘name‘=>I(‘name‘,‘‘,‘trim‘),

               ‘title‘=>I(‘title‘,‘‘,‘trim‘),

               ‘condition‘=>I(‘condition‘,‘‘,‘trim‘),

               ‘status‘=>I(‘status‘,0,‘intval‘),

               ‘type‘=>I(‘type‘,0,‘intval‘),

               );

           if(M("auth_rule")->add($data)){

               $this->success("添加成功...",U("Auth/index"));

           }else{

               $this->error("添加失败...");

           }

       }else{

           $this->display();

       }

    }

 

    //注册rule规则

    public function register(){

        $class_name=get_class();

        return register($class_name);

    }

 

    //删除用户组

    public function deleteGroup(){

        if(IS_GET){

            if(!isset($_GET[‘id‘])){

                return false;

            }

            $id=I("id",0,"intval");

            if(!$id){

                return false;

            }

            if(M("auth_group")->where(array("id"=>$id))->delete()){

                M("auth_group_access")->where(array("group_id"=>$id))->delete();

                $this->success("删除成功...",U("Auth/index"));

            }else{

                $this->error("删除失败...");

            }

        }

    }

 

    //修改用户组

    public function modifyGroup(){

        if(IS_GET){

            if(!isset($_GET[‘id‘])){

                return false;

            }

            $id=I("id",0,"intval");

            if(!$id){

                return false;

            }

            $group=M("auth_group")->where(array("id"=>$id))->find();

            $rule=M("auth_rule")->select();

            foreach($rule as $k=>$v){

                if(in_array($rule[$k][‘id‘],explode(‘,‘,$group[‘rules‘]))){

                    $rule[$k][‘is_checked‘]=1;

                }else{

                    $rule[$k][‘is_checked‘]=0;

                }

            }

            $this->rule=$rule;

            $this->group=$group;

            $this->id=$id;

            //p($rule);die;

            $this->display();

        }elseif(IS_POST){

            $data=http://www.mamicode.com/array(

                ‘title‘=>I("title","","trim"),

                ‘rules‘=>implode(",",$_POST[‘rule‘]),

                ‘status‘=>I("status","","trim")

            );

            if(M("auth_group")->where(array("id"=>$_POST[‘id‘]))->save($data)){

                $this->success("修改成功...",U("Auth/index"));

            }else{

                $this->error("修改失败...");

            }

        }

    }

 

    //删除RULE

    public function deleteRule(){

        if(IS_GET){

            if(!isset($_GET[‘id‘])){

                return false;

            }

            $id=I("id",0,"intval");

            if(!$id){

                return false;

            }

            if(M("auth_rule")->where(array("id"=>$id))->delete()){

                $this->success("删除成功...",U("Auth/index"));

            }else{

                $this->error("删除失败...");

            }

        }

    }

 

    //修改RULE

    public function modifyRule(){

        if(IS_POST){

            if(!isset($_POST[‘id‘])){

                return false;

            }

            $id=I("id",0,"intval");

            unset($_POST[‘id‘]);

            if(!$id){

                return false;

            }

            if(M("auth_rule")->where(array("id"=>$id))->save($_POST)){

                $this->success("修改成功...",U("Auth/index"));

            }else{

                $this->error("修改失败...");

            }

        }

    }

 

    //删除用户

    public function deleteUser(){

        if(IS_GET){

            if(!isset($_GET[‘id‘])){

                return false;

            }

            $id=I("id",0,"intval");

            if(!$id){

                return false;

            }

            if(M("user")->where(array("id"=>$id))->delete()){

                M("auth_group_access")->where(array("uid"=>$id))->delete();

                $this->success("删除成功...",U("Auth/index"));

            }else{

                $this->error("删除失败...");

            }

        }

    }

 

    //修改用户

    public function modifyUser(){

        if(IS_POST){

            $id=I("id",0,"intval");

            if(!$id){

                return false;

            }

            $data[‘username‘]=I("username","","trim");

            $data[‘remark‘]=I("remark","","trim");

            $data[‘status‘]=I("status",0,"intval");

            $tmp=0;

            if(isset($_POST[‘role_id‘])){

                M("auth_group_access")->where(array("uid"=>$id))->delete();

                foreach ($_POST[‘role_id‘] as $key => $value) {

                    if(M("auth_group_access")->add(array("uid"=>$id,"group_id"=>$_POST[‘role_id‘][$key]))){

                        $tmp=1;

                    }

                }

            }

            if(trim($_POST[‘password‘])){

                if(md5($_POST[‘password‘])!=md5($_POST[‘repassword‘])){

                    $this->error("两次密码输入不一致...");

                }else{

                    $data[‘password‘]=I("password","","md5");

                }

            }

            if(M("user")->where(array("id"=>$id))->save($data)){

                $this->success("修改成功...",U("Auth/index"));

            }else{

                if($tmp){

                    $this->success("修改成功...",U("Auth/index"));

                }else{

                    $this->error("修改失败...");

                }

            }

 

        }elseif(IS_GET){

            if(!isset($_GET[‘id‘])){

                return false;

            }

            $id=I("id",0,"intval");

            if(!$id){

                return false;

            }

            $this->user=M("user")->where(array(‘id‘=>$id))->field("password",true)->find();

            $user_group=M("auth_group_access")->where(array("uid"=>$id))->select();

            $group=M("auth_group")->select();

            foreach($user_group as $key => $value){

                $user_group[$key][‘group_name‘]=M("auth_group")->where(array("id"=>$user_group[$key][‘group_id‘]))->getField("title");

            }

            $this->user_group=$user_group;

            $this->group=$group;

            $this->display();

        }

    }

}

 

function.php如下:(authCheck方法会在模板中有使用,用来控制菜单等显示或隐藏,不需自己写sql来循环判断显不显示

/**

  * 注册rule规则

  * @param class_name string  类的名称

  * @return str           返回错误或者正确信息

 */

function register($class_name){

    $data=http://www.mamicode.com/get_class_methods($class_name);

//把一些父类的方法过滤掉    $arr=array(‘_initialize‘,‘__set‘,‘__construct‘,‘display‘,‘show‘,‘fetch‘,‘buildHtml‘,‘theme‘,‘assign‘,‘ __set‘,‘get‘,‘__get‘,‘__isset‘,‘__call‘,‘error‘,‘success‘,‘ajaxReturn‘,‘redirect‘,‘__destruct‘);

    foreach($arr as $k=>$v){

        if(in_array($arr[$k],$data)){

            $tmp=array_keys($data,$arr[$k]);

            unset($data[$tmp[0]]);

        }

    }

    $obj=M("auth_rule");

    $msg=‘‘;

    foreach($data as $k=>$v){

        $data[$k]=CONTROLLER_NAME.‘/‘.$data[$k];

        if(!$obj->where(array(‘name‘=>$data[$k]))->find()){

            if($obj->add(array(‘name‘=>$data[$k]))){

                $msg=$msg.$data[$k].‘注册成功\n‘;

            }else{

                $msg=$msg.$data[$k].‘注册失败\n‘;

            }

        }else{

            $msg=$msg.$data[$k].‘已注册\n‘ ;

        }

    }

    echo "<script>alert(‘".$msg."‘);history.back(-1);</script>";

}

 

/**

  * 控制模板中菜单的显示

  * @param rule string|array  需要验证的规则列表,支持逗号分隔的权限规则或索引数组

  * @param uid  int           认证用户的id

  * @param string mode        执行check的模式

  * @param relation string    如果为 ‘or‘ 表示满足任一条规则即通过验证;如果为 ‘and‘则表示需满足所有规则才能通过验证

  * @return boolean           通过验证返回true;失败返回false

 */

function authCheck($rule,$uid,$type=1, $mode=‘url‘, $relation=‘or‘){

    $auth=new \Think\Auth();

    //获取当前uid所在的角色组id

    //$groups=$auth->getGroups($uid);

    if($_SESSION[‘uname‘]==C(‘ADMIN_AUTH_KEY‘)){

      return true;

    }

    return $auth->check($rule,$uid,$type,$mode,$relation)?true:false;

}

 

注:模板中使用authCheck的方法,在你需要进行显示或者隐藏的地方加上条件就可以了。

  <ul class="nav nav-tabs nav-stacked main-menu">

      <if condition="authCheck(‘Auth/index‘,$_SESSION[C(‘USER_AUTH_KEY‘)])">

          <li class="nav-header hidden-tablet"><i class="icon-user"></i> Auth权限认证 </li>

          <li>

            <a class="ajax-link" href="http://www.mamicode.com/{:U(‘Auth/index‘)}"><span class="hidden-tablet">&nbsp;&nbsp;&nbsp;<i class="icon-th"></i> Auth认证 </span></a>

          </li>

       </if>

</ul>

 

最后一步、创建UserModel.class.php

<?php

/**

 * Created by PhpStorm.

 * User: Administrator

 * Date: 14-10-20

 * Time: 下午12:54

 */

namespace Admin\Model;

use Think\Model\RelationModel;

 

class UserModel extends RelationModel{

    //关联查询用户所属的用户组

    protected $_link = array(

        ‘auth_group‘ => array(

            ‘mapping_type‘ => self::MANY_TO_MANY,

            ‘class_name‘ => ‘auth_group‘,

            ‘mapping_name‘ => ‘classify‘,

            ‘foreign_key‘ => ‘uid‘,

            ‘relation_foreign_key‘ => ‘group_id‘,

            ‘relation_table‘ => ‘think_auth_group_access‘

        )

    );

}

 

Bootstrap+Thinkphp3.2+Auth认证+jquery-validator后台