赞
踩
springboot3.0 使用的jdk版本是17
| 描述 | 地址 |
| 源码地址 | springboot3.0+spring security6+vue3 前后分离: springboot3.0+spring security6+vue3 前后分离 |
| springboot3.0+spring security6+vue3 前后分离之前端部分 | springboot3.0+spring security6+vue3 前后分离之前端部分-CSDN博客 |
- /*
- Navicat Premium Data Transfer
- Source Server : localhost
- Source Server Type : MySQL
- Source Server Version : 80029 (8.0.29)
- Source Host : localhost:3306
- Source Schema : sp
- Target Server Type : MySQL
- Target Server Version : 80029 (8.0.29)
- File Encoding : 65001
- Date: 19/12/2023 19:23:41
- */
-
- SET NAMES utf8mb4;
- SET FOREIGN_KEY_CHECKS = 0;
-
- -- ----------------------------
- -- Table structure for sys_menu
- -- ----------------------------
- DROP TABLE IF EXISTS `sys_menu`;
- CREATE TABLE `sys_menu` (
- `id` int NOT NULL AUTO_INCREMENT COMMENT '主键',
- `name` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '菜单名称/按钮名称',
- `auth` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '权限名称',
- `create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
- `parent_id` int NULL DEFAULT NULL COMMENT '父级id',
- `is_type` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '类型 1:菜单 , 2:按钮',
- `pai_xu` int NULL DEFAULT NULL COMMENT '排序序号',
- `path` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '前端vue 跳转路径',
- PRIMARY KEY (`id`) USING BTREE,
- INDEX `idx_parent_id`(`parent_id` ASC) USING BTREE,
- INDEX `idx_is_type`(`is_type` ASC) USING BTREE,
- INDEX `idx_auth`(`auth` ASC) USING BTREE,
- INDEX `idx_path`(`path` ASC) USING BTREE
- ) ENGINE = InnoDB AUTO_INCREMENT = 34 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '系统菜单/权限表' ROW_FORMAT = Dynamic;
-
- -- ----------------------------
- -- Records of sys_menu
- -- ----------------------------
- INSERT INTO `sys_menu` VALUES (1, '组织管理', 'org', '2023-12-15 05:24:29', 0, '1', 1, '/org');
- INSERT INTO `sys_menu` VALUES (2, '组织管理二级菜单', 'org:er', '2023-12-15 05:25:51', 1, '1', 2, '/org/er');
- INSERT INTO `sys_menu` VALUES (3, '添加', 'org:er:add', '2023-12-15 05:26:52', 2, '2', 3, NULL);
- INSERT INTO `sys_menu` VALUES (4, '修改', 'org:er:edit', '2023-12-15 05:26:52', 2, '2', 4, NULL);
- INSERT INTO `sys_menu` VALUES (5, '用户管理', 'user', '2023-12-15 05:29:02', 0, '1', 5, '/user');
- INSERT INTO `sys_menu` VALUES (6, '用户管理二级菜单', 'user:er', '2023-12-15 05:29:02', 5, '1', 6, '/user/er');
- INSERT INTO `sys_menu` VALUES (7, '添加', 'user:er:add', '2023-12-15 05:26:52', 6, '2', 7, NULL);
- INSERT INTO `sys_menu` VALUES (8, '删除', 'user:er:del', '2023-12-15 05:26:52', 6, '2', 8, NULL);
- INSERT INTO `sys_menu` VALUES (9, '角色管理', 'role', '2023-12-15 05:29:02', 0, '1', 9, '/role');
- INSERT INTO `sys_menu` VALUES (10, '角色管理二级菜单', 'role:er', '2023-12-15 05:29:02', 9, '1', 10, '/role/er');
- INSERT INTO `sys_menu` VALUES (11, '添加', 'role:er:add', '2023-12-15 05:26:52', 10, '2', 11, NULL);
- INSERT INTO `sys_menu` VALUES (12, '删除', 'role:er:del', '2023-12-15 05:26:52', 10, '2', 12, NULL);
- INSERT INTO `sys_menu` VALUES (13, '权限管理', 'auth', '2023-12-15 05:29:02', 0, '1', 13, '/auth');
- INSERT INTO `sys_menu` VALUES (14, '权限管理二级菜单', 'auth:er', '2023-12-15 05:29:02', 13, '1', 14, '/auth/er');
- INSERT INTO `sys_menu` VALUES (15, '添加一级菜单', 'auth:er:add', '2023-12-15 05:26:52', 14, '2', 15, NULL);
- INSERT INTO `sys_menu` VALUES (16, '删除', 'auth:er:del', '2023-12-15 05:26:52', 14, '2', 16, NULL);
- INSERT INTO `sys_menu` VALUES (17, '应用管理', 'apply', '2023-12-16 20:43:40', 0, '1', 17, 'apply');
- INSERT INTO `sys_menu` VALUES (18, '应用管理二级菜单', 'apply:er', '2023-12-16 20:44:26', 17, '1', 18, '/apply/er');
- INSERT INTO `sys_menu` VALUES (19, '添加', 'apply:er:add', '2023-12-16 20:45:26', 18, '2', 19, NULL);
- INSERT INTO `sys_menu` VALUES (20, '修改', 'apply:er:edit', '2023-12-16 20:45:24', 18, '2', 20, NULL);
- INSERT INTO `sys_menu` VALUES (27, '删除', 'org:er:del', '2023-12-19 02:49:56', 2, '2', 30, NULL);
- INSERT INTO `sys_menu` VALUES (28, '分配角色', 'user:er:fp', '2023-12-19 02:51:05', 6, '2', 31, NULL);
- INSERT INTO `sys_menu` VALUES (29, '修改', 'role:er:edit', '2023-12-19 02:51:43', 10, '2', 32, NULL);
- INSERT INTO `sys_menu` VALUES (30, '分配权限', 'role:er:fp', '2023-12-19 02:52:02', 10, '2', 34, NULL);
- INSERT INTO `sys_menu` VALUES (31, '添加二级菜单', 'auth:er:add:sub', '2023-12-19 02:53:32', 14, '2', 35, NULL);
- INSERT INTO `sys_menu` VALUES (32, '修改', 'auth:er:edit', '2023-12-19 02:54:00', 14, '2', 37, NULL);
- INSERT INTO `sys_menu` VALUES (33, '添加按钮', 'auth:er:btn', '2023-12-19 07:36:36', 14, '2', 41, NULL);
-
- -- ----------------------------
- -- Table structure for sys_menu_role
- -- ----------------------------
- DROP TABLE IF EXISTS `sys_menu_role`;
- CREATE TABLE `sys_menu_role` (
- `id` int NOT NULL AUTO_INCREMENT,
- `role_id` int NULL DEFAULT NULL COMMENT '角色id',
- `menu_id` int NULL DEFAULT NULL COMMENT '权限id',
- PRIMARY KEY (`id`) USING BTREE,
- INDEX `idx_role_id`(`role_id` ASC) USING BTREE,
- INDEX `idx_menu_id`(`menu_id` ASC) USING BTREE
- ) ENGINE = InnoDB AUTO_INCREMENT = 575 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '权限角色关联表' ROW_FORMAT = Dynamic;
-
- -- ----------------------------
- -- Records of sys_menu_role
- -- ----------------------------
- INSERT INTO `sys_menu_role` VALUES (17, 2, 1);
- INSERT INTO `sys_menu_role` VALUES (18, 2, 2);
- INSERT INTO `sys_menu_role` VALUES (19, 2, 3);
- INSERT INTO `sys_menu_role` VALUES (20, 2, 4);
- INSERT INTO `sys_menu_role` VALUES (21, 2, 5);
- INSERT INTO `sys_menu_role` VALUES (22, 2, 6);
- INSERT INTO `sys_menu_role` VALUES (23, 2, 7);
- INSERT INTO `sys_menu_role` VALUES (24, 2, 8);
- INSERT INTO `sys_menu_role` VALUES (25, 2, 9);
- INSERT INTO `sys_menu_role` VALUES (26, 2, 10);
- INSERT INTO `sys_menu_role` VALUES (27, 2, 11);
- INSERT INTO `sys_menu_role` VALUES (28, 2, 12);
- INSERT INTO `sys_menu_role` VALUES (29, 2, 13);
- INSERT INTO `sys_menu_role` VALUES (30, 2, 14);
- INSERT INTO `sys_menu_role` VALUES (31, 2, 15);
- INSERT INTO `sys_menu_role` VALUES (32, 2, 16);
- INSERT INTO `sys_menu_role` VALUES (159, 3, 3);
- INSERT INTO `sys_menu_role` VALUES (160, 3, 4);
- INSERT INTO `sys_menu_role` VALUES (161, 3, 7);
- INSERT INTO `sys_menu_role` VALUES (162, 3, 8);
- INSERT INTO `sys_menu_role` VALUES (163, 3, 11);
- INSERT INTO `sys_menu_role` VALUES (164, 3, 12);
- INSERT INTO `sys_menu_role` VALUES (165, 3, 15);
- INSERT INTO `sys_menu_role` VALUES (166, 3, 16);
- INSERT INTO `sys_menu_role` VALUES (167, 3, 32);
- INSERT INTO `sys_menu_role` VALUES (168, 3, 17);
- INSERT INTO `sys_menu_role` VALUES (169, 3, 18);
- INSERT INTO `sys_menu_role` VALUES (170, 3, 19);
- INSERT INTO `sys_menu_role` VALUES (171, 3, 20);
- INSERT INTO `sys_menu_role` VALUES (515, 10, 1);
- INSERT INTO `sys_menu_role` VALUES (516, 10, 2);
- INSERT INTO `sys_menu_role` VALUES (517, 10, 3);
- INSERT INTO `sys_menu_role` VALUES (518, 10, 4);
- INSERT INTO `sys_menu_role` VALUES (519, 10, 27);
- INSERT INTO `sys_menu_role` VALUES (520, 10, 5);
- INSERT INTO `sys_menu_role` VALUES (521, 10, 6);
- INSERT INTO `sys_menu_role` VALUES (522, 10, 7);
- INSERT INTO `sys_menu_role` VALUES (523, 10, 8);
- INSERT INTO `sys_menu_role` VALUES (524, 10, 28);
- INSERT INTO `sys_menu_role` VALUES (525, 10, 20);
- INSERT INTO `sys_menu_role` VALUES (548, 1, 1);
- INSERT INTO `sys_menu_role` VALUES (549, 1, 2);
- INSERT INTO `sys_menu_role` VALUES (550, 1, 3);
- INSERT INTO `sys_menu_role` VALUES (551, 1, 4);
- INSERT INTO `sys_menu_role` VALUES (552, 1, 27);
- INSERT INTO `sys_menu_role` VALUES (553, 1, 5);
- INSERT INTO `sys_menu_role` VALUES (554, 1, 6);
- INSERT INTO `sys_menu_role` VALUES (555, 1, 7);
- INSERT INTO `sys_menu_role` VALUES (556, 1, 8);
- INSERT INTO `sys_menu_role` VALUES (557, 1, 28);
- INSERT INTO `sys_menu_role` VALUES (558, 1, 9);
- INSERT INTO `sys_menu_role` VALUES (559, 1, 10);
- INSERT INTO `sys_menu_role` VALUES (560, 1, 11);
- INSERT INTO `sys_menu_role` VALUES (561, 1, 12);
- INSERT INTO `sys_menu_role` VALUES (562, 1, 29);
- INSERT INTO `sys_menu_role` VALUES (563, 1, 30);
- INSERT INTO `sys_menu_role` VALUES (564, 1, 13);
- INSERT INTO `sys_menu_role` VALUES (565, 1, 14);
- INSERT INTO `sys_menu_role` VALUES (566, 1, 15);
- INSERT INTO `sys_menu_role` VALUES (567, 1, 16);
- INSERT INTO `sys_menu_role` VALUES (568, 1, 31);
- INSERT INTO `sys_menu_role` VALUES (569, 1, 32);
- INSERT INTO `sys_menu_role` VALUES (570, 1, 33);
- INSERT INTO `sys_menu_role` VALUES (571, 1, 17);
- INSERT INTO `sys_menu_role` VALUES (572, 1, 18);
- INSERT INTO `sys_menu_role` VALUES (573, 1, 19);
- INSERT INTO `sys_menu_role` VALUES (574, 1, 20);
-
- -- ----------------------------
- -- Table structure for sys_role
- -- ----------------------------
- DROP TABLE IF EXISTS `sys_role`;
- CREATE TABLE `sys_role` (
- `id` int NOT NULL AUTO_INCREMENT COMMENT '主键',
- `role_code` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '角色编码',
- `role_name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '角色名称',
- PRIMARY KEY (`id`) USING BTREE,
- INDEX `idx_role_code`(`role_code` ASC) USING BTREE
- ) ENGINE = InnoDB AUTO_INCREMENT = 12 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '角色表' ROW_FORMAT = Dynamic;
-
- -- ----------------------------
- -- Records of sys_role
- -- ----------------------------
- INSERT INTO `sys_role` VALUES (1, 'admin', '管理员');
- INSERT INTO `sys_role` VALUES (2, 'jingli', '经理');
- INSERT INTO `sys_role` VALUES (3, 'pt', '普通员工');
- INSERT INTO `sys_role` VALUES (10, 'caiwu', '财务');
-
- -- ----------------------------
- -- Table structure for sys_user
- -- ----------------------------
- DROP TABLE IF EXISTS `sys_user`;
- CREATE TABLE `sys_user` (
- `id` int NOT NULL AUTO_INCREMENT COMMENT '主键',
- `account` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '账号',
- `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '密码',
- `name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名',
- `create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
- PRIMARY KEY (`id`) USING BTREE,
- INDEX `idx_account`(`account` ASC) USING BTREE
- ) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '用户表' ROW_FORMAT = Dynamic;
-
- -- ----------------------------
- -- Records of sys_user
- -- ----------------------------
- INSERT INTO `sys_user` VALUES (1, 'zhangsan', '$2a$10$0nZBWnCqPASXP.cnA4vx7.yg3Bdxm4h8hGOZ2MDX25uFLQh/huui.', '张三', '2023-12-15 04:37:51');
- INSERT INTO `sys_user` VALUES (2, 'lisi', '$2a$10$0nZBWnCqPASXP.cnA4vx7.yg3Bdxm4h8hGOZ2MDX25uFLQh/huui.', '李四', '2023-12-15 04:38:07');
- INSERT INTO `sys_user` VALUES (3, 'zhaoliu', '123456', '赵六', '2023-12-15 04:38:24');
- INSERT INTO `sys_user` VALUES (4, 'wangwu', '$2a$10$xw3X/WlHz3hm6GvelIdztO/P1OS4uizN2kgii9Fiqf6rgjZYwR2.i', '王五', '2023-12-18 21:54:38');
- INSERT INTO `sys_user` VALUES (5, 'laojiu', '$2a$10$tAOkYkinUU2V7FkgbSTu6e0M2wjaQ2g.oZ0b9X28jndSK0rhfq81G', '老九', '2023-12-18 22:08:46');
- INSERT INTO `sys_user` VALUES (7, 'wmz', '$2a$10$bopmg91MtoGac65D3SxZxuxJCb2QCWDzQbOETAbQwuVyp9KpwGA/u', '王麻子', '2023-12-19 19:06:29');
-
- -- ----------------------------
- -- Table structure for sys_user_role
- -- ----------------------------
- DROP TABLE IF EXISTS `sys_user_role`;
- CREATE TABLE `sys_user_role` (
- `id` int NOT NULL AUTO_INCREMENT,
- `role_id` int NULL DEFAULT NULL COMMENT '角色id',
- `user_id` int NULL DEFAULT NULL COMMENT '用户id',
- PRIMARY KEY (`id`) USING BTREE,
- INDEX `idx_role_id`(`role_id` ASC) USING BTREE,
- INDEX `idx_user_id`(`user_id` ASC) USING BTREE
- ) ENGINE = InnoDB AUTO_INCREMENT = 34 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户角色关联表' ROW_FORMAT = Dynamic;
-
- -- ----------------------------
- -- Records of sys_user_role
- -- ----------------------------
- INSERT INTO `sys_user_role` VALUES (11, 2, 3);
- INSERT INTO `sys_user_role` VALUES (12, 3, 3);
- INSERT INTO `sys_user_role` VALUES (18, 2, 5);
- INSERT INTO `sys_user_role` VALUES (19, 2, 4);
- INSERT INTO `sys_user_role` VALUES (20, 3, 4);
- INSERT INTO `sys_user_role` VALUES (21, 1, 2);
- INSERT INTO `sys_user_role` VALUES (32, 1, 1);
- INSERT INTO `sys_user_role` VALUES (33, 10, 7);
-
- SET FOREIGN_KEY_CHECKS = 1;

- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.dmg</groupId>
- <artifactId>sp</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <name>sp</name>
- <description>sp</description>
- <properties>
- <java.version>17</java.version>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <spring-boot.version>3.0.2</spring-boot.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
-
- <!--必须引入webflux 否则 WebClient 不显示-->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-webflux</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-security</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <optional>true</optional>
- </dependency>
-
- <!-- 添加MyBatisPlus的依赖 -->
- <dependency>
- <groupId>com.baomidou</groupId>
- <artifactId>mybatis-plus-boot-starter</artifactId>
- <version>3.5.4.1</version>
- </dependency>
- <!-- MySQL数据 -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>8.0.16</version>
- </dependency>
- <!-- druid 连接池-->
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.1.14</version>
- </dependency>
- <!--JWT支持-->
- <dependency>
- <groupId>com.auth0</groupId>
- <artifactId>java-jwt</artifactId>
- <version>3.8.2</version>
- </dependency>
-
- <!--springboot3.0的版本中 mybatis也要3.0 否则报错-->
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>3.0.0</version>
- </dependency>
-
-
- </dependencies>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-dependencies</artifactId>
- <version>${spring-boot.version}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>3.8.1</version>
- <configuration>
- <source>17</source>
- <target>17</target>
- <encoding>UTF-8</encoding>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <version>${spring-boot.version}</version>
- <configuration>
- <mainClass>com.dmg.sp.SpApplication</mainClass>
- <skip>true</skip>
- </configuration>
- <executions>
- <execution>
- <id>repackage</id>
- <goals>
- <goal>repackage</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-
- </project>

- server:
- port: 8083
- spring:
- application:
- name: sp
- datasource:
- driverClassName: com.mysql.cj.jdbc.Driver
- type: com.alibaba.druid.pool.DruidDataSource
- url: jdbc:mysql://localhost:3306/sp?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&useSSL=true&allowMultiQueries=true
- username: root
- password: 123456
-
- mybatis-plus:
- configuration:
- log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
- mapper-locations: classpath:mapper/*.xml

- <?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.dmg.sp.dao.MenuMapper">
-
- <!--删除菜单关联的角色-->
- <delete id="deleteRole">
- DELETE from sys_menu_role
- WHERE menu_id=#{id}
- </delete>
-
-
- <!--根据菜单id集合 获取对应的权限-->
- <select id="getAuthList" resultType="com.dmg.sp.entity.Menu">
- SELECT id,auth,path from sys_menu
- WHERE id in
- <foreach item="item" collection="ids" index="index" open="("
- separator="," close=")">
- #{item}
- </foreach>
- </select>
-
-
- <!--获取所有菜单-->
- <select id="getMenuList" resultType="com.dmg.sp.entity.Menu">
- SELECT * from sys_menu
- ORDER BY pai_xu
- </select>
-
-
- <!--查看角色对应的权限-->
- <select id="getRoleAuth" resultType="java.lang.String">
- SELECT
- auth
- FROM
- sys_menu
- WHERE
- id IN ( SELECT menu_id FROM sys_menu_role WHERE role_id = #{roleId} )
- ORDER BY
- pai_xu
- </select>
-
- <!--查询用户关联的菜单id-->
- <select id="getMenuIdsByUserId" resultType="Integer">
- SELECT
- menu_id
- FROM
- sys_menu_role
- WHERE
- role_id IN ( SELECT role_id FROM sys_user_role WHERE user_id = #{userId} )
- </select>
-
- <!--根据菜单id集合查询父级id -->
- <select id="getPIdsByIds" resultType="Integer">
- SELECT DISTINCT
- parent_id
- FROM
- sys_menu
- WHERE
- id IN
- <foreach item="item" collection="ids" index="index" open="("
- separator="," close=")">
- #{item}
- </foreach>
- </select>
-
- </mapper>

- <?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.dmg.sp.dao.RoleMapper">
-
-
- <!--为角色分配权限-->
- <insert id="addRoleAuth">
- INSERT INTO `sys_menu_role` (`role_id`, `menu_id`)
- VALUES
- <foreach collection="menuIds" item="item" index="index" separator=",">
- (#{roleId},#{item})
- </foreach>
- </insert>
-
-
- <!--删除角色关联的用户-->
- <delete id="deleteUser">
- DELETE from sys_user_role
- WHERE role_id=#{id}
- </delete>
-
- <!--删除角色关联的权限-->
- <delete id="deleteAuth">
- DELETE from sys_menu_role
- WHERE role_id=#{id}
- </delete>
-
- <!--查看用户对应的角色-->
- <select id="getUserRole" resultType="com.dmg.sp.entity.Role">
- SELECT * from sys_role
- WHERE id in(
- SELECT role_id from sys_user_role
- WHERE user_id=#{userId}
- )
- </select>
-
-
- </mapper>

- <?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.dmg.sp.dao.UserMapper">
-
-
- <!--为用户分配角色-->
- <insert id="addUserRole">
- INSERT INTO `sys_user_role` (`role_id`, `user_id`)
- VALUES
- <foreach collection="roleIds" item="item" index="index" separator=",">
- (#{item},#{userId})
- </foreach>
- </insert>
-
- <!--删除用户关联的角色-->
- <delete id="deleteRole">
- DELETE from sys_user_role
- WHERE user_id=#{id}
- </delete>
-
- <!--查看用户对应的角色id-->
- <select id="getUserRoleIds" resultType="Integer">
- SELECT role_id from sys_user_role
- WHERE user_id=#{userId}
- </select>
-
- </mapper>

- package com.dmg.sp.config;
-
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.cors.CorsConfiguration;
- import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
- import org.springframework.web.filter.CorsFilter;
- import org.springframework.web.servlet.config.annotation.CorsRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
-
- //解决跨域
- @Configuration
- public class CorsConfig implements WebMvcConfigurer {
-
- @Override
- public void addCorsMappings(CorsRegistry registry) {
- //设置允许跨域的域名
- registry.addMapping("/**")
- //设置允许跨域的域名
- .allowedOriginPatterns("*")
- //是否允许cookie
- .allowCredentials(true)
- //设置允许请求的方式
- .allowedMethods(new String[]{"GET","POST","PUT","DELETE","OPTIONS"})
- //设置允许的请求头
- .allowedHeaders("*")
- //跨域允许时间
- .maxAge(3600);
- }
- }

- package com.dmg.sp.config;
-
- import com.auth0.jwt.interfaces.Claim;
- import com.dmg.sp.service.UserService;
- import com.dmg.sp.utils.JWTUtil;
- import jakarta.servlet.FilterChain;
- import jakarta.servlet.ServletException;
- import jakarta.servlet.http.HttpServletRequest;
- import jakarta.servlet.http.HttpServletResponse;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.http.HttpMethod;
- import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
- import org.springframework.security.core.Authentication;
- import org.springframework.security.core.context.SecurityContext;
- import org.springframework.security.core.context.SecurityContextHolder;
- import org.springframework.security.core.userdetails.UserDetails;
- import org.springframework.security.web.SecurityFilterChain;
- import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
- import org.springframework.stereotype.Component;
- import org.springframework.util.AntPathMatcher;
- import org.springframework.util.StringUtils;
- import org.springframework.web.filter.OncePerRequestFilter;
-
- import java.io.IOException;
- import java.util.Map;
-
- /**
- * 只登陆1次
- */
- @Slf4j
- @Component
- public class JwtAuthenticationFilter extends OncePerRequestFilter {
-
- @Autowired
- private UserService userService;
-
- /**
- * 所有请求的过滤器
- * @param request
- * @param response
- * @param filterChain
- * @throws ServletException
- * @throws IOException
- */
- @Override
- protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
- //origin:指定可以访问本项目的IP
- String origin = request.getHeader("Origin");
- response.setContentType("application/json;charset=UTF-8");
- response.setHeader("Access-Control-Allow-Origin", origin);
- response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
- response.setHeader("Access-Control-Max-Age", "1800");
- // 设置 受支持请求标头(自定义 可以访问的请求头 例如:Token)
- response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,token,Origin,Content-Type,Accept");
- // 指示的请求的响应是否可以暴露于该页面。当true值返回时它可以被暴露
- response.setHeader("Access-Control-Allow-Credentials", "true");
- //如果是OPTIONS请求,让其响应一个 200状态码,说明可以正常访问
- if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
- response.setStatus(HttpServletResponse.SC_OK);
- return;
- }
-
- //获取token信息
- String header=request.getHeader("Authorization");
- log.info("header:{}",header);
- //注意Bearer后面还有一个空格
- if(StringUtils.isEmpty(header) || !StringUtils.startsWithIgnoreCase(header,"Bearer ")){
- //如果请求头是空的 或者 前置没有以Bearer 开头 那么进入下一个过滤器链
- filterChain.doFilter(request,response);
- return;
- }
- //把Bearer空格去掉
- String jwt=header.substring(7);
- //获取token信息 第二个参数是盐值
- Map<String, Claim> tokenInfo= JWTUtil.getTokenInfo(jwt,"123456789");
- String account=tokenInfo.get("account").asString();
-
- //获取认证信息是否存在
- Authentication auth = SecurityContextHolder.getContext().getAuthentication();
- if(!StringUtils.isEmpty(account) && auth==null){
- //如果账号不为空 并且 认证信息是空的
- //获取用户信息
- UserDetails userDetails = userService.loadUserByUsername(account);
- if(account.equals(userDetails.getUsername())){
- //如果用户信息不为空
- SecurityContext securityContext=SecurityContextHolder.createEmptyContext();
- //创建用户 认证token 对象
- UsernamePasswordAuthenticationToken upt=new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
- //把web的请求信息 放到Details
- upt.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
- //把用户信息放到 安全上下文中
- securityContext.setAuthentication(upt);
- SecurityContextHolder.setContext(securityContext);
- }
-
- }
- //放行
- filterChain.doFilter(request,response);
- }
-
-
- }

- package com.dmg.sp.config;
-
- import com.dmg.sp.utils.Result;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import jakarta.servlet.ServletException;
- import jakarta.servlet.http.HttpServletRequest;
- import jakarta.servlet.http.HttpServletResponse;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.security.authentication.BadCredentialsException;
- import org.springframework.security.authentication.InsufficientAuthenticationException;
- import org.springframework.security.core.AuthenticationException;
- import org.springframework.security.web.AuthenticationEntryPoint;
- import org.springframework.stereotype.Component;
- import org.springframework.web.util.WebUtils;
-
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.HashMap;
- import java.util.Map;
-
- /**
- * 我的身份验证入口点
- * 没有登陆认证 异常处理器
- * @param
- * @return
- * @throws Exception
- */
- @Slf4j
- @Component
- public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
-
- @Override
- public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
- //返回json格式
- response.setContentType("application/json;charset=utf-8");
- //没有登陆 直接访问其他接口 就报401
- response.setStatus(401);
- Result<String> result = Result.error("401", "请先登录");
- ObjectMapper objectMapper=new ObjectMapper();
- String s=objectMapper.writeValueAsString(result);
- //把json数据 写入 返回给前端
- PrintWriter writer=response.getWriter();
- writer.write(s);
- writer.flush();
- writer.close();
- }
- }

- package com.dmg.sp.config;
-
-
- import com.baomidou.mybatisplus.core.toolkit.StringUtils;
- import com.dmg.sp.dao.MenuMapper;
- import com.dmg.sp.entity.Menu;
- import com.dmg.sp.service.MenuService;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.http.HttpMethod;
- import org.springframework.security.access.AccessDecisionManager;
- import org.springframework.security.access.AccessDecisionVoter;
- import org.springframework.security.access.vote.AuthenticatedVoter;
- import org.springframework.security.access.vote.UnanimousBased;
- import org.springframework.security.authentication.AnonymousAuthenticationToken;
- import org.springframework.security.authentication.AuthenticationManager;
- import org.springframework.security.authorization.AuthorizationDecision;
- import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
- import org.springframework.security.config.annotation.web.builders.HttpSecurity;
- import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
- import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
- import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
- import org.springframework.security.config.http.SessionCreationPolicy;
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
- import org.springframework.security.crypto.password.PasswordEncoder;
- import org.springframework.security.web.SecurityFilterChain;
- import org.springframework.security.web.access.expression.WebExpressionVoter;
- import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
- import org.springframework.util.AntPathMatcher;
- import org.springframework.util.CollectionUtils;
-
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.List;
-
- @EnableWebSecurity
- @Slf4j
- @Configuration
- public class SpConfig {
-
- @Autowired
- private JwtAuthenticationFilter jwtAuthenticationFilter;
-
- @Autowired
- private MyAuthenticationEntryPoint myAuthenticationEntryPoint;
-
- @Autowired
- private MenuMapper menuMapper;
-
-
- //密码加密
- @Bean
- public PasswordEncoder passwordEncoder(){
- return new BCryptPasswordEncoder();
- }
-
- //安全过滤器链
- @Bean
- public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
-
- //每次都需要认证 不需要session 会话管理策略设置为无状态,这样就可以防止应用程序的会话被劫持攻击。
- http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
- http
- //禁用表单登录 前后分离用不上
- .formLogin().disable()
- //先进行jwt 校验 在进行账号密码登录
- .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
- //动态拦截所有请求 如果没有匹配上的 那么就拦截
- .authorizeHttpRequests(x->x.anyRequest().authenticated())
- //没有登录 直接返回异常信息
- .exceptionHandling(x->x.authenticationEntryPoint(myAuthenticationEntryPoint))
- //关闭csrf
- .csrf().disable();
- //创建对象
- return http.build();
- }
-
-
- //忽略路径 放行路径
- @Bean
- public WebSecurityCustomizer webSecurityCustomizer(){
- //放行登录接口 这样才能登录成功
- return x->x.ignoring().requestMatchers("/dengLu");
- }
-
-
- /**
- * 把认证管理器注入到容器
- * LoginServiceImpl类中 才能使用这个认证接口
- * @param config
- * @return
- * @throws Exception
- */
- @Bean
- public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
- return config.getAuthenticationManager();
- }
-
- }

- package com.dmg.sp.controller;
-
-
- import com.dmg.sp.service.LoginService;
- import com.dmg.sp.utils.Result;
- import com.dmg.sp.vo.LoginVo;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.CrossOrigin;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RestController;
-
-
- @Slf4j
- @RestController
- public class LoginController {
-
- @Autowired
- private LoginService loginService;
-
- /**
- * 登录
- * @param vo
- * @return
- */
- @PostMapping("/dengLu")
- public Result dengLu(@RequestBody LoginVo vo){
- return loginService.login(vo);
- }
- }

- package com.dmg.sp.controller;
-
-
- import com.dmg.sp.entity.Menu;
- import com.dmg.sp.entity.MyUserDetails;
- import com.dmg.sp.entity.Role;
- import com.dmg.sp.service.MenuService;
- import com.dmg.sp.utils.Result;
- import com.dmg.sp.vo.IdVo;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.security.core.Authentication;
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.security.core.context.SecurityContextHolder;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RestController;
-
- import java.util.Collection;
- import java.util.List;
- import java.util.stream.Collectors;
-
- @RestController
- public class MenuController {
-
- @Autowired
- private MenuService menuService;
-
- /**
- * 获取当前登录人的权限
- * @return
- */
- @PostMapping("/getMyAuth")
- public Result getMyAuth(){
- //从认证信息上下文中 获取用户权限
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- MyUserDetails myUserDetails =(MyUserDetails) authentication.getPrincipal();
- return Result.success(myUserDetails.getAuthList());
- }
-
- /**
- * 获取所有菜单和权限(包括按钮)
- * @return
- */
- @PostMapping("/getMenuList")
- public Result getMenuList(){
- //根据用户id 获取对应的菜单
- List<Menu> list=menuService.getMenuList();
- return Result.success(list);
- }
-
- /**
- * 添加菜单
- * @return
- */
- @PostMapping("/addMenu")
- public Result addMenu(@RequestBody Menu menu){
- menuService.addMenu(menu);
- return Result.success();
- }
-
- /**
- * 修改菜单
- * @return
- */
- @PostMapping("/editMenu")
- public Result editMenu(@RequestBody Menu menu){
- menuService.editMenu(menu);
- return Result.success();
- }
-
- /**
- * 删除菜单
- * @return
- */
- @PostMapping("/deleteMenu")
- public Result deleteMenu(@RequestBody Menu menu){
- menuService.deleteMenu(menu.getId());
- return Result.success();
- }
-
- /**
- * 查看菜单详情
- * @return
- */
- @PostMapping("/getMenuById")
- public Result getMenuById(@RequestBody Menu menu){
- return Result.success(menuService.getMenuById(menu.getId()));
- }
-
- /**
- * 查看角色对应的权限
- * @return
- */
- @PostMapping("/getRoleAuth")
- public Result getRoleAuth(@RequestBody IdVo vo){
- return Result.success(menuService.getRoleAuth(vo.getRoleId()));
- }
- }

- package com.dmg.sp.controller;
-
-
- import com.dmg.sp.entity.Menu;
- import com.dmg.sp.entity.MyUserDetails;
- import com.dmg.sp.entity.Role;
- import com.dmg.sp.service.RoleService;
- import com.dmg.sp.utils.Result;
- import com.dmg.sp.vo.IdVo;
- import com.dmg.sp.vo.RoleAuthVo;
- import com.dmg.sp.vo.UserRoleVo;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.security.core.Authentication;
- import org.springframework.security.core.context.SecurityContextHolder;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RestController;
-
- import java.util.List;
-
- @RestController
- public class RoleController {
-
- @Autowired
- private RoleService roleService;
-
- /**
- * 获取所有角色
- * @return
- */
- @PostMapping("/getRoleList")
- public Result getRoleList(){
- List<Role> list=roleService.getRoleList();
- return Result.success(list);
- }
-
- /**
- * 添加角色
- * @return
- */
- @PostMapping("/addRole")
- public Result addRole(@RequestBody Role role){
- roleService.addRole(role);
- return Result.success();
- }
-
- /**
- * 修改角色
- * @return
- */
- @PostMapping("/editRole")
- public Result editRole(@RequestBody Role role){
- roleService.editRole(role);
- return Result.success();
- }
-
- /**
- * 删除角色
- * @return
- */
- @PostMapping("/deleteRole")
- public Result deleteRole(@RequestBody Role role){
- roleService.deleteRole(role.getId());
- return Result.success();
- }
-
- /**
- * 查看角色详情
- * @return
- */
- @PostMapping("/getRoleById")
- public Result getRoleById(@RequestBody Role role){
- return Result.success(roleService.getRoleById(role.getId()));
- }
-
- /**
- * 查看用户对应的角色
- * @return
- */
- @PostMapping("/getUserRole")
- public Result getUserRole(@RequestBody IdVo vo){
- return Result.success(roleService.getUserRole(vo.getUserId()));
- }
-
- /**
- * 为角色分配权限
- * @return
- */
- @PostMapping("/setRoleAuth")
- public Result setRoleAuth(@RequestBody RoleAuthVo vo){
- roleService.setRoleAuth(vo);
- return Result.success();
- }
-
- }

- package com.dmg.sp.controller;
-
-
- import com.dmg.sp.entity.MyUserDetails;
- import com.dmg.sp.entity.Role;
- import com.dmg.sp.entity.User;
- import com.dmg.sp.service.RoleService;
- import com.dmg.sp.service.SysUserService;
- import com.dmg.sp.utils.Result;
- import com.dmg.sp.vo.IdVo;
- import com.dmg.sp.vo.UserRoleVo;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.security.core.Authentication;
- import org.springframework.security.core.context.SecurityContextHolder;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RestController;
-
- import java.util.List;
-
- @RestController
- public class UserController {
-
-
- @Autowired
- private SysUserService sysUserService;
-
- /**
- * 获取所有用户
- * @return
- */
- @PostMapping("/getUserList")
- public Result getUserList(){
- List<User> list=sysUserService.getUserList();
- return Result.success(list);
- }
-
- /**
- * 为用户分配角色
- * @return
- */
- @PostMapping("/setUserRole")
- public Result setUserRole(@RequestBody UserRoleVo vo){
- sysUserService.setUserRole(vo);
- return Result.success();
- }
-
-
- /**
- * 添加用户
- * @return
- */
- @PostMapping("/addUser")
- public Result addUser(@RequestBody User user){
- sysUserService.addUser(user);
- return Result.success();
- }
-
-
- /**
- * 获取当前登录人信息
- * @return
- */
- @PostMapping("/getUserInfo")
- public Result getUserInfo(){
- //从认证信息上下文中 获取用户权限
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- MyUserDetails myUserDetails =(MyUserDetails) authentication.getPrincipal();
- User user = myUserDetails.getUser();
- return Result.success(user);
- }
-
-
- /**
- * 查看用户对应的角色id
- * @return
- */
- @PostMapping("/getUserRoleIds")
- public Result getUserRoleIds(@RequestBody IdVo vo){
- return Result.success(sysUserService.getUserRoleIds(vo.getUserId()));
- }
- }

- package com.dmg.sp.dao;
-
- import com.baomidou.mybatisplus.core.mapper.BaseMapper;
- import com.dmg.sp.entity.Menu;
- import org.apache.ibatis.annotations.Param;
-
- import java.util.List;
-
-
- public interface MenuMapper extends BaseMapper<Menu> {
-
-
- /**
- * 根据菜单id集合 获取对应的权限
- * @param ids
- * @return
- */
- public List<Menu>getAuthList(@Param("ids") List<Integer> ids);
-
- /**
- * 获取所有菜单
- * @return
- */
- List<Menu> getMenuList();
-
- /**
- * 删除菜单关联的角色
- * @return
- */
- Integer deleteRole(Integer id);
-
-
- /**
- * 查看角色对应的权限
- * @return
- */
- public List<String> getRoleAuth(@Param("roleId") Integer roleId);
-
- /**
- * 查询用户关联的菜单id
- * @param userId
- * @return
- */
- public List<Integer> getMenuIdsByUserId(@Param("userId") Integer userId);
-
- /**
- * 根据菜单id集合查询父级id
- * @param ids
- * @return
- */
- public List<Integer> getPIdsByIds(@Param("ids") List<Integer> ids);
- }

- package com.dmg.sp.dao;
-
- import com.baomidou.mybatisplus.core.mapper.BaseMapper;
- import com.dmg.sp.entity.Role;
- import com.dmg.sp.entity.User;
- import org.apache.ibatis.annotations.Param;
-
- import java.util.List;
-
- public interface RoleMapper extends BaseMapper<Role> {
-
- /**
- * 删除角色关联的用户
- * @param id
- * @return
- */
- Integer deleteUser(@Param("id") Integer id);
-
- /**
- * 删除角色关联的权限
- * @param id
- * @return
- */
- Integer deleteAuth(@Param("id") Integer id);
-
- /**
- * 查看用户对应的角色
- * @param userId
- * @return
- */
- public List<Role> getUserRole(@Param("userId") Integer userId);
-
- /**
- * 为角色分配权限
- * @return
- */
- public Integer addRoleAuth(@Param("roleId") Integer roleId,
- @Param("menuIds") List<Integer> menuIds);
- }

- package com.dmg.sp.dao;
-
- import com.baomidou.mybatisplus.core.mapper.BaseMapper;
- import com.dmg.sp.entity.User;
- import com.dmg.sp.vo.UserRoleVo;
- import org.apache.ibatis.annotations.Mapper;
- import org.apache.ibatis.annotations.Param;
-
- import java.util.List;
-
-
- public interface UserMapper extends BaseMapper<User> {
-
- /**
- * 删除用户关联的角色
- * @param id
- * @return
- */
- public Integer deleteRole(@Param("id") Integer id);
-
- /**
- * 为用户分配角色
- * @return
- */
- public Integer addUserRole(@Param("userId") Integer userId,
- @Param("roleIds") List<Integer> roleIds);
-
- /**
- * 查看用户对应的角色id
- * @return
- */
- public List<Integer>getUserRoleIds(@Param("userId") Integer userId);
- }

- package com.dmg.sp.entity;
-
-
- import com.baomidou.mybatisplus.annotation.IdType;
- import com.baomidou.mybatisplus.annotation.TableField;
- import com.baomidou.mybatisplus.annotation.TableId;
- import com.baomidou.mybatisplus.annotation.TableName;
- import com.fasterxml.jackson.annotation.JsonFormat;
- import lombok.Data;
-
- import java.util.Date;
- import java.util.List;
-
- @Data
- @TableName("sys_menu")
- public class Menu {
-
- @TableId(type = IdType.AUTO)
- private Integer id;
-
- //菜单名称/按钮名称
- private String name;
-
- //权限名称
- private String auth;
-
- //创建日期
- @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
- private Date createTime;
-
- //父级id
- private Integer parentId;
-
- //类型 1:菜单 , 2:按钮
- private String isType;
-
- //排序序号
- private Integer paiXu;
-
- /**
- * 前端vue 跳转路径
- */
- private String path;
-
- //子集菜单
- @TableField(exist = false)
- private List<Menu> children;
- }

- package com.dmg.sp.entity;
-
- import lombok.Data;
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.security.core.authority.SimpleGrantedAuthority;
- import org.springframework.security.core.userdetails.UserDetails;
-
- import java.util.Arrays;
- import java.util.Collection;
- import java.util.List;
- import java.util.stream.Collectors;
-
- /**
- * UserDetails 用户详细信息接口
- *
- * @param
- * @return
- * @throws Exception
- */
- @Data
- public class MyUserDetails implements UserDetails {
-
-
- private User user;
-
- private List<SimpleGrantedAuthority> simpleGrantedAuthorityList;
-
- public MyUserDetails(User user,List<SimpleGrantedAuthority> simpleGrantedAuthorityList){
- this.user=user;
- this.simpleGrantedAuthorityList=simpleGrantedAuthorityList;
- }
-
- /**
- * 获取所有权限
- * @return
- */
- @Override
- public Collection<? extends GrantedAuthority> getAuthorities() {
- return simpleGrantedAuthorityList;
- }
-
- @Override
- public String getPassword() {
- return user.getPassword();
- }
-
- @Override
- public String getUsername() {
- return user.getAccount();
- }
-
- @Override
- public boolean isAccountNonExpired() {
- return true;
- }
-
- @Override
- public boolean isAccountNonLocked() {
- return true;
- }
-
- @Override
- public boolean isCredentialsNonExpired() {
- return true;
- }
-
- //是否启用 true:启用, false:禁用
- @Override
- public boolean isEnabled() {
- return true;
- }
-
- /**
- * 二次处理权限
- * 获取字符串集合的权限
- * @return
- */
- public List<String>getAuthList(){
- //转成list集合
- return simpleGrantedAuthorityList.stream().map(x->x.getAuthority()).collect(Collectors.toList());
- }
- }

- package com.dmg.sp.entity;
-
-
- import com.baomidou.mybatisplus.annotation.IdType;
- import com.baomidou.mybatisplus.annotation.TableId;
- import com.baomidou.mybatisplus.annotation.TableName;
- import lombok.Data;
-
- @Data
- @TableName("sys_role")
- public class Role {
-
- @TableId(type = IdType.AUTO)
- private Integer id;
-
- //角色编码
- private String roleCode;
-
- //角色名称
- private String roleName;
- }

- package com.dmg.sp.entity;
-
- import com.baomidou.mybatisplus.annotation.IdType;
- import com.baomidou.mybatisplus.annotation.TableField;
- import com.baomidou.mybatisplus.annotation.TableId;
- import com.baomidou.mybatisplus.annotation.TableName;
- import com.fasterxml.jackson.annotation.JsonFormat;
- import lombok.Data;
-
- import java.util.Date;
- import java.util.List;
-
-
- @Data
- @TableName("sys_user")
- public class User {
-
- @TableId(type = IdType.AUTO)
- private Integer id;
-
- //账号
- private String account;
-
- //密码
- private String password;
-
- //姓名
- private String name;
-
- //创建日期
- @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
- private Date createTime;
-
- @TableField(exist = false)
- private List<Menu> menu;
-
- }

- package com.dmg.sp.service;
-
- import com.dmg.sp.utils.Result;
- import com.dmg.sp.vo.LoginVo;
-
- public interface LoginService {
-
- public Result login(LoginVo vo);
- }
- package com.dmg.sp.service;
-
- import com.dmg.sp.entity.Menu;
- import org.springframework.web.bind.annotation.RequestBody;
-
- import java.util.List;
-
- public interface MenuService {
-
-
- List<Menu> getMenuList();
-
- public void addMenu(Menu menu);
- public void editMenu(Menu menu);
- public void deleteMenu(Integer id);
- public Menu getMenuById(Integer id);
-
- public List<String> getRoleAuth(Integer roleId);
-
- /**
- * 获取当前登录人的菜单信息
- * @return
- */
- public List<Menu> getMyMenu();
- }

- package com.dmg.sp.service;
-
- import com.dmg.sp.entity.Role;
- import com.dmg.sp.utils.Result;
- import com.dmg.sp.vo.IdVo;
- import com.dmg.sp.vo.RoleAuthVo;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestBody;
-
- import java.util.List;
-
- public interface RoleService {
-
- public List<Role>getRoleList();
- public void addRole(Role role);
- public void editRole(Role role);
- public void deleteRole(Integer id);
- public Role getRoleById(Integer id);
- public List<Role> getUserRole(Integer userId);
- public void setRoleAuth(RoleAuthVo vo);
-
- }

- package com.dmg.sp.service;
-
- import com.dmg.sp.entity.User;
- import com.dmg.sp.utils.Result;
- import com.dmg.sp.vo.UserRoleVo;
- import org.apache.ibatis.annotations.Param;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestBody;
-
- import java.util.List;
-
- public interface SysUserService {
-
- List<User> getUserList();
-
- /**
- * 为用户分配角色
- * @return
- */
- public void setUserRole(UserRoleVo vo);
-
- public void addUser(User user);
-
-
- /**
- * 查看用户对应的角色id
- * @return
- */
- public List<Integer>getUserRoleIds(Integer userId);
-
- }

- package com.dmg.sp.service;
-
- import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
- import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
- import com.dmg.sp.dao.MenuMapper;
- import com.dmg.sp.dao.UserMapper;
- import com.dmg.sp.entity.Menu;
- import com.dmg.sp.entity.MyUserDetails;
- import com.dmg.sp.entity.User;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.security.core.authority.SimpleGrantedAuthority;
- import org.springframework.security.core.userdetails.UserDetails;
- import org.springframework.security.core.userdetails.UserDetailsService;
- import org.springframework.security.core.userdetails.UsernameNotFoundException;
- import org.springframework.stereotype.Service;
-
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
-
- /**
- * UserDetailsService 用户查询接口
- *
- * @param
- * @return
- * @throws Exception
- */
- @Slf4j
- @Service
- public class UserService implements UserDetailsService {
-
- @Autowired
- private UserMapper userMapper;
- @Autowired
- private MenuMapper menuMapper;
-
-
- /**
- * 根据账号查询用户信息
- * @param
- * @return
- * @throws Exception
- */
- @Override
- public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
- log.info("根据账号查询用户信息==========================================================");
- QueryWrapper<User>queryWrapper=new QueryWrapper<>();
- queryWrapper.eq("account",username);
- User user = userMapper.selectOne(queryWrapper);
- if(user==null){
- log.info("用户不存在");
- throw new UsernameNotFoundException("用户不存在");
- }
- //根据用户id获取权限信息
- List<Menu>auths=getAuthList(user.getId());
- //组装权限信息 放入 SimpleGrantedAuthority
- List<SimpleGrantedAuthority> simpleGrantedAuthorityList=getGrantedAuthority(auths);
- //把权限放入用户对象中
- user.setMenu(auths);
- //最后返回UserDetails对象
- return new MyUserDetails(user,simpleGrantedAuthorityList);
- }
-
-
- /**
- * 组装权限信息 放入 SimpleGrantedAuthority
- * @return
- */
- private List<SimpleGrantedAuthority> getGrantedAuthority(List<Menu>auths){
- List<SimpleGrantedAuthority> list=new ArrayList<>();
- for (Menu x : auths) {
- SimpleGrantedAuthority simpleGrantedAuthority=new SimpleGrantedAuthority(x.getAuth());
- list.add(simpleGrantedAuthority);
- }
- return list;
- }
-
-
- /**
- * 根据用户id 获取所有权限
- * 在分配权限的时候 如果只选择了按钮
- * 那么也会把他的父级菜单给查询出来
- *
- * 只有按钮都不选择的时候 菜单才不展示
- * @param userId
- * @return
- */
- private List<Menu> getAuthList(Integer userId){
- //查询用户关联的菜单id 按钮
- List<Integer> menuIds = menuMapper.getMenuIdsByUserId(userId);
- if(CollectionUtils.isEmpty(menuIds)){
- //如果还没有授权 直接返回空
- return new ArrayList<>();
- }
- //根据菜单id 查询父级 id 二级菜单
- List<Integer> pIds=menuMapper.getPIdsByIds(menuIds);
- if(CollectionUtils.isEmpty(pIds)){
- //如果没有父级id 直接返回关联的权限
- return menuMapper.getAuthList(menuIds);
- }
- //根据pIds 查询父级 id 一级菜单
- List<Integer> oneIds=menuMapper.getPIdsByIds(pIds);
- //通过所有的菜单id 查询权限信息
- oneIds.addAll(pIds);
- oneIds.addAll(menuIds);
- return menuMapper.getAuthList(oneIds);
- }
- }

- package com.dmg.sp.service.impl;
-
- import com.dmg.sp.entity.MyUserDetails;
- import com.dmg.sp.service.LoginService;
- import com.dmg.sp.utils.JWTUtil;
- import com.dmg.sp.utils.Result;
- import com.dmg.sp.vo.LoginVo;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.security.authentication.AuthenticationManager;
- import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
- import org.springframework.security.core.Authentication;
- import org.springframework.stereotype.Service;
-
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Objects;
-
- @Slf4j
- @Service
- public class LoginServiceImpl implements LoginService {
-
-
- //认证管理器
- @Autowired
- private AuthenticationManager authenticationManager;
-
- @Override
- public Result login(LoginVo vo) {
- //根据账号和密码 创建 认证令牌对象
- UsernamePasswordAuthenticationToken upt=new UsernamePasswordAuthenticationToken(vo.getAccount(),vo.getPassword());
- //进行登录 获取认证信息
- Authentication authenticate = authenticationManager.authenticate(upt);
- if(authenticate==null){
- throw new RuntimeException("登录失败");
- }
- Map<String,String> map=new HashMap<>();
- map.put("account",vo.getAccount());
- //第二个参数是盐值
- //获取token
- String token= JWTUtil.getToken(map,"123456789");
- return Result.success(token);
- }
- }

- package com.dmg.sp.service.impl;
-
- import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
- import com.dmg.sp.dao.MenuMapper;
- import com.dmg.sp.entity.Menu;
- import com.dmg.sp.entity.MyUserDetails;
- import com.dmg.sp.entity.Role;
- import com.dmg.sp.service.MenuService;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.security.core.Authentication;
- import org.springframework.security.core.context.SecurityContextHolder;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import org.springframework.util.CollectionUtils;
- import org.springframework.util.StringUtils;
-
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
-
-
- @Slf4j
- @Service
- public class MenuServiceImpl implements MenuService {
-
- @Autowired
- private MenuMapper menuMapper;
-
-
- /**
- * 获取所有菜单
- * @return
- */
- @Override
- public List<Menu> getMenuList() {
- List<Menu>res=new ArrayList<>();
- List<Menu>list=menuMapper.getMenuList();
- //递归放入 子菜单
- for (Menu x : list) {
- if(x.getIsType().equals("2")){
- //如果是按钮 直接跳过 因为是 最后一层
- continue;
- }
- dfs(x,list);
- if(x.getParentId()==0){
- //只把一级菜单放入集合中 其他级别的菜单都在一级菜单的子集中
- res.add(x);
- }
- }
- return res;
- }
-
-
- /**
- * 添加菜单
- * @param menu
- */
- @Transactional(rollbackFor = Exception.class)
- @Override
- public void addMenu(Menu menu) {
- //根据权限查询是否存在
- if(getByAuth(menu.getAuth())!=null){
- throw new RuntimeException("权限已存在");
- }
- menu.setCreateTime(new Date());
- menuMapper.insert(menu);
- }
-
-
-
- /**
- * 修改菜单
- * @param menu
- */
- @Transactional(rollbackFor = Exception.class)
- @Override
- public void editMenu(Menu menu) {
- Menu bean=menuMapper.selectById(menu.getId());
- if(bean==null){
- throw new RuntimeException("菜单不存在");
- }
- Menu item=getByAuth(menu.getAuth());
- if(item!=null && !item.getAuth().equals(bean.getAuth())){
- //如果不是当前菜单的权限,并且已存在 那么抛出异常
- throw new RuntimeException("权限已存在");
- }
- menuMapper.updateById(menu);
- }
-
-
- /**
- * 删除菜单
- * @param id
- */
- @Transactional(rollbackFor = Exception.class)
- @Override
- public void deleteMenu(Integer id) {
- //判断菜单是否存在
- if(menuMapper.selectById(id)==null){
- throw new RuntimeException("菜单不存在");
- }
- //判断当前是否有子集,如果有子集 不允许删除
- if(getPIdCount(id)>0){
- throw new RuntimeException("当前菜单下,还有子集,请先删除子集");
- }
- //删除菜单关联的角色
- menuMapper.deleteRole(id);
- //删除菜单
- menuMapper.deleteById(id);
- }
-
-
- /**
- * 根据菜单id 查看详情
- * @param id
- */
- @Override
- public Menu getMenuById(Integer id) {
- return menuMapper.selectById(id);
- }
-
- /**
- * 查看角色对应的权限
- * @return
- */
- @Override
- public List<String> getRoleAuth(Integer roleId) {
- return menuMapper.getRoleAuth(roleId);
- }
-
-
-
-
-
- /**
- * 递归放入父级中
- * @param x
- * @param list
- */
- private void dfs(Menu x,List<Menu>list){
- for (Menu menu : list) {
- if(menu.getParentId().equals(x.getId())){
- //如果子集 匹配上了父级 那么把子集放入父级中
- List<Menu> children = x.getChildren();
- if(CollectionUtils.isEmpty(children)){
- children=new ArrayList<>();
- }
- children.add(menu);
- x.setChildren(children);
- }
- }
- }
-
- /**
- * 根据权限获取菜单信息
- * @return
- */
- private Menu getByAuth(String auth){
- QueryWrapper<Menu> queryWrapper=new QueryWrapper();
- queryWrapper.eq("auth",auth);
- Menu x=menuMapper.selectOne(queryWrapper);
- return x;
- }
-
- /**
- * 获取是否有子集
- * @return
- */
- private Long getPIdCount(Integer parentId){
- QueryWrapper<Menu> queryWrapper=new QueryWrapper();
- queryWrapper.eq("parent_id",parentId);
- return menuMapper.selectCount(queryWrapper);
- }
-
-
- /**
- * 获取当前登录人的菜单信息
- * @return
- */
- @Override
- public List<Menu> getMyMenu() {
- //从认证信息上下文中 获取用户权限
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- if(authentication.getPrincipal() instanceof MyUserDetails){
- MyUserDetails myUserDetails =(MyUserDetails) authentication.getPrincipal();
- return myUserDetails.getUser().getMenu();
- }
- return new ArrayList<>();
- }
-
- }

- package com.dmg.sp.service.impl;
-
- import com.dmg.sp.service.UserService;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Bean;
- import org.springframework.security.authentication.AuthenticationProvider;
- import org.springframework.security.authentication.BadCredentialsException;
- import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
- import org.springframework.security.core.Authentication;
- import org.springframework.security.core.AuthenticationException;
- import org.springframework.security.core.userdetails.UserDetails;
- import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
- import org.springframework.security.crypto.password.PasswordEncoder;
- import org.springframework.stereotype.Component;
-
- /**
- *
- * 实现身份验证提供程序
- * @param
- * @return
- * @throws Exception
- */
- @Slf4j
- @Component
- public class MyAuthenticationProvider implements AuthenticationProvider {
-
- @Autowired
- private UserService userService;
-
- @Autowired
- private PasswordEncoder passwordEncoder;
-
-
-
- /**
- * LoginServiceImpl的登录方法点击认证的时候 直接跳转到这里
- * 登陆认证
- * @param
- * @return
- * @throws Exception
- */
- @Override
- public Authentication authenticate(Authentication authentication) throws AuthenticationException {
- //从authentication获取用户名和凭证(密码)信息
- String username=authentication.getName();
- String password=authentication.getCredentials().toString();
- log.info("密码=========================={}",password);
- //查询用户是否存在
- UserDetails userDetails = userService.loadUserByUsername(username);
- //比较和数据库的密码是否一样
- if(passwordEncoder.matches(password,userDetails.getPassword())){
- //返回用户名密码认证令牌
- //因为UsernamePasswordAuthenticationToken的上级父类的父类是Authentication 所以可以直接返回
- return new UsernamePasswordAuthenticationToken(username,password,userDetails.getAuthorities());
- }else {
- throw new BadCredentialsException("用户名或者密码错误了");
- }
- }
-
- @Override
- public boolean supports(Class<?> authentication) {
- //保证认证和返回的对象都是UsernamePasswordAuthenticationToken
- return authentication.equals(UsernamePasswordAuthenticationToken.class);
- }
- }

- package com.dmg.sp.service.impl;
-
- import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
- import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
- import com.dmg.sp.dao.RoleMapper;
- import com.dmg.sp.entity.Role;
- import com.dmg.sp.service.RoleService;
- import com.dmg.sp.vo.RoleAuthVo;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
-
- import java.util.List;
- @Slf4j
- @Service
- public class RoleServiceImpl implements RoleService {
-
- @Autowired
- private RoleMapper roleMapper;
-
- /**
- * 获取所有角色
- * @return
- */
- @Override
- public List<Role> getRoleList() {
- return roleMapper.selectList(null);
- }
-
- /**
- * 添加角色
- * @param role
- */
- @Transactional(rollbackFor = Exception.class)
- @Override
- public void addRole(Role role) {
- //根据角色编码查询是否存在相同的角色
- if(getRoleByCode(role.getRoleCode())!=null){
- throw new RuntimeException("角色编码已存在");
- }
- roleMapper.insert(role);
- }
-
- /**
- * 修改角色
- * @param role
- */
- @Transactional(rollbackFor = Exception.class)
- @Override
- public void editRole(Role role) {
- Role bean=roleMapper.selectById(role.getId());
- if(bean==null){
- throw new RuntimeException("角色不存在");
- }
- Role item=getRoleByCode(role.getRoleCode());
- if(item!=null && !item.getRoleCode().equals(bean.getRoleCode())){
- //如果要修改的角色已存在,但是 不是当前角色的编码 那么抛出异常
- throw new RuntimeException("角色编码已存在");
- }
- roleMapper.updateById(role);
- }
-
- /**
- * 删除角色
- * @param id
- */
- @Transactional(rollbackFor = Exception.class)
- @Override
- public void deleteRole(Integer id) {
- //判断角色是否存在
- Role role=roleMapper.selectById(id);
- if(role==null){
- throw new RuntimeException("角色不存在");
- }
- if(role.getRoleCode().equals("admin")){
- throw new RuntimeException("管理员不能删除");
- }
-
- //删除角色关联的用户
- roleMapper.deleteUser(id);
- //删除角色关联的权限
- roleMapper.deleteAuth(id);
- //删除角色
- roleMapper.deleteById(id);
- }
-
- /**
- * 根据角色id 查看角色详情
- * @param id
- * @return
- */
- @Override
- public Role getRoleById(Integer id) {
- return roleMapper.selectById(id);
- }
-
- /**
- * 查看用户对应的角色
- * @param userId
- * @return
- */
- @Override
- public List<Role> getUserRole(Integer userId) {
- return roleMapper.getUserRole(userId);
- }
-
- /**
- * 为角色分配权限
- * @return
- */
- @Override
- public void setRoleAuth(RoleAuthVo vo) {
- //判断角色是否存在
- if(roleMapper.selectById(vo.getRoleId())==null){
- throw new RuntimeException("角色不存在");
- }
- if(CollectionUtils.isEmpty(vo.getMenuIds())){
- throw new RuntimeException("权限不能为空");
- }
- //先删除旧的角色权限
- roleMapper.deleteAuth(vo.getRoleId());
- //在添加新的角色权限
- roleMapper.addRoleAuth(vo.getRoleId(),vo.getMenuIds());
- }
-
- /**
- * 根据角色编码获取角色信息
- * @param code
- * @return
- */
- private Role getRoleByCode(String code){
- QueryWrapper<Role> queryWrapper=new QueryWrapper();
- queryWrapper.eq("role_code",code);
- Role role=roleMapper.selectOne(queryWrapper);
- return role;
- }
- }

- package com.dmg.sp.service.impl;
-
- import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
- import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
- import com.dmg.sp.dao.UserMapper;
- import com.dmg.sp.entity.Role;
- import com.dmg.sp.entity.User;
- import com.dmg.sp.service.SysUserService;
- import com.dmg.sp.vo.UserRoleVo;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
-
- import java.util.Date;
- import java.util.List;
-
- @Slf4j
- @Service
- public class SysUserServiceImpl implements SysUserService {
-
- @Autowired
- private UserMapper userMapper;
-
-
- /**
- * 获取所有用户
- * @return
- */
- @Override
- public List<User> getUserList() {
- return userMapper.selectList(null);
- }
-
- /**
- * 为用户分配角色
- * @return
- */
- @Transactional(rollbackFor = Exception.class)
- @Override
- public void setUserRole(UserRoleVo vo) {
- //判断用户是否存在
- if(vo.getUserId()==null || userMapper.selectById(vo.getUserId())==null){
- throw new RuntimeException("用户不存在");
- }
- if(CollectionUtils.isEmpty(vo.getRoleIds())){
- throw new RuntimeException("角色不能为空");
- }
- //先删除旧的用户角色
- userMapper.deleteRole(vo.getUserId());
- //在添加新的用户角色
- userMapper.addUserRole(vo.getUserId(),vo.getRoleIds());
- }
-
-
- /**
- * 添加用户
- * @param user
- */
- @Transactional(rollbackFor = Exception.class)
- @Override
- public void addUser(User user) {
- //根据账号获取用户信息
- if(getByAccount(user.getAccount())!=null){
- throw new RuntimeException("该账号已存在");
- }
- //对密码进行加密
- BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
- String encode = bCryptPasswordEncoder.encode(user.getPassword());
- user.setPassword(encode);
- user.setCreateTime(new Date());
- userMapper.insert(user);
- }
-
-
- /**
- * 查看用户对应的角色id
- * @return
- */
- @Override
- public List<Integer> getUserRoleIds(Integer userId) {
- return userMapper.getUserRoleIds(userId);
- }
-
- /**
- * 根据账号获取用户信息
- * @param account
- * @return
- */
- private User getByAccount(String account){
- QueryWrapper<User> queryWrapper=new QueryWrapper();
- queryWrapper.eq("account",account);
- User x=userMapper.selectOne(queryWrapper);
- return x;
- }
- }

- package com.dmg.sp.utils;
-
- import com.auth0.jwt.JWT;
- import com.auth0.jwt.JWTCreator;
- import com.auth0.jwt.algorithms.Algorithm;
- import com.auth0.jwt.interfaces.Claim;
- import com.auth0.jwt.interfaces.DecodedJWT;
-
- import java.util.Calendar;
- import java.util.Map;
-
- public class JWTUtil {
- /**
- * 传入payload信息获取token
- */
- public static String getToken(Map<String, String> map, String secret) {
- JWTCreator.Builder builder = JWT.create();
- //payload
- map.forEach(builder::withClaim);
- Calendar instance = Calendar.getInstance();
- //默认7天过期
- instance.add(Calendar.DATE, 7);
- //指定令牌的过期时间
- builder.withExpiresAt(instance.getTime());
- return builder.sign(Algorithm.HMAC256(secret));
- }
-
- /**
- * 验证token 合法性
- */
- public static DecodedJWT verify(String token, String secret) {
- //如果有任何验证异常,此处都会抛出异常
- return JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
- }
-
- /**
- * 获取token信息方法
- */
- public static Map<String, Claim> getTokenInfo(String token, String secret) {
- return JWT.require(Algorithm.HMAC256(secret)).build().verify(token).getClaims();
- }
- }

- package com.dmg.sp.utils;
-
- import jakarta.servlet.http.HttpServletRequest;
- import jakarta.servlet.http.HttpServletResponse;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.http.HttpStatus;
- import org.springframework.security.authentication.BadCredentialsException;
- import org.springframework.security.core.userdetails.UsernameNotFoundException;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.RestControllerAdvice;
-
- import java.net.BindException;
-
- /**
- * 全局异常处理器
- */
- @Slf4j
- @RestControllerAdvice
- public class MyGlobalExceptionHandler {
-
- @ExceptionHandler(UsernameNotFoundException.class)
- public Result usernameNotFoundException(UsernameNotFoundException e) {
- return Result.error("401",e.getMessage());
- }
-
- @ExceptionHandler(BadCredentialsException.class)
- public Result badCredentialsException(BadCredentialsException e) {
- return Result.error("401",e.getMessage());
- }
-
- @ExceptionHandler(Exception.class)
- public Result exception(Exception e) {
- return Result.error("500",e.getMessage());
- }
- }

- package com.dmg.sp.utils;
-
- import lombok.Data;
-
- /**
- * 返回对象
- * @param <T>
- */
- @Data
- public class Result<T> {
-
- private String code;
-
- private String msg;
-
- private T data;
-
- private static String SUCCESS="200";
-
- private static String ERROR="500";
-
- //禁止外部new对象
- private Result(){
-
- }
-
- public static <T> Result<T> success(String code,String msg,T data){
- Result result=new Result();
- result.setCode(code);
- result.setMsg(msg);
- result.setData(data);
- return result;
- }
-
- public static <T> Result<T> success(String msg,T data){
- Result result=new Result();
- result.setCode(SUCCESS);
- result.setMsg(msg);
- result.setData(data);
- return result;
- }
-
- public static <T> Result<T> success(T data){
- Result result=new Result();
- result.setCode(SUCCESS);
- result.setMsg(null);
- result.setData(data);
- return result;
- }
-
- public static <T> Result<T> success(){
- Result result=new Result();
- result.setCode(SUCCESS);
- result.setMsg(null);
- result.setData(null);
- return result;
- }
-
- public static <T> Result<T> error(String code,String msg){
- Result result=new Result();
- result.setCode(code);
- result.setMsg(msg);
- result.setData(null);
- return result;
- }
-
- public static <T> Result<T> error(String msg){
- Result result=new Result();
- result.setCode(ERROR);
- result.setMsg(msg);
- result.setData(null);
- return result;
- }
-
- public static <T> Result<T> error(){
- Result result=new Result();
- result.setCode(ERROR);
- result.setMsg(null);
- result.setData(null);
- return result;
- }
-
- }

- package com.dmg.sp.vo;
-
- import lombok.Data;
-
- @Data
- public class IdVo {
-
- //用户id
- private Integer userId;
-
- //角色id
- private Integer roleId;
-
- //菜单id
- private Integer menuId;
- }

- package com.dmg.sp.vo;
-
-
- import lombok.Data;
-
- @Data
- public class LoginVo {
-
- //账号
- private String account;
-
- //密码
- private String password;
- }
- package com.dmg.sp.vo;
-
- import lombok.Data;
-
- import java.util.List;
-
- @Data
- public class RoleAuthVo {
-
- //角色id
- private Integer roleId;
-
- //菜单id 集合
- private List<Integer> menuIds;
- }
- package com.dmg.sp.vo;
-
- import lombok.Data;
-
- import java.util.List;
-
- @Data
- public class UserRoleVo {
-
- //用户id
- private Integer userId;
-
- //角色id 集合
- private List<Integer> roleIds;
- }
- package com.dmg.sp;
-
- import org.mybatis.spring.annotation.MapperScan;
- import org.mybatis.spring.annotation.MapperScans;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.context.annotation.ComponentScan;
-
- @MapperScan(basePackages = {"com.dmg.sp.dao"})
- @SpringBootApplication
- public class SpApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(SpApplication.class, args);
- }
-
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。