0
点赞
收藏
分享

微信扫一扫

权限控制-角色管理

修改 ​​auth_user​​​ 表的,​​open_id​​​ 字段,因为这个表是给工作人员使用的,也就是内部自己使用的系统,后面我会编写一套专门提供给用户使用的那个会使用到微信登录所以字段取值为 open_id,把当前这个表的 open_id 改为 ​​username​​ SQL 如下

ALTER TABLE `video_db`.`auth_user` CHANGE COLUMN `open_id` `username` VARCHAR ( 20 ) CHARACTER 
SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT '' COMMENT '用户名' AFTER `id`;

修改 ​​UserController​​ 的分页查询中的过滤条件如下图

权限控制-角色管理_数据

修改前端 ​​list.vue​​ 修改内容如下图

权限控制-角色管理_Project_02

还需要修改 ​​form.vue​​ 修改内容如下

权限控制-角色管理_数据_03

后端

去除 ​​RoleMenu​​​ 与 ​​UserRole​​ 类当中的逻辑删除分别如下

权限控制-角色管理_json_04

修改 RoleController

/**
* <p>
* 角色 前端控制器
* </p>
*
* @author BNTang
* @since 2021-04-21
*/
@Api(tags = "角色组")
@RestController
@RequestMapping("/service_auth/admin/role")
public class RoleController {
@Resource
private RoleService roleService;

@ApiOperation(value = "获取角色分页列表")
@GetMapping("/getRolePageList/{page}/{limit}")
public ResponseResult index(@ApiParam(name = "page", value = "当前页码", required = true) @PathVariable Long page,
@ApiParam(name = "limit", value = "每页记录数", required = true) @PathVariable Long limit,
Role role) {
// 开启分页
Page<Role> pageParam = new Page<>(page, limit);

// 构建查询条件
QueryWrapper<Role> wrapper = new QueryWrapper<>();
if (!StringUtils.isEmpty(role.getRoleName())) {
wrapper.like("role_name", role.getRoleName());
}

// 根据查询条件进行分页
roleService.page(pageParam, wrapper);

// 返回结果
return ResponseResult.ok()
.data("items", pageParam.getRecords())
.data("total", pageParam.getTotal());
}

@ApiOperation(value = "获取角色")
@GetMapping("/getRoleById/{id}")
public ResponseResult get(@PathVariable String id) {
return ResponseResult.ok().data("item", roleService.getById(id));
}

@ApiOperation(value = "新增角色")
@PostMapping("/saveRole")
public ResponseResult save(@RequestBody Role role) {
roleService.save(role);
return ResponseResult.ok();
}

@ApiOperation(value = "修改角色")
@PostMapping("/updateRole")
public ResponseResult updateById(@RequestBody Role role) {
roleService.updateById(role);
return ResponseResult.ok();
}

@ApiOperation(value = "删除角色")
@PostMapping("/removeRole/{id}")
public ResponseResult remove(@PathVariable String id) {
roleService.removeById(id);
return ResponseResult.ok();
}

@ApiOperation(value = "根据id列表删除角色(批量删除)")
@PostMapping("/batchRemoveRole")
public ResponseResult batchRemove(@RequestBody List<String> idList) {
roleService.removeByIds(idList);
return ResponseResult.ok();
}
}

修改 RoleService

/**
* <p>
* 角色 服务类
* </p>
*
* @author BNTang
* @since 2021-04-21
*/
public interface RoleService extends IService<Role> {

/**
* <b>
* 根据用户ID获取角色数据
* </b>
*
* @param userId 用户ID
* @return 角色数据
*/
Map<String, Object> findRoleByUserId(String userId);

/**
* <b>
* 根据用户ID分配用户角色
* </b>
*
* @param userId 用户ID
* @param roleId 角色ID
*/
void saveUserRoleRelationShip(String userId, String[] roleId);
}

修改 RoleServiceImpl

/**
* <p>
* 角色 服务实现类
* </p>
*
* @author BNTang
* @since 2021-04-21
*/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

@Resource
private UserRoleService userRoleService;

/**
* <b>
* 根据用户ID获取角色数据
* </b>
*/
@Override
public Map<String, Object> findRoleByUserId(String userId) {
// 1.查询出所有的角色
List<Role> allRoles = baseMapper.selectList(null);

// 2.当前用户选中的角色有哪些
QueryWrapper<UserRole> queryWrapper = new QueryWrapper<UserRole>()
.eq("user_id", userId)
.select("role_id");

// 获取到当前用户所在的角色关系
List<UserRole> userRoleList = userRoleService.list(queryWrapper);

// 取出所有的roleId 放到一个集合当中
List<String> roleIds = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList());

// 根据角色id,取出所有的角色对象
List<Role> userRoles = new ArrayList<>();

allRoles.forEach(role -> {
if (roleIds.contains(role.getId())) {
userRoles.add(role);
}
});

Map<String, Object> roleMap = new HashMap<>(2);

// 用户的角色
roleMap.put("assignRoles", userRoles);

// 所有的角色
roleMap.put("allRolesList", allRoles);
return roleMap;
}

/**
* <b>
* 根据用户ID分配用户角色
* </b>
*/
@Override
public void saveUserRoleRelationShip(String userId, String[] roleId) {
// 1.删除原来角色与用户之间的关系
userRoleService.remove(new QueryWrapper<UserRole>().eq("user_id", userId));

// 2.重新建立关系
List<UserRole> userRoleArrayList = Stream.of(roleId).map(role -> {
UserRole userRole = new UserRole();
userRole.setUserId(userId);
userRole.setRoleId(role);
return userRole;
}).collect(Collectors.toList());

// 3.批量保存关系
userRoleService.saveBatch(userRoleArrayList);
}
}

前端

新增 api 文件 ​​role.js​

import request from '@/utils/request';

const api_name = '/service_auth/admin/role';

export default {
// 获取分页列表数据
getPageList(page, limit, searchObj) {
return request({
url: `${api_name}/getRolePageList/${page}/${limit}`,
method: 'get',
// url查询字符串或表单键值对
params: searchObj
});
},
// 根据ID获取角色
getById(id) {
return request({
url: `${api_name}/getRoleById/${id}`,
method: 'get'
});
},
// 保存角色
save(role) {
return request({
url: `${api_name}/saveRole`,
method: 'post',
data: role
});
},
// 更新角色
updateById(role) {
return request({
url: `${api_name}/updateRole`,
method: 'post',
data: role
});
},
// 删除角色
removeById(id) {
return request({
url: `${api_name}/removeRole/${id}`,
method: 'post'
});
},
// 批量删除
removeRows(idList) {
return request({
url: `${api_name}/batchRemoveRole`,
method: 'post',
data: idList
});
}
}

修改路由文件 ​​index.js​

权限控制-角色管理_Project_05

{
path: 'role/list',
name: '角色管理',
component: () => import('@/views/video/auth/role/list'),
meta: {title: '角色管理'}
},
{
path: 'role/form',
name: '添加角色',
component: () => import('@/views/video/auth/role/form'),
meta: {title: '添加角色'},
hidden: true
},
{
path: 'role/update/:id',
name: '修改角色',
component: () => import('@/views/video/auth/role/form'),
meta: {title: '修改角色'},
hidden: true
},
{
path: 'role/distribution/:id',
name: '角色权限',
component: () => import('@/views/video/auth/role/roleForm'),
meta: {title: '角色权限'},
hidden: true
},

新增对应的 vue 页面如下, form.vue

<template>
<div class="app-container">
<el-form ref="role" :model="role" :rules="validateRules" label-width="120px">
<el-form-item label="角色名称" prop="roleName">
<el-input v-model="role.roleName"/>
</el-form-item>
<el-form-item>
<el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保存</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
import roleApi from '@/api/video/auth/role';

const defaultForm = {
roleName: ''
}
export default {
name: "form",
data() {
return {
role: defaultForm,

// 保存按钮是否禁用
saveBtnDisabled: false,
validateRules: {
roleName: [{required: true, trigger: 'blur', message: '角色名必须输入'}]
}
}
},
// 监听器
watch: {
$route(to, from) {
this.init();
}
},
// 生命周期方法(在路由切换,组件不变的情况下不会被调用)
created() {
this.init()
},
methods: {
// 表单初始化
init() {
if (this.$route.params && this.$route.params.id) {
const id = this.$route.params.id;
this.fetchDataById(id);
} else {
// 对象拓展运算符:拷贝对象,而不是赋值对象的引用
this.role = {...defaultForm};
}
},
saveOrUpdate() {
this.$refs.role.validate(valid => {
if (valid) {
// 防止表单重复提交
this.saveBtnDisabled = true;
if (!this.role.id) {
this.saveData();
} else {
this.updateData();
}
}
});
},
// 新增讲师
saveData() {
roleApi.save(this.role).then(response => {
// debugger
if (response.success) {
this.$message({
type: 'success',
message: response.message
})
this.$router.push({path: '/auth/role/list'});
}
});
},
// 根据id更新记录
updateData() {
// teacher数据的获取
roleApi.updateById(this.role).then(response => {
if (response.success) {
this.$message({
type: 'success',
message: response.message
})
this.$router.push({path: '/auth/role/list'});
}
});
},
// 根据id查询记录
fetchDataById(id) {
roleApi.getById(id).then(response => {
this.role = response.data.item;
});
}
}
}
</script>

list.vue

<template>
<div class="app-container">

<!--查询表单-->
<el-form :inline="true" class="demo-form-inline">
<el-form-item>
<el-input v-model="searchObj.roleName" placeholder="角色名称"/>
</el-form-item>
<el-button type="primary" icon="el-icon-search" @click="fetchData()">查询</el-button>
<el-button type="default" @click="resetData()">清空</el-button>
</el-form>

<!-- 工具条 -->
<div>
<el-button type="danger" size="mini" @click="addUser()">添加</el-button>
<el-button type="danger" size="mini" @click="removeRows()">批量删除</el-button>
</div>

<!-- 角色列表 -->
<el-table
v-loading="listLoading"
:data="list"
stripe
style="width: 100%"
@selection-change="handleSelectionChange">
<el-table-column type="selection"/>
<el-table-column label="序号" align="center">
<template slot-scope="scope">
{{ (page - 1) * limit + scope.$index + 1 }}
</template>
</el-table-column>
<el-table-column align="center" prop="roleName" label="角色名称"/>
<el-table-column label="操作" align="center">
<template slot-scope="scope">
<router-link :to="'/auth/role/distribution/'+scope.row.id">
分配权限
</router-link>
<router-link :to="'/auth/role/update/'+scope.row.id">
编辑
</router-link>
<a @click="removeDataById(scope.row.id)">删除</a>
</template>
</el-table-column>
</el-table>

<!-- 分页组件 -->
<el-pagination
:current-page="page"
:total="total"
:page-size="limit"
:page-sizes="[5, 10, 20, 30, 40, 50, 100]"
style="padding: 30px 0; text-align: center;"
layout="sizes, prev, pager, next, jumper, ->, total, slot"
@current-change="fetchData"
@size-change="changeSize"
/>
</div>
</template>

<script>
import roleApi from '@/api/video/auth/role';

export default {
name: "list",
data() {
return {
// 数据是否正在加载
listLoading: true,

// 讲师列表
list: null,

// 数据库中的总记录数
total: 0,

// 默认页码
page: 1,

// 每页记录数
limit: 10,

// 查询表单对象
searchObj: {},

// 批量选择中选择的记录列表
multipleSelection: []
}
},
// 生命周期函数:内存准备完毕,页面尚未渲染
created() {
this.fetchData()
},
methods: {
// 当页码发生改变的时候
changeSize(size) {
this.limit = size;
this.fetchData(1);
},
addUser() {
this.$router.push({path: '/auth/role/form'});
},
// 加载讲师列表数据
fetchData(page = 1) {
this.listLoading = true;

// 异步获取远程数据(ajax)
this.page = page;
roleApi.getPageList(this.page, this.limit, this.searchObj).then(response => {
this.list = response.data.items;
this.total = response.data.total;

// 数据加载并绑定成功
this.listLoading = false;
}
);
},
// 重置查询表单
resetData() {
this.searchObj = {};
this.fetchData();
},
// 根据id删除数据
removeDataById(id) {
this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 点击确定,远程调用ajax
return roleApi.removeById(id);
}).then((response) => {
this.fetchData(this.page);
if (response.success) {
this.$message({
type: 'success',
message: '删除成功!'
});
}
}).catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
});
});
},
// 当表格复选框选项发生变化的时候触发
handleSelectionChange(selection) {
this.multipleSelection = selection;
},
// 批量删除
removeRows() {
if (this.multipleSelection.length === 0) {
this.$message({
type: 'warning',
message: '请选择要删除的记录!'
});
return;
}
this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 点击确定,远程调用ajax
// 遍历selection,将id取出放入id列表
let idList = [];
this.multipleSelection.forEach(item => {
idList.push(item.id);
});
// 调用api
return roleApi.removeRows(idList);
}).then((response) => {
this.fetchData(this.page);
if (response.success) {
this.$message({
type: 'success',
message: '删除成功!'
});
}
}).catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
});
});
}
}
}
</script>

roleForm.vue

<template>
<div style="margin: 20px 20px">
<el-tree
:data="data"
show-checkbox
default-expand-all
node-key="id"
ref="tree"
highlight-current
:props="defaultProps">
</el-tree>
<el-button :disabled="saveBtnDisabled" type="primary" @click="save">保存</el-button>
</div>
</template>
<script>
import menu from '@/api/video/auth/menu';

export default {
name: "roleForm",
data() {
return {
saveBtnDisabled: false,
data: [],
defaultProps: {
children: 'children',
label: 'name'
},
roleId: ''
};
},
// 监听器
watch: {
$route(to, from) {
this.init();
}
},
created() {
this.init();
},
methods: {
init() {
if (this.$route.params && this.$route.params.id) {
this.roleId = this.$route.params.id;
this.fetchDataById(this.roleId);
}
},
fetchDataById(roleId) {
menu.getMenuWithRoleId(roleId).then(response => {
this.data = response.data.children;
let jsonList = JSON.parse(JSON.stringify(this.data));
let list = [];
this.getJsonToList(list, jsonList[0]['children']);
this.setCheckedKeys(list);
})
},
// 把json数据转成string再转成对象,根据Key获取value数据
getJsonToList(list, jsonList) {
// 遍历这个集合对象,获取key的值
for (let i = 0; i < jsonList.length; i++) {
if (jsonList[i]['select'] === true && jsonList[i]['level'] === 4) {
list.push(jsonList[i]['id']);
}
if (jsonList[i]['children'] != null) {
this.getJsonToList(list, jsonList[i]['children']);
}
}
},
getCheckedKeys() {
console.log(this.$refs.tree.getCheckedKeys());
},
setCheckedKeys(list) {
this.$refs.tree.setCheckedKeys(list);
},
save() {
this.saveBtnDisabled = true;
let ids = this.$refs.tree.getCheckedKeys().join(",");
console.log(ids);
menu.doAssignRoleAuth(this.roleId, ids).then(response => {
if (response.success) {
this.$message({
type: 'success',
message: '保存成功'
})
this.$router.push({path: '/auth/role/list'});
}
});
}
}
};
</script>

修改 ​​vue elementUI tree​​ 树形控件使得能够获取父节点ID的实例,不修改源码之前是获取不到的,也就是说点击了一个子节点获取不到父节点的 ID 如下图

权限控制-角色管理_json_06

修改 ​​node_modules\element-ui\lib\element-ui.common.js​​​ 中的第 ​​25382​​ 行如下图

权限控制-角色管理_Project_07

if ((child.checked || child.indeterminate) && (!leafOnly || leafOnly && child.isLeaf)) {
checkedNodes.push(child.data);
}




举报

相关推荐

0 条评论