Implementation of role management in blog system
Overview: the basic function of role management is to add, delete, modify and query roles. However, due to the relationship between roles and permissions, the relationship between roles needs to be considered in adding, deleting, modifying and querying. When adding roles, you need to grant permissions to roles. Granting permissions to roles is a difficulty in my implementation. The relationship is complex, The implementation of the front-end page in the background is also complex.
1,index.ctp view
Introduction: I use ajax to add, delete and change asynchronously here, so I only need one page to realize all the functions of role management. The amount of code is relatively large, and many problems have been encountered in the implementation. Among them, the check box rendering of permission display uses a large number of jquery functions, which is more complex. Now I only realize the basic functions, It will be further optimized in the future.
<!--Breadcrumb navigation--> <div style="margin-bottom: 5px"> <span class="layui-breadcrumb"> <a href="">home page</a> <a><cite>Role management</cite></a> </span> </div> <!--Show new mode box--> <button type="button" onclick="add()" class="layui-btn" data-toggle="modal" data-target="#Mymodal "> new role < / button > <!--The table shows all roles and administrators with permissions--> <table class="layui-table"> <colgroup> <col width="150"> <col width="200"> <col> </colgroup> <tr> <th>number</th> <th>Role name</th> <th>managers</th> <th>describe</th> <th>operation</th> </tr> <?php foreach($params as $v): ?> <tr> <td><?=$v['Role']['id']?></td> <td><?=$v['Role']['role_name']?></td> <td><?=$v['Role']['name']?></td> <td><?=$v['Role']['desc']?></td> <td> <!--The super administrator role cannot be manipulated--> <?php if($v['Role']['id'] == 1): ?> <?php else: ?> <a class="layui-icon layui-icon-edit" data-toggle="modal" data-target="#myModal" onclick="edit(<?= $v['Role']['id']?>,'<?= $v['Role']['role_name']?>','<?= $v['Role']['desc']?>')"></a> <a class="layui-icon layui-icon-subtraction" onclick="del(<?= $v['Role']['id']?>)"></a> <?php endif; ?> </td> </tr> <?php endforeach; ?> </table> <!--Add / modify mode box--> <div class="modal fade" id="myModal" data-backdrop="false" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog modal-lg" role="document" > <div class="modal-content" > <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" onclick="close1()" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title" id="myModalLabel">Role operation</h4> </div> <div class="modal-body"> <div class="layui-form" style="width: 60%;margin-top: 20px;"> <div class="layui-form-item"> <label class="layui-form-label">Role name</label> <div class="layui-input-block"> <input type="hidden" id="id" class="layui-input"> <input type="text" id="username" placeholder="Please enter role name" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label" >Role description</label> <div class="layui-input-block"> <input type="text" id="desc" placeholder="Please enter role description" class="layui-input"> </div> </div> <!--Display of check boxes for implementing permissions--> <div class="layui-form-item"> <label class="layui-form-label" >Site permissions</label> <div class="layui-input-block layui-tab layui-tab-brief" style="width: 500px" lay-filter="demo"> <ul class="layui-tab-title"> <?php foreach($auth as $v1): ?> <?php if($v1['pid'] == 0): ?> <li data-id="<?=$v1['id']?>"><?=$v1['auth_name'];?></li> <?php endif; ?> <?php endforeach; ?> </ul> <div class="layui-tab-content"> <?php foreach($auth as $v1): ?> <?php if($v1['pid'] == 0): ?> <div class="layui-tab-item"> <?php foreach($auth as $v2): ?> <?php if($v1['id'] == $v2['pid'] ): ?> <input type="checkbox" name="auth" lay-skin="primary" value="<?= $v2['id']?>" title="<?=$v2['auth_name']?>"> <?php endif; ?> <?php endforeach; ?> </div> <?php endif; ?> <?php endforeach; ?> </div> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" onclick="close1()" data-dismiss="modal">return</button> <button type="button" id="ajax_submit1" class="btn btn-primary">Submit</button> </div> </div> </div> </div> <script> //Close modal box reload function close1(){ window.location.reload(); } //layui loading layui.use(['element','form','layer'],function(){ var element = layui.element; var form = layui.layer; var layer = layui.layer; //Submit modification $("#ajax_submit1").click(function () { var auth_array = new Array(); $('input[name=auth]:checked').each(function () { auth_array.push($(this).val()); }); var auth_str = auth_array.join(','); //data var data = { 'id':$('#id').val(), 'role_name':$('#username').val(), 'desc':$('#username').val(), 'auth_ids':auth_str, } $.ajax({ 'url':'/Role/dellRole', 'data':data, 'type':'post', 'dataType':'json', 'success':function (res) { if (res.code == 400){ layer.msg("operation failed!"); }else if(res.code == 200){ layer.msg("Operation succeeded!"); } setTimeout(function () { window.location.reload(); },800) } }); }) }); //Load when clicking modify function edit(role_id,role_name,desc) { var data ={ 'role_id':role_id, }; $("#username").val(role_name); $("#desc").val(desc); $('#id').val(role_id); //Get all the permissions of the role through the role id, and then render it to the modify mode box $.ajax({ 'url': '/Role/roleFindRole', 'type':'post', 'data':data, 'dataType':'JSON', 'success':function (res) { var array = new Array(); $.each(res,function (data,value) { array.push(parseInt(value)); }); $('input[name=auth]').each(function () { var cat = parseInt($(this).val()); if ($.inArray(cat,array) != -1) { $(this).attr("checked",true); layui.form.render(); } }); }, }); } //Delete role function del(role_id) { var data = { 'role_id':role_id } $.ajax({ 'url':'/Role/delRole', 'type':'post', 'dataType':'Json', 'data':data, 'success':function (res) { if (res.code ==200){ layui.use('layer',function () { var layer = layui.layer; layer.msg('Delete succeeded'); }) }else{ layui.use('layer',function () { var layer = layui.layer; layer.msg('Deletion failed'); }) } setTimeout(function () { window.location.reload(); },800); } }); } </script>
Background page display:
2,RoleController.php controller
Introduction: the implementation of the controller is to obtain data from the model, and the data required by the background page is rendered to the background page through the controller. What is a little complicated here is that there is a lot of data required during page display, and the administrator information, permission information and all permission information of the role need to be used.
<?php /** * Created by PhpStorm. * User: wyq * Date: 2021/7/9 * Time: 21:41 */ App::uses('CakeSession', 'Model/Datasource'); class RoleController extends AppController { public $uses = array('Admin'); /* * Show information about all roles */ public function index() { //Get all role information $res = $this->Role->getAll(); //res1 is all permission information, which is used to display all permission information when permission is granted foreach ($res[0]['auth'] as $v){ $res1[] = $v; } $this->set(array('params'=>$res,'auth'=>$res1)); } /* * Find permissions through roles. In order to render the permission check box, those who have permissions are selected */ public function roleFindRole(){ //Get current user information $role_id =$_POST['role_id']; //Get the permission information of the current user $auth = $this->Role->find_auth($role_id); //Return permission json array $auth = explode(',',$auth); exit(json_encode($auth)); } /* * Add or modify role information. If you do not pass id data here, you are adding. Otherwise, you are modifying */ public function dellRole(){ $post = $_POST; //Modify operation if ($post['id']){ if (in_array('',$post)){ $res = array('code'=>400,'msg'=>'update error'); exit(json_encode($res)); }else{ $data = $this->Role->dellRole($post); if ($data){ $res = array('code'=>200,'msg'=>'update success'); exit(json_encode($res)); }else{ $res = array('code'=>400,'msg'=>'update error'); exit(json_encode($res)); } } }else{ //Add operation if ($post['role_name'] == ''){ $res = array('code'=>400,'msg'=>'insert error'); exit(json_encode($res)); }else{ $data = $this->Role->dellRole($post); if ($data){ $res = array('code'=>200,'msg'=>'insert success'); exit(json_encode($res)); }else{ $res = array('code'=>400,'msg'=>'insert error'); exit(json_encode($res)); } } } } /* * Delete user information */ public function delRole(){ $id = $_POST['role_id']; $data = $this->Role->delRole($id); if ($data){ $res = array('code'=>200,'msg'=>'success'); }else{ $res = array('code'=>400,'msg'=>'error'); } exit(json_encode($res)); } }
3,Role.php model:
<?php /** * Created by PhpStorm. * User: wyq * Date: 2021/7/8 * Time: 21:23 */ class Role extends AppModel { public $uses = array ('Admin','Auth'); /* * Obtain the user's permission group through the user's role */ public function find_auth($id){ $this->setSource('role'); $auths = $this->find('first',array( 'conditions' => array('id' => $id), 'fields' => 'auth_ids' )); return $auths['Role']['auth_ids']; } /* * Obtain the user display menu through the user's permission */ public function get_menu($auth){ //Execute native sql $sql = "SELECT `id`, `auth_name`, `is_menu`, `pid`, `path` FROM `auth` WHERE `id` in (".$auth.") and is_menu =1"; $data = $this->query($sql); foreach ($data as $v){ $res[] = $v['auth']; } return $res; } /* * Get all menus */ public function get_all_menu(){ $this->setSource('auth'); $data = $this->find('all',array( 'conditions'=>array('is_menu'=>1) )); foreach ($data as $v){ $res[] = $v['Role']; } return $res; } /* * Obtain all user permissions through the user's permission group */ public function get_auth($auth,$type = 1){ //Execute native sql $sql = "SELECT `id`, `auth_name`, `is_menu`, `pid`, `path` FROM `auth` WHERE `id` in (".$auth.")"; $data = $this->query($sql); foreach ($data as $v){ if ($v['auth']['path']!=""){ $res[] = $v['auth']['path']; } } if ($type == 1){ return $res; }else{ return $data; } } /* * Get all roles */ public function getAll(){ $this->setSource('role'); $res = $this->find('all'); //Get administrator information for role foreach ($res as &$v){ $role = ClassRegistry::init('Admin'); //Obtain the username of the administrator through the role id, which is used to display the administrator list of the role $v['Role']['name'] = $role->findAdminName($v['Role']['id']); $auth= ClassRegistry::init('Auth'); //Obtain all permissions, which is used to display all permissions for users to select when granting permissions $data[]= $auth->getAuth(); foreach ($data[0] as $v1){ $result[] = $v1['Auth']; } $v['auth'] = $result; } //All users using this role return $res; } /* * Add or modify role information */ public function dellRole($data){ $this->setSource('role'); $res = $this->save($data); return $res; } /* * Delete role information */ public function delRole($id){ $this->setSource('role'); $data = $this->delete($id); return $data; } }
Summary: this function is not a very complex function, but for me, the implementation of the foreground page is more complex, and the controller code and model code are also more complex than the previous code. The data here involves several tables, and the data format also has certain requirements. This function should be the most complex part of permission management, and the next administrator management is not so complex, These two days of coding have improved my relatively weak front-end ability and made me have a deeper understanding of RBAC.