当前位置:网站首页>Query permission information from database

Query permission information from database

2022-06-09 10:20:00 Leon_ Jinhai_ Sun

preparation


CREATE DATABASE /*!32312 IF NOT EXISTS*/`sg_security` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;

USE `sg_security`;

/*Table structure for table `sys_menu` */

DROP TABLE IF EXISTS `sys_menu`;

CREATE TABLE `sys_menu` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `menu_name` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT ' Menu name ',
  `path` varchar(200) DEFAULT NULL COMMENT ' Routing address ',
  `component` varchar(255) DEFAULT NULL COMMENT ' Component path ',
  `visible` char(1) DEFAULT '0' COMMENT ' Menu status (0 Show  1 hide )',
  `status` char(1) DEFAULT '0' COMMENT ' Menu status (0 normal  1 Discontinue use )',
  `perms` varchar(100) DEFAULT NULL COMMENT ' Authority sign ',
  `icon` varchar(100) DEFAULT '#' COMMENT ' Menu icons ',
  `create_by` bigint(20) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  `update_by` bigint(20) DEFAULT NULL,
  `update_time` datetime DEFAULT NULL,
  `del_flag` int(11) DEFAULT '0' COMMENT ' Whether or not to delete (0 Not delete  1 deleted )',
  `remark` varchar(500) DEFAULT NULL COMMENT ' remarks ',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COMMENT=' Menu table ';

/*Table structure for table `sys_role` */

DROP TABLE IF EXISTS `sys_role`;

CREATE TABLE `sys_role` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(128) DEFAULT NULL,
  `role_key` varchar(100) DEFAULT NULL COMMENT ' Role permission string ',
  `status` char(1) DEFAULT '0' COMMENT ' A status (0 normal  1 Discontinue use )',
  `del_flag` int(1) DEFAULT '0' COMMENT 'del_flag',
  `create_by` bigint(200) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  `update_by` bigint(200) DEFAULT NULL,
  `update_time` datetime DEFAULT NULL,
  `remark` varchar(500) DEFAULT NULL COMMENT ' remarks ',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT=' Role table ';

/*Table structure for table `sys_role_menu` */

DROP TABLE IF EXISTS `sys_role_menu`;

CREATE TABLE `sys_role_menu` (
  `role_id` bigint(200) NOT NULL AUTO_INCREMENT COMMENT ' role ID',
  `menu_id` bigint(200) NOT NULL DEFAULT '0' COMMENT ' menu id',
  PRIMARY KEY (`role_id`,`menu_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;

/*Table structure for table `sys_user` */

DROP TABLE IF EXISTS `sys_user`;

CREATE TABLE `sys_user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT ' Primary key ',
  `user_name` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT ' user name ',
  `nick_name` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT ' nickname ',
  `password` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT ' password ',
  `status` char(1) DEFAULT '0' COMMENT ' Account status (0 normal  1 Discontinue use )',
  `email` varchar(64) DEFAULT NULL COMMENT ' mailbox ',
  `phonenumber` varchar(32) DEFAULT NULL COMMENT ' cell-phone number ',
  `sex` char(1) DEFAULT NULL COMMENT ' User's gender (0 male ,1 Woman ,2 Unknown )',
  `avatar` varchar(128) DEFAULT NULL COMMENT ' Head portrait ',
  `user_type` char(1) NOT NULL DEFAULT '1' COMMENT ' The user types (0 Administrators ,1 Ordinary users )',
  `create_by` bigint(20) DEFAULT NULL COMMENT ' Creator's user id',
  `create_time` datetime DEFAULT NULL COMMENT ' Creation time ',
  `update_by` bigint(20) DEFAULT NULL COMMENT ' Updated by ',
  `update_time` datetime DEFAULT NULL COMMENT ' Update time ',
  `del_flag` int(11) DEFAULT '0' COMMENT ' Delete logo (0 Represents not deleted ,1 Represents the deletion of )',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT=' User table ';

/*Table structure for table `sys_user_role` */

DROP TABLE IF EXISTS `sys_user_role`;

CREATE TABLE `sys_user_role` (
  `user_id` bigint(200) NOT NULL AUTO_INCREMENT COMMENT ' user id',
  `role_id` bigint(200) NOT NULL DEFAULT '0' COMMENT ' role id',
  PRIMARY KEY (`user_id`,`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
SELECT 
	DISTINCT m.`perms`
FROM
	sys_user_role ur
	LEFT JOIN `sys_role` r ON ur.`role_id` = r.`id`
	LEFT JOIN `sys_role_menu` rm ON ur.`role_id` = rm.`role_id`
	LEFT JOIN `sys_menu` m ON m.`id` = rm.`menu_id`
WHERE
	user_id = 2
	AND r.`status` = 0
	AND m.`status` = 0
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Date;


@TableName(value="sys_menu")
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Menu implements Serializable {
    private static final long serialVersionUID = -54979041104113736L;
    
        @TableId
    private Long id;
    /**
    *  Menu name 
    */
    private String menuName;
    /**
    *  Routing address 
    */
    private String path;
    /**
    *  Component path 
    */
    private String component;
    /**
    *  Menu status (0 Show  1 hide )
    */
    private String visible;
    /**
    *  Menu status (0 normal  1 Discontinue use )
    */
    private String status;
    /**
    *  Authority sign 
    */
    private String perms;
    /**
    *  Menu icons 
    */
    private String icon;
    
    private Long createBy;
    
    private Date createTime;
    
    private Long updateBy;
    
    private Date updateTime;
    /**
    *  Whether or not to delete (0 Not delete  1 deleted )
    */
    private Integer delFlag;
    /**
    *  remarks 
    */
    private String remark;
}

Code implementation

​ We just need to according to the user id You can query the corresponding permission information .

​ So we can first define mapper, Which provides a method according to userid Query permission information .

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sangeng.domain.Menu;

import java.util.List;

public interface MenuMapper extends BaseMapper<Menu> {
    List<String> selectPermsByUserId(Long id);
}

In particular, custom methods , So you need to create a corresponding mapper file , Define corresponding sql sentence

<?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="com.sangeng.mapper.MenuMapper">


    <select id="selectPermsByUserId" resultType="java.lang.String">
        SELECT
            DISTINCT m.`perms`
        FROM
            sys_user_role ur
            LEFT JOIN `sys_role` r ON ur.`role_id` = r.`id`
            LEFT JOIN `sys_role_menu` rm ON ur.`role_id` = rm.`role_id`
            LEFT JOIN `sys_menu` m ON m.`id` = rm.`menu_id`
        WHERE
            user_id = #{userid}
            AND r.`status` = 0
            AND m.`status` = 0
    </select>
</mapper>

stay application.yml Middle configuration mapperXML The location of the file

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/sg_security?characterEncoding=utf-8&serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
  redis:
    host: localhost
    port: 6379
mybatis-plus:
  mapper-locations: classpath*:/mapper/**/*.xml 

Then we can go to UserDetailsServiceImpl To call the mapper The method of querying permission information is encapsulated into LoginUser In the object .

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(wrapper);
        if(Objects.isNull(user)){
            throw new RuntimeException(" Wrong user name or password ");
        }
        List<String> permissionKeyList =  menuMapper.selectPermsByUserId(user.getId());
//        // Test writing method 
//        List<String> list = new ArrayList<>(Arrays.asList("test"));
        return new LoginUser(user,permissionKeyList);
    }
}

原网站

版权声明
本文为[Leon_ Jinhai_ Sun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090937210281.html