概述
权限控制采用springsecurity
数据库设计
用户表
java
DROP TABLE IF EXISTS `admin`;
CREATE TABLE `admin` (
`aid` int(32) NOT NULL AUTO_INCREMENT,
`email` varchar(50) DEFAULT NULL,
`username` varchar(50) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`phoneNum` varchar(20) DEFAULT NULL,
`status` tinyint(1) DEFAULT NULL,
`adminImg` varchar(255) DEFAULT NULL,
PRIMARY KEY (`aid`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
角色表
java
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`rid` int(32) NOT NULL AUTO_INCREMENT,
`roleName` varchar(50) DEFAULT NULL,
`roleDesc` varchar(50) DEFAULT NULL,
PRIMARY KEY (`rid`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
权限表
java
DROP TABLE IF EXISTS `permission`;
CREATE TABLE `permission` (
`pid` int(32) NOT NULL AUTO_INCREMENT,
`permissionName` varchar(50) DEFAULT NULL,
`permissionDesc` varchar(50) DEFAULT NULL,
PRIMARY KEY (`pid`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8;
用户角色关联表
java
DROP TABLE IF EXISTS `admin_role`;
CREATE TABLE `admin_role` (
`aid` varchar(32) NOT NULL,
`rid` varchar(32) NOT NULL,
PRIMARY KEY (`aid`,`rid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
角色权限关联表
java
DROP TABLE IF EXISTS `role_permission`;
CREATE TABLE `role_permission` (
`rid` varchar(32) DEFAULT NULL,
`pid` varchar(32) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
实体类设计
用户实体类
java
@Data
public class Admin implements Serializable {
@TableId
private Integer aid;
private String username;//姓名
private String password;//密码
private String phoneNum;//手机号
private String email;//邮箱
private String adminImg;//头像
private boolean status; // 状态 true可用 false禁用
@TableField(exist = false) // 不是数据库的字段
private List<Role> roles; // 角色集合
}
角色实体类
java
@Data
public class Role implements Serializable {
@TableId
private Integer rid;
private String roleName; // 角色名
private String roleDesc; // 角色介绍
@TableField(exist = false) // 不是数据库的字段
private List<Permission> permissions;// 权限集合
}
权限实体类
java
@Data
public class Permission implements Serializable {
@TableId
private Integer pid;
private String permissionName; //权限名
private String permissionDesc;//权限详情
}
Mapper接口设计
包的层级关系
AdminMapper
java
public interface AdminMapper extends BaseMapper<Admin> {
// 根据id查询管理员,包括角色和权限
Admin findById(Integer id);
// 删除管理员的所有角色
void deleteAdminAllRole(Integer id);
// 给管理员添加角色
void addRoleToAdmin(@Param("aid") Integer aid, @Param("rid") Integer rid);
// 根据管理员名查询权限
List<Permission> findAllPermission(String username);
}
AdminMapper .xml
java
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="jkw.mapper.AdminMapper">
<resultMap id="adminMapper" type="jkw.pojo.Admin">
<id property="aid" column="aid"></id>
<result property="username" column="username"></result>
<result property="email" column="email"></result>
<result property="phoneNum" column="phoneNum"></result>
<result property="status" column="status"></result>
<result property="adminImg" column="adminImg"></result>
<collection property="roles" column="aid" ofType="jkw.pojo.Role">
<id property="rid" column="rid"></id>
<result property="roleName" column="roleName"></result>
<result property="roleDesc" column="roleDesc"></result>
<collection property="permissions" column="rid" ofType="jkw.pojo.Permission">
<id property="pid" column="pid"></id>
<result property="permissionName" column="permissionName"></result>
<result property="permissionDesc" column="permissionDesc"></result>
</collection>
</collection>
</resultMap>
<delete id="deleteAdminAllRole" parameterType="int">
DELETE
FROM admin_role
WHERE aid = #{id}
</delete>
<select id="findById" parameterType="int" resultMap="adminMapper">
SELECT *
FROM admin
LEFT JOIN admin_role
ON admin.aid = admin_role.aid
LEFT JOIN role
ON admin_role.rid = role.rid
LEFT JOIN role_permission
ON role.rid = role_permission.rid
LEFT JOIN permission
ON role_permission.pid = permission.pid
WHERE admin.aid = #{id}
</select>
<insert id="addRoleToAdmin">
INSERT INTO admin_role
VALUES (#{aid}, #{rid});
</insert>
<select id="findAllPermission" resultType="jkw.pojo.Permission" parameterType="string">
SELECT DISTINCT permission.*
FROM admin
LEFT JOIN admin_role
ON admin.aid = admin_role.aid
LEFT JOIN role
ON admin_role.rid = role.rid
LEFT JOIN role_permission
ON role.rid = role_permission.rid
LEFT JOIN permission
ON role_permission.pid = permission.pid
WHERE admin.username = #{username}
</select>
</mapper>
RoleMapper
java
public interface RoleMapper extends BaseMapper<Role> {
// 删除角色_权限中间表的相关数据
void deleteRoleAllPermission(Integer rid);
// 删除用户_角色表的相关数据
void deleteRoleAllAdmin(Integer rid);
// 根据id查询角色,包括权限
Role findById(Integer id);
// 给角色添加权限
void addPermissionToRole(@Param("rid") Integer rid, @Param("pid")Integer pid);
}
RoleMapper .xml
java
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="jkw.mapper.RoleMapper">
<resultMap id="roleMapper" type="jkw.pojo.Role">
<id property="rid" column="rid"></id>
<result property="roleName" column="roleName"></result>
<result property="roleDesc" column="roleDesc"></result>
<collection property="permissions" column="rid" ofType="jkw.pojo.Permission">
<id property="pid" column="pid"></id>
<result property="permissionName" column="permissionName"></result>
<result property="permissionDesc" column="permissionDesc"></result>
</collection>
</resultMap>
<delete id="deleteRoleAllPermission" parameterType="int">
DELETE
FROM role_permission
WHERE rid = #{rid}
</delete>
<delete id="deleteRoleAllAdmin" parameterType="int">
DELETE
FROM admin_role
where rid = #{rid}
</delete>
<select id="findById" parameterType="int" resultMap="roleMapper">
SELECT *
FROM role
LEFT JOIN role_permission
ON role.rid = role_permission.rid
LEFT JOIN permission
ON role_permission.pid = permission.pid
WHERE role.rid = #{id}
</select>
<insert id="addPermissionToRole">
INSERT INTO role_permission
VALUES (#{rid}, #{pid});
</insert>
</mapper>
PermissionMapper
java
public interface PermissionMapper extends BaseMapper<Permission> {
// 删除角色_权限表中的相关数据
void deletePermissionAllRole(Integer pid);
}
PermissionMapper .xml
java
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="jkw.mapper.PermissionMapper">
<delete id="deletePermissionAllRole" parameterType="int">
DELETE
FROM role_permission
WHERE pid = #{pid}
</delete>
</mapper>
service服务层设计
AdminService
java
/**
* 用户服务层
*/
public interface AdminService {
// 新增管理员
void add(Admin admin);
// 修改管理员
void update(Admin admin);
// 删除管理员【自定义】
void delete(Integer id);
//修改状态
void updateStatus(Integer id);
// 根据id查询管理员(查询用户详情)【自定义】
Admin findById(Integer id);
//分页查询管理员
Page<Admin> search(int page, int size);
// 修改管理员角色【自定义】
void updateRoleToAdmin(Integer aid, Integer[] rids);
// 根据名字查询管理员
Admin findByName(String username);
// 根据名字查询管理员所有权限
List<Permission> findAllPermission(String username);
}
AdminServiceImpl
java
@Service
@Transactional
public class AdminServiceImpl implements AdminService {
@Autowired
private AdminMapper adminMapper;
@Override
public void add(Admin admin) {
adminMapper.insert(admin);
//初始化用户,不然添加后什么角色都没有,会报错
adminMapper.addRoleToAdmin(admin.getAid(), 2);
}
@Override
public void update(Admin admin) {
// 如果前端传来空密码,则密码还是原来的密码
if (!StringUtils.hasText(admin.getPassword())) {
// 查询原来的密码
String password = adminMapper.selectById(admin.getAid()).getPassword();
admin.setPassword(password);
}
adminMapper.updateById(admin);
}
@Override
public void delete(Integer id) {
// 删除用户的所有角色
adminMapper.deleteAdminAllRole(id);
// 删除用户
adminMapper.deleteById(id);
}
@Override
public void updateStatus(Integer id) {
Admin admin = adminMapper.selectById(id);
admin.setStatus(!admin.isStatus());//状态取反
adminMapper.updateById(admin);
}
@Override
public Admin findById(Integer id) {
return adminMapper.findById(id);
}
@Override
public Page<Admin> search(int page, int size) {
return adminMapper.selectPage(new Page<>(page, size), null);
}
@Override
public void updateRoleToAdmin(Integer aid, Integer[] rids) {
// 删除用户的所有角色
adminMapper.deleteAdminAllRole(aid);
// 重新添加管理员角色
for (Integer rid : rids) {
adminMapper.addRoleToAdmin(aid, rid);
}
}
@Override
public Admin findByName(String username) {
QueryWrapper<Admin> wrapper = new QueryWrapper();
wrapper.eq("username", username);
Admin admin = adminMapper.selectOne(wrapper);
return admin;
}
@Override
public List<Permission> findAllPermission(String username) {
return adminMapper.findAllPermission(username);
}
}
RoleService
java
/**
* 角色服务接口
*/
public interface RoleService {
// 新增角色
void add(Role role);
// 修改角色
void update(Role role);
// 删除角色
void delete(Integer id);
// 根据id查询角色【自定义】
Role findById(Integer id);
// 查询所有角色
List<Role> findAll();
// 分页查询角色
Page<Role> search(int page, int size);
// 修改角色的权限【自定义】
void addPermissionToRole(Integer rid, Integer[] pids);
}
RoleServiceImpl
java
@Service
@Transactional
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleMapper roleMapper;
@Override
public void add(Role role) {
roleMapper.insert(role);
}
@Override
public void update(Role role) {
roleMapper.updateById(role);
}
@Override
public void delete(Integer id) {
// 删除角色
roleMapper.deleteById(id);
// 删除角色_权限中间表的相关数据
roleMapper.deleteRoleAllPermission(id);
// 删除用户_角色中间表的相关数据
roleMapper.deleteRoleAllAdmin(id);
}
@Override
public Role findById(Integer id) {
return roleMapper.findById(id);
}
@Override
public List<Role> findAll() {
return roleMapper.selectList(null);
}
@Override
public Page<Role> search(int page, int size) {
return roleMapper.selectPage(new Page(page,size),null);
}
@Override
public void addPermissionToRole(Integer rid, Integer[] pids) {
// 删除角色的所有权限
roleMapper.deleteRoleAllPermission(rid);
// 给角色添加权限
for (Integer pid : pids) {
roleMapper.addPermissionToRole(rid,pid);
}
}
}
PermissionService
java
/**
* 权限服务接口
*/
public interface PermissionService {
// 新增权限
void add(Permission permission);
// 修改权限
void update(Permission permission);
// 删除权限【自定义】
void delete(Integer id);
// 根据id查询权限
Permission findById(Integer id);
// 查询所有权限
List<Permission> findAll();
// 分页查询权限
Page<Permission> search(int page, int size);
}
PermissionServiceImpl
java
@Transactional
@Service
public class PermissionServiceImpl implements PermissionService {
@Autowired
private PermissionMapper permissionMapper;
@Override
public void add(Permission permission) {
permissionMapper.insert(permission);
}
@Override
public void update(Permission permission) {
permissionMapper.updateById(permission);
}
@Override
public void delete(Integer id) {
// 删除权限
permissionMapper.deleteById(id);
// 删除角色_权限表中的相关数据
permissionMapper.deletePermissionAllRole(id);
}
@Override
public Permission findById(Integer id) {
return permissionMapper.selectById(id);
}
@Override
public List<Permission> findAll() {
return permissionMapper.selectList(null);
}
@Override
public Page<Permission> search(int page, int size) {
return permissionMapper.selectPage(new Page(page,size),null);
}
}
controller 控制交互层设计
AdminController
java
@RestController
@RequestMapping("/sys/admin")
@CrossOrigin
public class AdminController {
@Autowired
private AdminService adminService;
@Autowired
private PasswordEncoder encoder;
/**
* 新增管理员
*
* @param admin 管理员
* @return
*/
@PostMapping("/add")
public BaseResult add(Admin admin) {
String password = admin.getPassword();
password = encoder.encode(password);
admin.setPassword(password);
adminService.add(admin);
return BaseResult.ok();
}
/**
* 修改管理员(设置空密码则还是原来密码)
*
* @param admin 管理员
* @return
*/
@PostMapping("/update")
public BaseResult update(Admin admin) {
String password = admin.getPassword();
if (StringUtils.hasText(password)) { // 密码不为空加密
password = encoder.encode(password);
admin.setPassword(password);
}
adminService.update(admin);
return BaseResult.ok();
}
/**
* 删除管理员(附带对应的角色)
*
* @param aid 管理员id
* @return
*/
@DeleteMapping("/delete")
public BaseResult delete(Integer aid) {
adminService.delete(aid);
return BaseResult.ok();
}
/**
* 修改管理员的状态
*
* @param aid 管理员id
* @return
*/
@PostMapping("/updateStatus")
public BaseResult updateStatus(Integer aid) {
adminService.updateStatus(aid);
return BaseResult.ok();
}
/**
* 根据id查询管理员(详情)
*
* @param aid 管理员id
* @return
*/
@GetMapping("/findById")
public BaseResult<Admin> findById(Integer aid) {
Admin admin = adminService.findById(aid);
return BaseResult.ok(admin);
}
/**
* 分页查询管理员
*
* @param page 当前页
* @param size 每页条数
* @return
*/
@PreAuthorize("hasAnyAuthority('/sys/admin')")
@GetMapping("/search")
public BaseResult<Page<Admin>> search(int page, int size) {
Page<Admin> adminPage = adminService.search(page, size);
return BaseResult.ok(adminPage);
}
/**
* 修改管理员角色
*
* @param aid 管理员id
* @param rids 角色id
* @return
*/
@PostMapping("/updateRoleToAdmin")
public BaseResult updateRoleToAdmin(Integer aid, Integer[] rids) {
adminService.updateRoleToAdmin(aid, rids);
return BaseResult.ok();
}
/**
* 获取登录管理员名
*
* @return 管理员名
*/
@GetMapping("/getUsername")
public BaseResult<String> getUsername() {
// 1.获取会话对象
SecurityContext context = SecurityContextHolder.getContext();
// 2.获取认证对象
Authentication authentication = context.getAuthentication();
// 3.获取登录用户信息
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
String username = userDetails.getUsername();
return BaseResult.ok(username);
}
@GetMapping("/findByUsername")
public BaseResult findByUsername(String username){
Admin admin = adminService.findByName(username);
return BaseResult.ok(admin);
}
}
RoleController
java
@RestController
@RequestMapping("/sys/role")
@CrossOrigin
public class RoleController {
@Autowired
private RoleService roleService;
/**
* 新增角色
*
* @param role 角色对象
* @return 执行结果
*/
@PostMapping("/add")
public BaseResult add(Role role) {
roleService.add(role);
return BaseResult.ok();
}
/**
* 修改角色
*
* @param role 角色对象
* @return 执行结c果
*/
@PostMapping("/update")
public BaseResult update(Role role) {
roleService.update(role);
return BaseResult.ok();
}
/**
* 删除角色(包括中间表的管理员、权限)
*
* @param rid 角色id
* @return 执行结果
*/
@DeleteMapping("/delete")
public BaseResult delete(Integer rid) {
roleService.delete(rid);
return BaseResult.ok();
}
/**
* 根据id查询角色
*
* @param rid
* @return 查询到的角色
*/
@GetMapping("/findById")
public BaseResult<Role> findById(Integer rid) {
Role role = roleService.findById(rid);
return BaseResult.ok(role);
}
/**
* 查询所有角色
*
* @return 查询结果
*/
@GetMapping("/findAll")
public BaseResult<List<Role>> findAll() {
List<Role> all = roleService.findAll();
return BaseResult.ok(all);
}
/**
* 分页查询角色
*
* @param page 页码
* @param size 每页条数
* @return 查询结果
*/
@PreAuthorize("hasAnyAuthority('/sys/role')")
@GetMapping("/search")
public BaseResult<Page<Role>> search(int page, int size) {
Page<Role> page1 = roleService.search(page, size);
return BaseResult.ok(page1);
}
/**
* 修改角色的权限
*
* @param rid 角色id
* @param pids 权限id
* @return 执行结果
*/
@PostMapping("/updatePermissionToRole")
public BaseResult updatePermissionToRole(Integer rid, Integer[] pids) {
roleService.addPermissionToRole(rid, pids);
return BaseResult.ok();
}
}
PermissionController
java
@RestController
@RequestMapping("/sys/permission")
@CrossOrigin
public class PermissionController {
@Autowired
private PermissionService permissionService;
/**
* 新增权限
*
* @param permission 权限对象
* @return 执行结果
*/
@PostMapping("/add")
public BaseResult add(Permission permission) {
permissionService.add(permission);
return BaseResult.ok();
}
/**
* 修改权限
*
* @param permission 权限对象
* @return 执行结果
*/
@PostMapping("/update")
public BaseResult update(Permission permission) {
permissionService.update(permission);
return BaseResult.ok();
}
/**
* 删除权限(包括中间表对应的角色)
*
* @param pid 权限id
* @return 执行结果
*/
@DeleteMapping("/delete")
public BaseResult delete(Integer pid) {
permissionService.delete(pid);
return BaseResult.ok();
}
/**
* 根据id查询权限
*
* @param pid 权限id
* @return 查询结果
*/
@GetMapping("/findById")
public BaseResult<Permission> findById(Integer pid) {
Permission permission = permissionService.findById(pid);
return BaseResult.ok(permission);
}
/**
* 查询所有权限
*
* @return 所有权限
*/
@GetMapping("/findAll")
public BaseResult<List<Permission>> findAll() {
List<Permission> all = permissionService.findAll();
return BaseResult.ok(all);
}
/**
* 分页查询权限
*
* @param page 页面
* @param size 每页条数
* @return 查询结果
*/
@PreAuthorize("hasAnyAuthority('/sys/permission')")
@GetMapping("/search")
public BaseResult<Page<Permission>> search(int page, int size) {
Page<Permission> permissionPage = permissionService.search(page, size);
return BaseResult.ok(permissionPage);
}
}