基于ThinkPHP5的Auth权限认证管理模块

搞了一个多月的时间终于搞定这个基于ThinkPHP5的auth权限管理模块,下面是一些截图和参考资料。看云的那个文档给了我很大的帮助,花了10块钱买了他的源代码,然后自己修改了一番,适应了当时在做的系统。

 

 

Auth.php

<?php
/**
 * Created by PhpStorm.
 * User: 11547
 * Date: 2018/7/30
 * Time: 10:50
 */

namespace app\admin\controller;


use app\common\model\Common;
use think\Session;
use think\Request;
use think\Loader;
use think\Db;

class Auth extends Admin
{
    function _initialize()
    {
        parent::_initialize();
        //$this->role = Loader::model('role');
    }

    /**
     * 权限列表
     */
    public function auth()
    {
        $data = Db::name('auth')->getTreeData('tree','id','title');
        $assign = array(
            'data' => $data
        );
        $this->assign($assign);
        return $this->fetch();
    }


    /**
     * 添加权限
     */
    public function addAuth(){
        $data=input('post.');
//        var_dump($data);
        unset($data['id']);
        $result=Db::name('auth')->insert($data);
        if ($result) {
            $this->success('添加成功','Admin/Role/auth');
        }else{
            $this->error('添加失败');
        }
    }

    /**
     * 修改权限
     */
    public function editAuth(){
        $data=input('post.');
        $info=['title'=>$data['title'],'name'=>$data['name']];
        $result=Db::name('auth')->where(["id"=>$data['id']])->update($info);
        // $result=\app\admin\model\Admin::change(["id"=>$data['id']],$info);
        if ($result) {
            $this->success('修改成功!','Admin/Role/auth');
        }else{
            $this->error('您没有做任何修改!');
        }
    }

    /**
     * 删除权限
     */
    public function deleteAuth($id){
        $map=array(
            'id'=>$id
        );
        $result=Db::name('auth')->delete($map);
        if($result){
            $this->success('删除成功','Admin/Role/auth');
        }else{
            $this->error('请先删除子权限');
        }

    }
}

auth.html

<!--添加权限-->
<div class="modal fade" id="thinkright-add" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title" id="myModalLabel">
                    添加权限
                </h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" action="{:url('admin/role/addAuth')}" method="post">
                    <div class="panel-body">
                        <div class="form-group">
                            <label class="col-sm-3 control-label" for="demo-hor-inputemail">权限名称</label>
                            <div class="col-sm-9">
                                <input type="hidden" name="pid" value="0">
                                <input type="text"  id="demo-hor-inputemail" class="form-control" name="title" required="required">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label" for="demo-hor-inputpass">权限</label>
                            <div class="col-sm-9">
                                <input type="text"  id="demo-hor-inputpass" class="form-control" name="name" required="required">
                                <span class="text-warning">输入模块/控制器/方法即可, 例如 admin/role/index</span>
                            </div>
                        </div>
                    </div>
                    <div class="panel-footer text-right">
                        <button class="btn btn-success" type="submit">提交</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!--修改权限-->
<div class="modal fade" id="thinkright-edit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title" id="myModalLabel2">
                    修改权限
                </h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" action="{:url('Admin/role/editAuth')}" method="post">
                    <div class="panel-body">
                        <div class="form-group">
                            <label class="col-sm-3 control-label" for="demo-hor-inputemail">权限名称</label>
                            <div class="col-sm-9">
                                <input type="hidden" name="id">
                                <input type="text"  id="demo-hor-inputemail2" class="form-control" name="title" required="required">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label" for="demo-hor-inputpass">权限</label>
                            <div class="col-sm-9">
                                <input type="text"  id="demo-hor-inputpass2" class="form-control" name="name" required="required">
                                <span class="text-danger">输入模块/控制器/方法即可,例如 admin/role/index</span>
                            </div>
                        </div>
                    </div>
                    <div class="panel-footer text-right">
                        <button class="btn btn-success" type="submit">修改</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Data Tables -->
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-lg-12">
            <div class="ibox float-e-margins" style="background: white;padding: 10px">
                <!-- 表单标题概要 -->
                <div class="ibox-title">
                    <h5>{:lang('Auth List')}</h5>
                    <div class="ibox-tools">
                        <a class="collapse-link">
                            <i class="fa fa-chevron-up"></i>
                        </a>
                        <a class="close-link">
                            <i class="fa fa-times"></i>
                        </a>
                    </div>
                </div>
                <!-- 表单内容 -->
                <div class="ibox-content">
                    <!-- 用户控件(操作) -->
                    <!--{toolbar id="toolbar"}-->
                    <!--{/toolbar}-->
                    <div class="toolbar">
                        <div class="btn-group">
                            <button  class="btn btn-primary" data-toggle="modal"  data-target="#myModal" onclick="add()">
                                <i class="fa fa-plus" aria-hidden="true" style="margin-right: 2px"></i>
                                添加权限
                            </button>
                        </div>
                    </div>
                    <!-- 表格数据 -->
                    <!--<table id="authtable" data-toggle="gridview" class="table"-->
                           <!--data-url="{:url('admin/role/getList')}"-->
                           <!--data-toolbar="#toolbar" data-show-columns="true"-->
                           <!--data-page-size="10"-->
                           <!--data-page-list="[10, 25, 50, All]" data-unique-id="id" data-pagination="true"-->
                           <!--data-side-pagination="client" data-search="true" data-click-to-select="false">-->
                        <!--<thead>-->
                        <!--<tr>-->
                            <!--<th data-width="40" data-checkbox="true"></th>-->
                            <!--<th data-width="100" data-field="rolename">{:lang('Role Name')}</th>-->
                            <!--<th data-width="100" data-field="status">{:lang('Status')}</th>-->
                            <!--<th data-width="200" data-field="note">{:lang('Note')}</th>-->
                            <!--<th data-width="300" data-field="operate" data-align="center" data-formatter="operateFormatter" data-events="operateEvents">{:lang('Operate')}</th>-->
                        <!--</tr>-->
                        <!--</thead>-->
                    <!--</table>-->
                    <table id="demo-dt-basic" class="table table-striped table-bordered" cellspacing="0" width="100%">
                        <thead>
                        <tr>
                            <th>权限名称</th>
                            <th>权限</th>
                            <th class="min-tablet">操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {foreach name="data" id="v"}
                        <tr>
                            <td>{$v['_name']}</td>
                            <td>{$v['name']}</td>
                            <td>
                                <a href="javascript:;" ruleId="{$v['id']}" onclick="add_child(this)">添加子权限</a> |
                                <a href="javascript:;" ruleId="{$v['id']}" ruleName="{$v['name']}" ruleTitle="{$v['title']}" onclick="edit(this)">修改</a> |
                                <a href="javascript:if(confirm('确定删除?'))location='{:url('Admin/Role/deleteAuth',array('id'=>$v['id']))}'">删除</a>
                            </td>
                        </tr>
                        {/foreach}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    /*添加权限*/
    function add(){
        $("input[name='title'],input[name='name']").val('');
        $("input[name='pid']").val(0);
        $('#thinkright-add').modal('show');
    }


    // 添加子菜单
    function add_child(obj){
        var ruleId=$(obj).attr('ruleId');
        $("input[name='pid']").val(ruleId);
        $("input[name='title']").val('');
        $("input[name='name']").val('');
        $('#thinkright-add').modal('show');
    }

    // 修改菜单
    function edit(obj){
        var ruleId=$(obj).attr('ruleId');
        var ruletitle=$(obj).attr('ruletitle');
        var ruleName=$(obj).attr('ruleName');
        $("input[name='id']").val(ruleId);
        $("input[name='title']").val(ruletitle);
        $("input[name='name']").val(ruleName);
        $('#thinkright-edit').modal('show');
    }
</script>

Admin.php(验证权限部分)

public function _initialize()
	{
		parent::_initialize();
		//判断是否已经登录

		if( !Session::has('userinfo', 'admin') ) {
			$this->error('Please login first', url('admin/Login/index'));
		}
        $auth=new \think\Auth();
		$userRow = Session::get('userinfo', 'admin');
		//验证权限
		$request = Request::instance();
		$rule_name = $request->module().'/'.$request->controller().'/'.$request->action();
		$this->uid = $userRow['id'];
		$this->role_id = $userRow['role_id'];

//        var_dump($this->uid);
		if($rule_name == 'admin/login/index' || $rule_name == 'admin/index/index') {
            $result = true;
        } else {
		    $result = $auth->check($rule_name, $this->uid);
        }
        if(!$result){
            $this->error('您没有权限访问');
        }
		/*if($userRow['administrator']!=1 && !$this->checkRule($this->uid, $rule_val)) {
			$this->error(lang('Without the permissions page'));
		}*/
	}

check_user.html

<div class="table">
    <table class="table table-striped table-bordered table-hover table-condensed">
        <tr>
            <th width="10%"> 搜索用户名:</th>
            <td>
                <form class="form-inline" action="">
                    <!--输出数据,此处测试正确-->
                    <input class="input-medium" type="text" name="username" value="{$Think.get.username}">
                    <input class="btn btn-primary" type="submit" value="搜索" style="margin-left: 10px">
                </form>
            </td>
        </tr>
    </table>
    <table class="table table-striped table-bordered table-hover table-condensed">
        <tr>
            <th width="10%">用户名</th>
            <th>操作</th>
        </tr>
        {foreach name="user_data" item="v"}
            <tr>
                <th>{$v['username']}</th>
                <td>
                    {if condition="in_array($v['id'], $uids)"} 已经是{$group_name[0]['rolename']}
                        {else /}
                    <a href="{:url('Admin/Role/authorizeUser',array('uid'=>$v['id'],'role_id'=>$role_id,'username'=>$_GET['username']))}">设置为{$group_name[0]['rolename']}</a>
                    {/if}
                </td>
            </tr>
        {/foreach}
    </table>
</div>

edit.html

{__NOLAYOUT__}
<form data-method="post" data-action="{:url('admin/role/saveData')}" data-submit="ajax" data-validate="true" class="form-horizontal">
    <div class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span></button>
                    <h3 class="modal-title">{$data['id']?lang('Edit'):lang('Add')}{:lang('Role')}</h3>
                </div>
                <input type="hidden" name="id" value="{$data.id ?? ''}">
                <div class="modal-body">
                    <div class="modal-body-content">
                        <div class="form-group must">
                            <label class="col-sm-3 control-label">{:lang('Role Name')}</label>
                            <div class="col-sm-7">
                                <input type="text" class="form-control" name="name" maxlength="8"  placeholder="{:lang('Up_characters',['langth' =>8])}" required value="{$data.name ?? ''}">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="col-sm-3 control-label">{:lang('Status')}</label>
                            <div class="col-sm-7">
                                <select name="status" class="form-control" required>
                                    <option value="1" {$data['status']==1 ? 'selected' : ''}>{:lang('Start')}</option>
                                    <option value="0" {$data['status']==0 ? 'selected' : ''}>{:lang('Off')}</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-3 control-label">{:lang('Note')}</label>
                            <div class="col-sm-7"> 
                                <input type="text" class="form-control" name="remark" maxlength="10" placeholder="{:lang('Up_characters',['langth' =>10])}"  value="{$data.remark ?? ''}"  >
                            </div>
                        </div>

                    </div> 
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">{:lang('Cancel')}</button>
                    <button type="submit" class="btn btn-primary">{:lang('Save')}</button>
                </div>
            </div>
        </div>
    </div>
</form>

还有index.html,rule_distribution.html,User.php,Role.php不再一一列出。

 

参考资料:

  1. thinkphp整合系列之rbac的升级版auth权限管理系统demo-白俊遥博客
  2. 看云文档-本权限管理demo主要是针对新手的!
  3. 5行代码搞定基于Auth的权限认证
  • 8
    点赞
  • 10
    评论
  • 14
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

打赏
文章很值,打赏犒劳作者一下
相关推荐
©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页

打赏

爷爷我回来了

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者