完成用户的角色分配,妥妥的。睡觉~

This commit is contained in:
YunaiV 2021-01-11 00:02:29 +08:00
parent 8921556d75
commit 7f171d14a4
14 changed files with 256 additions and 67 deletions

View File

@ -17,6 +17,23 @@ export function assignRoleMenu(data) {
}) })
} }
// 查询用户拥有的角色数组
export function listUserRoles(userId) {
return request({
url: '/system/permission/list-user-roles?userId=' + userId,
method: 'get'
})
}
// 赋予用户角色
export function assignUserRole(data) {
return request({
url: '/system/permission/assign-user-role',
method: 'post',
data: data
})
}
// 赋予角色数据权限 // 赋予角色数据权限
export function assignRoleDataScope(data) { export function assignRoleDataScope(data) {
return request({ return request({

View File

@ -9,6 +9,14 @@ export function listRole(query) {
}) })
} }
// 查询角色(精简)列表
export function listSimpleRoles() {
return request({
url: '/system/role/list-all-simple',
method: 'get'
})
}
// 查询角色详细 // 查询角色详细
export function getRole(roleId) { export function getRole(roleId) {
return request({ return request({

View File

@ -163,6 +163,13 @@
@click="handleResetPwd(scope.row)" @click="handleResetPwd(scope.row)"
v-hasPermi="['system:user:resetPwd']" v-hasPermi="['system:user:resetPwd']"
>重置</el-button> >重置</el-button>
<el-button
size="mini"
type="text"
icon="el-icon-circle-check"
@click="handleRole(scope.row)"
v-hasPermi="['system:permission:assign-user-role']"
>分配角色</el-button>
</template> </template>
</el-table-column> </el-table-column>
</el-table> </el-table>
@ -290,31 +297,30 @@
</el-dialog> </el-dialog>
<!-- 分配角色 --> <!-- 分配角色 -->
<!-- <el-dialog title="分配角色" :visible.sync="openMenu" width="500px" append-to-body>--> <el-dialog title="分配角色" :visible.sync="openRole" width="500px" append-to-body>
<!-- <el-form :model="form" label-width="80px">--> <el-form :model="form" label-width="80px">
<!-- <el-form-item label="用户名称">--> <el-form-item label="用户名称">
<!-- <el-input v-model="form.username" :disabled="true" />--> <el-input v-model="form.username" :disabled="true" />
<!-- </el-form-item>--> </el-form-item>
<!-- <el-form-item label="用户昵称">--> <el-form-item label="用户昵称">
<!-- <el-input v-model="form.nickname" :disabled="true" />--> <el-input v-model="form.nickname" :disabled="true" />
<!-- </el-form-item>--> </el-form-item>
<!-- <el-form-item label="角色">--> <el-form-item label="角色">
<!-- <el-select v-model="form.roleIds" multiple placeholder="请选择">--> <el-select v-model="form.roleIds" multiple placeholder="请选择">
<!-- <el-option--> <el-option
<!-- v-for="item in roleOptions"--> v-for="item in roleOptions"
<!-- :key="item.roleId"--> :key="parseInt(item.id)"
<!-- :label="item.roleName"--> :label="item.name"
<!-- :value="item.roleId"--> :value="parseInt(item.id)"
<!-- :disabled="item.status == 1"--> ></el-option>
<!-- ></el-option>--> </el-select>
<!-- </el-select>--> </el-form-item>
<!-- </el-form-item>--> </el-form>
<!-- </el-form>--> <div slot="footer" class="dialog-footer">
<!-- <div slot="footer" class="dialog-footer">--> <el-button type="primary" @click="submitRole"> </el-button>
<!-- <el-button type="primary" @click="submitMenu"> </el-button>--> <el-button @click="cancelRole"> </el-button>
<!-- <el-button @click="cancelMenu"> </el-button>--> </div>
<!-- </div>--> </el-dialog>
<!-- </el-dialog>-->
</div> </div>
</template> </template>
@ -330,6 +336,8 @@ import {listSimplePosts} from "@/api/system/post";
import {SysCommonStatusEnum} from "@/utils/constants"; import {SysCommonStatusEnum} from "@/utils/constants";
import {DICT_TYPE, getDictDatas} from "@/utils/dict"; import {DICT_TYPE, getDictDatas} from "@/utils/dict";
import {assignUserRole, listUserRoles} from "@/api/system/permission";
import {listSimpleRoles} from "@/api/system/role";
export default { export default {
name: "User", name: "User",
@ -420,6 +428,8 @@ export default {
} }
] ]
}, },
//
openRole: false,
// //
SysCommonStatusEnum: SysCommonStatusEnum, SysCommonStatusEnum: SysCommonStatusEnum,
@ -499,6 +509,11 @@ export default {
this.open = false; this.open = false;
this.reset(); this.reset();
}, },
//
cancelMenu() {
this.openRole = false;
this.reset();
},
// //
reset() { reset() {
this.form = { this.form = {
@ -561,6 +576,28 @@ export default {
}); });
}).catch(() => {}); }).catch(() => {});
}, },
/** 分配用户角色操作 */
handleRole(row) {
this.reset();
const id = row.id
// form username nickname
this.form.id = id;
this.form.username = row.username;
this.form.nickname = row.nickname;
//
this.openRole = true;
//
listSimpleRoles().then(response => {
// roleOptions
this.roleOptions = [];
this.roleOptions.push(...response.data);
});
//
listUserRoles(id).then(response => {
//
this.form.roleIds = response.data;
})
},
/** 提交按钮 */ /** 提交按钮 */
submitForm: function() { submitForm: function() {
this.$refs["form"].validate(valid => { this.$refs["form"].validate(valid => {
@ -581,6 +618,19 @@ export default {
} }
}); });
}, },
/** 提交按钮(角色权限) */
submitRole: function() {
if (this.form.id !== undefined) {
assignUserRole({
userId: this.form.id,
roleIds: this.form.roleIds,
}).then(response => {
this.msgSuccess("分配角色成功");
this.openRole = false;
this.getList();
});
}
},
/** 删除按钮操作 */ /** 删除按钮操作 */
handleDelete(row) { handleDelete(row) {
const ids = row.id || this.ids; const ids = row.id || this.ids;

View File

@ -3,6 +3,7 @@ package cn.iocoder.dashboard.modules.system.controller.permission;
import cn.iocoder.dashboard.common.pojo.CommonResult; import cn.iocoder.dashboard.common.pojo.CommonResult;
import cn.iocoder.dashboard.modules.system.controller.permission.vo.permission.SysPermissionAssignRoleDataScopeReqVO; import cn.iocoder.dashboard.modules.system.controller.permission.vo.permission.SysPermissionAssignRoleDataScopeReqVO;
import cn.iocoder.dashboard.modules.system.controller.permission.vo.permission.SysPermissionAssignRoleMenuReqVO; import cn.iocoder.dashboard.modules.system.controller.permission.vo.permission.SysPermissionAssignRoleMenuReqVO;
import cn.iocoder.dashboard.modules.system.controller.permission.vo.permission.SysPermissionAssignUserRoleReqVO;
import cn.iocoder.dashboard.modules.system.service.permission.SysPermissionService; import cn.iocoder.dashboard.modules.system.service.permission.SysPermissionService;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
@ -53,22 +54,20 @@ public class SysPermissionController {
return success(true); return success(true);
} }
// @GetMapping("/list-admin-roles") @ApiOperation("获得管理员拥有的角色编号列表")
// @ApiOperation("获得管理员拥有的角色编号列表") @ApiImplicitParam(name = "userId", value = "用户编号", required = true)
//// @RequiresPermissions("system:permission:assign-admin-role") @GetMapping("/list-user-roles")
// @ApiImplicitParam(name = "adminId", value = "管理员编号", required = true) // @RequiresPermissions("system:permission:assign-user-role")
// public CommonResult<Set<Integer>> listAdminRoles(Integer adminId) { public CommonResult<Set<Long>> listAdminRoles(@RequestParam("userId") Long userId) {
// return success(permissionManager.listAdminRoles(adminId)); return success(permissionService.listUserRoleIs(userId));
// } }
// @PostMapping("/assign-admin-role") @ApiOperation("赋予用户角色")
// @ApiOperation("赋予用户角色") @PostMapping("/assign-user-role")
//// @RequiresPermissions("system:permission:assign-admin-role") // @RequiresPermissions("system:permission:assign-user-role")
// public CommonResult<Boolean> assignAdminRole(PermissionAssignAdminRoleDTO assignAdminRoleDTO) { public CommonResult<Boolean> assignUserRole(@Validated @RequestBody SysPermissionAssignUserRoleReqVO reqVO) {
// permissionManager.assignAdminRole(assignAdminRoleDTO); permissionService.assignUserRole(reqVO.getUserId(), reqVO.getRoleIds());
// return success(true); return success(true);
// } }
// system:permission:assign-role-data-scope TODO
} }

View File

@ -1,5 +1,6 @@
package cn.iocoder.dashboard.modules.system.controller.permission; package cn.iocoder.dashboard.modules.system.controller.permission;
import cn.iocoder.dashboard.common.enums.CommonStatusEnum;
import cn.iocoder.dashboard.common.pojo.CommonResult; import cn.iocoder.dashboard.common.pojo.CommonResult;
import cn.iocoder.dashboard.common.pojo.PageResult; import cn.iocoder.dashboard.common.pojo.PageResult;
import cn.iocoder.dashboard.modules.system.controller.permission.vo.role.*; import cn.iocoder.dashboard.modules.system.controller.permission.vo.role.*;
@ -13,6 +14,9 @@ import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import static cn.iocoder.dashboard.common.pojo.CommonResult.success; import static cn.iocoder.dashboard.common.pojo.CommonResult.success;
@ -31,6 +35,16 @@ public class SysRoleController {
return success(roleService.pageRole(reqVO)); return success(roleService.pageRole(reqVO));
} }
@ApiOperation(value = "获取角色精简信息列表", notes = "只包含被开启的角色,主要用于前端的下拉选项")
@GetMapping("/list-all-simple")
public CommonResult<List<SysRoleSimpleRespVO>> listSimpleRoles() {
// 获得角色列表只要开启状态的
List<SysRoleDO> list = roleService.listRoles(Collections.singleton(CommonStatusEnum.ENABLE.getStatus()));
// 排序后返回个诶前端
list.sort(Comparator.comparing(SysRoleDO::getSort));
return success(SysRoleConvert.INSTANCE.convertList02(list));
}
@ApiOperation("创建角色") @ApiOperation("创建角色")
@PostMapping("/create") @PostMapping("/create")
// @PreAuthorize("@ss.hasPermi('system:role:add')") // @PreAuthorize("@ss.hasPermi('system:role:add')")
@ -85,29 +99,4 @@ public class SysRoleController {
return success(true); return success(true);
} }
//
// /**
// * 修改保存数据权限
// */
// @PreAuthorize("@ss.hasPermi('system:role:edit')")
// @Log(title = "角色管理", businessType = BusinessType.UPDATE)
// @PutMapping("/dataScope")
// public AjaxResult dataScope(@RequestBody SysRole role)
// {
// roleService.checkRoleAllowed(role);
// return toAjax(roleService.authDataScope(role));
// }
//
// /**
// * 获取角色选择框列表
// */
// @PreAuthorize("@ss.hasPermi('system:role:query')")
// @GetMapping("/optionselect")
// public AjaxResult optionselect()
// {
// return AjaxResult.success(roleService.selectRoleAll());
// }
} }

View File

@ -0,0 +1,22 @@
package cn.iocoder.dashboard.modules.system.controller.permission.vo.permission;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.Set;
@ApiModel("赋予用户角色 Request VO")
@Data
public class SysPermissionAssignUserRoleReqVO {
@ApiModelProperty(value = "角色编号", required = true, example = "1")
@NotNull(message = "角色编号不能为空")
private Long userId;
@ApiModelProperty(value = "角色编号列表", example = "1,3,5")
private Set<Long> roleIds = Collections.emptySet(); // 兜底
}

View File

@ -0,0 +1,21 @@
package cn.iocoder.dashboard.modules.system.controller.permission.vo.role;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@ApiModel("角色精简信息 Response VO")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SysRoleSimpleRespVO {
@ApiModelProperty(value = "角色编号", required = true, example = "1024")
private Integer id;
@ApiModelProperty(value = "角色名称", required = true, example = "芋道")
private String name;
}

View File

@ -3,6 +3,7 @@ package cn.iocoder.dashboard.modules.system.convert.permission;
import cn.iocoder.dashboard.common.pojo.PageResult; import cn.iocoder.dashboard.common.pojo.PageResult;
import cn.iocoder.dashboard.modules.system.controller.permission.vo.role.SysRoleCreateReqVO; import cn.iocoder.dashboard.modules.system.controller.permission.vo.role.SysRoleCreateReqVO;
import cn.iocoder.dashboard.modules.system.controller.permission.vo.role.SysRoleRespVO; import cn.iocoder.dashboard.modules.system.controller.permission.vo.role.SysRoleRespVO;
import cn.iocoder.dashboard.modules.system.controller.permission.vo.role.SysRoleSimpleRespVO;
import cn.iocoder.dashboard.modules.system.controller.permission.vo.role.SysRoleUpdateReqVO; import cn.iocoder.dashboard.modules.system.controller.permission.vo.role.SysRoleUpdateReqVO;
import cn.iocoder.dashboard.modules.system.dal.mysql.dataobject.permission.SysRoleDO; import cn.iocoder.dashboard.modules.system.dal.mysql.dataobject.permission.SysRoleDO;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
@ -10,6 +11,8 @@ import org.mapstruct.Mapper;
import org.mapstruct.Mapping; import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers; import org.mapstruct.factory.Mappers;
import java.util.List;
@Mapper @Mapper
public interface SysRoleConvert { public interface SysRoleConvert {
@ -24,4 +27,6 @@ public interface SysRoleConvert {
SysRoleDO convert(SysRoleCreateReqVO bean); SysRoleDO convert(SysRoleCreateReqVO bean);
List<SysRoleSimpleRespVO> convertList02(List<SysRoleDO> list);
} }

View File

@ -8,6 +8,10 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.List;
@Mapper @Mapper
public interface SysRoleMapper extends BaseMapper<SysRoleDO> { public interface SysRoleMapper extends BaseMapper<SysRoleDO> {
@ -27,5 +31,7 @@ public interface SysRoleMapper extends BaseMapper<SysRoleDO> {
return selectOne(new QueryWrapperX<SysRoleDO>().eq("code", code)); return selectOne(new QueryWrapperX<SysRoleDO>().eq("code", code));
} }
default List<SysRoleDO> selectListByStatus(@Nullable Collection<Integer> statuses) {
return selectList(new QueryWrapperX<SysRoleDO>().in("status", statuses));
}
} }

View File

@ -5,7 +5,9 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
@Mapper @Mapper
public interface SysUserRoleMapper extends BaseMapper<SysUserRoleDO> { public interface SysUserRoleMapper extends BaseMapper<SysUserRoleDO> {
@ -14,4 +16,20 @@ public interface SysUserRoleMapper extends BaseMapper<SysUserRoleDO> {
return selectList(new QueryWrapper<SysUserRoleDO>().eq("user_id", userId)); return selectList(new QueryWrapper<SysUserRoleDO>().eq("user_id", userId));
} }
default void insertList(Long userId, Collection<Long> roleIds) {
List<SysUserRoleDO> list = roleIds.stream().map(roleId -> {
SysUserRoleDO entity = new SysUserRoleDO();
entity.setUserId(userId);
entity.setRoleId(roleId);
return entity;
}).collect(Collectors.toList());
// TODO 芋艿mybatis plus 增加批量插入的功能
list.forEach(this::insert);
}
default void deleteListByUserIdAndRoleIdIds(Long userId, Collection<Long> roleIds) {
delete(new QueryWrapper<SysUserRoleDO>().eq("user_id", userId)
.in("role_id", roleIds));
}
} }

View File

@ -59,6 +59,22 @@ public interface SysPermissionService {
*/ */
void assignRoleMenu(Long roleId, Set<Long> menuIds); void assignRoleMenu(Long roleId, Set<Long> menuIds);
/**
* 获得用户拥有的角色编号集合
*
* @param userId 用户编号
* @return 角色编号集合
*/
Set<Long> listUserRoleIs(Long userId);
/**
* 设置用户角色
*
* @param userId 角色编号
* @param roleIds 角色编号集合
*/
void assignUserRole(Long userId, Set<Long> roleIds);
/** /**
* 设置角色的数据权限 * 设置角色的数据权限
* *

View File

@ -6,6 +6,7 @@ import cn.iocoder.dashboard.modules.system.controller.permission.vo.role.SysRole
import cn.iocoder.dashboard.modules.system.controller.permission.vo.role.SysRoleUpdateReqVO; import cn.iocoder.dashboard.modules.system.controller.permission.vo.role.SysRoleUpdateReqVO;
import cn.iocoder.dashboard.modules.system.dal.mysql.dataobject.permission.SysRoleDO; import cn.iocoder.dashboard.modules.system.dal.mysql.dataobject.permission.SysRoleDO;
import javax.annotation.Nullable;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -30,6 +31,14 @@ public interface SysRoleService {
*/ */
SysRoleDO getRoleFromCache(Long id); SysRoleDO getRoleFromCache(Long id);
/**
* 获得角色列表
*
* @param statuses 筛选的状态允许空空时不筛选
* @return 角色列表
*/
List<SysRoleDO> listRoles(@Nullable Collection<Integer> statuses);
/** /**
* 获得角色数组从缓存中 * 获得角色数组从缓存中
* *

View File

@ -142,6 +142,29 @@ public class SysPermissionServiceImpl implements SysPermissionService {
} }
} }
@Override
public Set<Long> listUserRoleIs(Long userId) {
return CollectionUtils.convertSet(userRoleMapper.selectListByUserId(userId),
SysUserRoleDO::getRoleId);
}
@Override
public void assignUserRole(Long userId, Set<Long> roleIds) {
// 获得角色拥有角色编号
Set<Long> dbRoleIds = CollectionUtils.convertSet(userRoleMapper.selectListByUserId(userId),
SysUserRoleDO::getRoleId);
// 计算新增和删除的角色编号
Collection<Long> createRoleIds = CollUtil.subtract(roleIds, dbRoleIds);
Collection<Long> deleteMenuIds = CollUtil.subtract(dbRoleIds, roleIds);
// 执行新增和删除对于已经授权的角色不用做任何处理
if (!CollectionUtil.isEmpty(createRoleIds)) {
userRoleMapper.insertList(userId, createRoleIds);
}
if (!CollectionUtil.isEmpty(deleteMenuIds)) {
userRoleMapper.deleteListByUserIdAndRoleIdIds(userId, deleteMenuIds);
}
}
@Override @Override
public void assignRoleDataScope(Long roleId, Integer dataScope, Set<Long> dataScopeDeptIds) { public void assignRoleDataScope(Long roleId, Integer dataScope, Set<Long> dataScopeDeptIds) {
roleService.updateRoleDataScope(roleId, dataScope, dataScopeDeptIds); roleService.updateRoleDataScope(roleId, dataScope, dataScopeDeptIds);

View File

@ -21,6 +21,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import javax.annotation.Nullable;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.*; import java.util.*;
@ -71,6 +72,11 @@ public class SysRoleServiceImpl implements SysRoleService {
return roleCache.get(id); return roleCache.get(id);
} }
@Override
public List<SysRoleDO> listRoles(@Nullable Collection<Integer> statuses) {
return roleMapper.selectListByStatus(statuses);
}
@Override @Override
public List<SysRoleDO> listRolesFromCache(Collection<Long> ids) { public List<SysRoleDO> listRolesFromCache(Collection<Long> ids) {
if (CollectionUtil.isEmpty(ids)) { if (CollectionUtil.isEmpty(ids)) {