commit d291d0803c722748773468ecc10ef304307465a9 Author: 冷冷 Date: Fri Feb 1 21:06:59 2019 +0800 :bookmark: v2.0.0. happy new year diff --git a/.editorconfig b/.editorconfig new file mode 100755 index 00000000..afff4db4 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,22 @@ +root = true + +# 对所有文件生效 +[*] +charset = utf-8 +indent_style = space +indent_size = 2 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{java,xml}] +indent_style = tab +indent_size = 4 + +[*.{yml,json}] +indent_style = space +indent_size = 2 + +# 对后缀名为 md 的文件生效 +[*.md] +trim_trailing_whitespace = false diff --git a/.gitignore b/.gitignore new file mode 100755 index 00000000..6915694f --- /dev/null +++ b/.gitignore @@ -0,0 +1,58 @@ +### gradle ### +.gradle +/build/ +!gradle/wrapper/gradle-wrapper.jar + +### STS ### +.settings/ +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +rebel.xml + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ + +### maven ### +target/ +*.war +*.ear +*.zip +*.tar +*.tar.gz + +### logs #### +/logs/ +*.log + +### temp ignore ### +*.cache +*.diff +*.patch +*.tmp +*.java~ +*.properties~ +*.xml~ + +### system ignore ### +.DS_Store +Thumbs.db +Servers +.metadata +upload +gen_code diff --git a/LICENSE b/LICENSE new file mode 100755 index 00000000..f2f81d6d --- /dev/null +++ b/LICENSE @@ -0,0 +1,56 @@ +GNU LESSER GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. + +0. Additional Definitions. +As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License. + +“The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. + +An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. + +A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”. + +The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. + +The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. + +1. Exception to Section 3 of the GNU GPL. +You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. + +2. Conveying Modified Versions. +If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: + +a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or +b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. +3. Object Code Incorporating Material from Library Header Files. +The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: + +a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. +b) Accompany the object code with a copy of the GNU GPL and this license document. +4. Combined Works. +You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: + +a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. +b) Accompany the Combined Work with a copy of the GNU GPL and this license document. +c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. +d) Do one of the following: +0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. +1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. +e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) +5. Combined Libraries. +You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: + +a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. +b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. +6. Revised Versions of the GNU Lesser General Public License. +The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. + +If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. diff --git a/README.md b/README.md new file mode 100755 index 00000000..0104aa76 --- /dev/null +++ b/README.md @@ -0,0 +1,76 @@ +

+ Build Status + Coverage Status + Downloads +

+ +**Pig Microservice Architecture** + +- 基于 Spring Cloud Finchley 、Spring Security OAuth2 的RBAC权限管理系统 +- 基于数据驱动视图的理念封装 Element-ui,即使没有 vue 的使用经验也能快速上手 +- 提供对常见容器化支持 Docker、Kubernetes、Rancher2 支持 +- 提供 lambda 、stream api 、webflux 的生产实践 + + +部署文档 | 在线体验 | 前端解决方案 | 1.0 版本 + + + + +![](http://a.pigx.top/20190201162417.png?imageView2/2/w/650) + +#### 核心依赖 + + +依赖 | 版本 +---|--- +Spring Boot | 2.0.8.RELEASE +Spring Cloud | Finchley.SR2 +Spring Security OAuth2 | 2.3.3 +Mybatis Plus | 3.0.6 +hutool | 4.3.3 +Avue | 1.5.0 + + + +#### 模块说明 +```lua +pig +├── pig-ui -- 前端工程[8080] +├── pig-auth -- 授权服务提供[3000] +└── pig-common -- 系统公共模块 + ├── pig-common-core -- 公共工具类核心包 + ├── pig-common-log -- 日志服务 + └── pig-common-security -- 安全工具类 +├── pig-config -- 配置中心[8888] +├── pig-eureka -- 服务注册与发现[8761] +├── pig-gateway -- Spring Cloud Gateway网关[9999] +└── pig-upms -- 通用用户权限管理模块 + └── pigx-upms-api -- 通用用户权限管理系统公共api模块 + └── pigx-upms-biz -- 通用用户权限管理系统业务处理模块[4000] +└── pigx-visual -- 图形化模块 + ├── pigx-monitor -- Spring Boot Admin监控 [5001] + └── pigx-codegen -- 图形化代码生成[5003] + +``` +#### 提交反馈 + +1. 欢迎提交 issue,请写清楚遇到问题的原因,开发环境,复显步骤。 + +2. 不接受`功能请求`的 issue,功能请求可能会被直接关闭。 + +3. wangiegie@gmail.com +4. 交流群 23754102 + +#### 开源协议 +![](http://a.pigx.top/20190201155120.png) + + +#### 鸣谢 + +avue [@smallwei](https://avue.top) +mica-auto [@dreamlu](https://dreamlu.net) +bladex [@smallc](http://bladex.vip) +mybatis-plus [@青苗](http://mp.baomidou.com) +hutool [@路小磊](https://dreamlu.net) + diff --git a/db/Dockerfile b/db/Dockerfile new file mode 100644 index 00000000..39a787c1 --- /dev/null +++ b/db/Dockerfile @@ -0,0 +1,7 @@ +FROM mysql:5.7 + +MAINTAINER lengleng(wangiegie@gmail.com) + +RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime + +COPY ./doc/db/pig.sql /docker-entrypoint-initdb.d diff --git a/db/pig.sql b/db/pig.sql new file mode 100644 index 00000000..086d5d64 --- /dev/null +++ b/db/pig.sql @@ -0,0 +1,287 @@ +/* + Navicat Premium Data Transfer + + Source Server : localhost + Source Server Type : MySQL + Source Server Version : 50723 + Source Host : localhost + Source Database : pig + + Target Server Type : MySQL + Target Server Version : 50723 + File Encoding : utf-8 + + Date: 02/01/2019 20:51:15 PM +*/ +DROP DATABAS IF EXISTS `pig`; +CREATE DATABASE `pig` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin; + +SET NAMES utf8; +SET FOREIGN_KEY_CHECKS = 0; + +-- ---------------------------- +-- Table structure for `sys_dept` +-- ---------------------------- +DROP TABLE IF EXISTS `sys_dept`; +CREATE TABLE `sys_dept` ( + `dept_id` int(20) NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL COMMENT '部门名称', + `sort` int(11) DEFAULT NULL COMMENT '排序', + `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间', + `del_flag` char(1) DEFAULT '0' COMMENT '是否删除 -1:已删除 0:正常', + `parent_id` int(11) DEFAULT NULL, + PRIMARY KEY (`dept_id`) +) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='部门管理'; + +-- ---------------------------- +-- Records of `sys_dept` +-- ---------------------------- +BEGIN; +INSERT INTO `sys_dept` VALUES ('1', '山东农信', null, '2018-01-22 19:00:23', '2018-09-13 01:46:29', '0', '0'), ('2', '沙县国际', null, '2018-01-22 19:00:38', '2018-09-13 01:46:30', '0', '0'), ('3', '潍坊农信', null, '2018-01-22 19:00:44', '2018-09-13 01:46:31', '0', '1'), ('4', '高新农信', null, '2018-01-22 19:00:52', '2018-10-06 10:41:52', '0', '3'), ('5', '院校农信', null, '2018-01-22 19:00:57', '2018-10-06 10:42:51', '0', '4'), ('6', '潍院农信', null, '2018-01-22 19:01:06', '2019-01-09 10:58:18', '1', '5'), ('7', '山东沙县', null, '2018-01-22 19:01:57', '2018-09-13 01:46:42', '0', '2'), ('8', '潍坊沙县', null, '2018-01-22 19:02:03', '2018-09-13 01:46:43', '0', '7'), ('9', '高新沙县', null, '2018-01-22 19:02:14', '2018-09-13 01:46:44', '1', '8'), ('10', '租户2', null, '2018-11-18 13:27:11', '2018-11-18 13:42:19', '0', '0'), ('11', '院校沙县', null, '2018-12-10 21:19:26', null, '0', '8'); +COMMIT; + +-- ---------------------------- +-- Table structure for `sys_dept_relation` +-- ---------------------------- +DROP TABLE IF EXISTS `sys_dept_relation`; +CREATE TABLE `sys_dept_relation` ( + `ancestor` int(11) NOT NULL COMMENT '祖先节点', + `descendant` int(11) NOT NULL COMMENT '后代节点', + PRIMARY KEY (`ancestor`,`descendant`), + KEY `idx1` (`ancestor`), + KEY `idx2` (`descendant`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC COMMENT='部门关系表'; + +-- ---------------------------- +-- Records of `sys_dept_relation` +-- ---------------------------- +BEGIN; +INSERT INTO `sys_dept_relation` VALUES ('1', '1'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '2'), ('2', '7'), ('2', '8'), ('2', '11'), ('3', '3'), ('3', '4'), ('3', '5'), ('4', '4'), ('4', '5'), ('5', '5'), ('7', '7'), ('7', '8'), ('7', '11'), ('8', '8'), ('8', '11'), ('10', '10'), ('11', '11'); +COMMIT; + +-- ---------------------------- +-- Table structure for `sys_dict` +-- ---------------------------- +DROP TABLE IF EXISTS `sys_dict`; +CREATE TABLE `sys_dict` ( + `id` int(64) NOT NULL AUTO_INCREMENT COMMENT '编号', + `value` varchar(100) NOT NULL COMMENT '数据值', + `label` varchar(100) NOT NULL COMMENT '标签名', + `type` varchar(100) NOT NULL COMMENT '类型', + `description` varchar(100) NOT NULL COMMENT '描述', + `sort` int(10) NOT NULL COMMENT '排序(升序)', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `remarks` varchar(255) DEFAULT NULL COMMENT '备注信息', + `del_flag` char(1) NOT NULL DEFAULT '0' COMMENT '删除标记', + PRIMARY KEY (`id`), + KEY `sys_dict_value` (`value`), + KEY `sys_dict_label` (`label`), + KEY `sys_dict_del_flag` (`del_flag`) +) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='字典表'; + +-- ---------------------------- +-- Records of `sys_dict` +-- ---------------------------- +BEGIN; +INSERT INTO `sys_dict` VALUES ('1', '9', '异常', 'log_type', '日志异常', '1', '2018-07-09 06:16:14', '2018-11-24 07:25:11', '日志异常', '0'), ('2', '0', '正常', 'log_type', '正常', '0', '2018-07-09 06:15:40', '2018-11-24 07:25:14', '正常', '0'), ('3', 'WX', '微信', 'social_type', '微信登录', '0', '2018-08-16 14:01:45', '2018-11-24 07:25:16', '微信登录', '0'), ('4', 'QQ', 'QQ', 'social_type', 'QQ登录', '1', '2018-07-09 06:15:40', '2018-11-24 07:25:18', 'QQ登录', '0'), ('5', '0', '正常', 'log_type', '日志类型', '0', '2018-09-30 02:33:53', '2018-11-24 07:25:20', '日志正常', '0'), ('6', '0', '未提交', 'leave_status', '请假状态', '0', '2018-09-30 02:34:45', '2018-11-24 07:25:23', '请假状态', '0'), ('7', '1', '审批中', 'leave_status', '请假状态', '1', '2018-09-30 02:35:16', '2018-11-24 07:25:25', '请假状态', '0'), ('8', '2', '完成', 'leave_status', '请假状态', '2', '2018-09-30 02:35:58', '2018-11-24 07:25:28', '请假状态', '0'), ('9', '9', '驳回', 'leave_status', '请假状态', '9', '2018-09-30 02:36:31', '2018-11-24 07:25:31', '请假状态', '0'); +COMMIT; + +-- ---------------------------- +-- Table structure for `sys_log` +-- ---------------------------- +DROP TABLE IF EXISTS `sys_log`; +CREATE TABLE `sys_log` ( + `id` bigint(64) NOT NULL AUTO_INCREMENT COMMENT '编号', + `type` char(1) DEFAULT '1' COMMENT '日志类型', + `title` varchar(255) DEFAULT '' COMMENT '日志标题', + `service_id` varchar(32) DEFAULT NULL COMMENT '服务ID', + `create_by` varchar(64) DEFAULT NULL COMMENT '创建者', + `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `remote_addr` varchar(255) DEFAULT NULL COMMENT '操作IP地址', + `user_agent` varchar(1000) DEFAULT NULL COMMENT '用户代理', + `request_uri` varchar(255) DEFAULT NULL COMMENT '请求URI', + `method` varchar(10) DEFAULT NULL COMMENT '操作方式', + `params` text COMMENT '操作提交的数据', + `time` mediumtext COMMENT '执行时间', + `del_flag` char(1) DEFAULT '0' COMMENT '删除标记', + `exception` text COMMENT '异常信息', + PRIMARY KEY (`id`), + KEY `sys_log_create_by` (`create_by`), + KEY `sys_log_request_uri` (`request_uri`), + KEY `sys_log_type` (`type`), + KEY `sys_log_create_date` (`create_time`) +) ENGINE=InnoDB AUTO_INCREMENT=52 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='日志表'; + +-- ---------------------------- +-- Records of `sys_log` +-- ---------------------------- +BEGIN; +INSERT INTO `sys_log` VALUES ('51', '0', '添加角色', 'test', 'admin', '2019-01-24 20:56:43', null, '0:0:0:0:0:0:0:1', 'PostmanRuntime/7.6.0', '/role', 'POST', 'Authorization=%5B%5D', '65', '0', null); +COMMIT; + +-- ---------------------------- +-- Table structure for `sys_menu` +-- ---------------------------- +DROP TABLE IF EXISTS `sys_menu`; +CREATE TABLE `sys_menu` ( + `menu_id` int(11) NOT NULL COMMENT '菜单ID', + `name` varchar(32) NOT NULL COMMENT '菜单名称', + `permission` varchar(32) DEFAULT NULL COMMENT '菜单权限标识', + `path` varchar(128) DEFAULT NULL COMMENT '前端URL', + `parent_id` int(11) DEFAULT NULL COMMENT '父菜单ID', + `icon` varchar(32) DEFAULT NULL COMMENT '图标', + `component` varchar(64) DEFAULT NULL COMMENT 'VUE页面', + `sort` int(11) DEFAULT '1' COMMENT '排序值', + `keep_alive` char(1) DEFAULT '0' COMMENT '0-开启,1- 关闭', + `type` char(1) DEFAULT NULL COMMENT '菜单类型 (0菜单 1按钮)', + `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `del_flag` char(1) DEFAULT '0' COMMENT '逻辑删除标记(0--正常 1--删除)', + PRIMARY KEY (`menu_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='菜单权限表'; + +-- ---------------------------- +-- Records of `sys_menu` +-- ---------------------------- +BEGIN; +INSERT INTO `sys_menu` VALUES ('1000', '权限管理', null, '/upms', '-1', 'icon-quanxianguanli', 'Layout', '0', '0', '0', '2018-09-28 08:29:53', '2018-09-28 08:53:01', '0'), ('1100', '用户管理', null, 'user', '1000', 'icon-yonghuguanli', 'views/admin/user/index', '1', '0', '0', '2017-11-02 22:24:37', '2018-09-28 09:00:41', '0'), ('1101', '用户新增', 'sys_user_add', null, '1100', null, null, null, '0', '1', '2017-11-08 09:52:09', '2018-09-28 09:06:34', '0'), ('1102', '用户修改', 'sys_user_edit', null, '1100', null, null, null, '0', '1', '2017-11-08 09:52:48', '2018-09-28 09:06:37', '0'), ('1103', '用户删除', 'sys_user_del', null, '1100', null, null, null, '0', '1', '2017-11-08 09:54:01', '2018-09-28 09:06:42', '0'), ('1200', '菜单管理', null, 'menu', '1000', 'icon-caidanguanli', 'views/admin/menu/index', '2', '0', '0', '2017-11-08 09:57:27', '2018-09-28 09:00:45', '0'), ('1201', '菜单新增', 'sys_menu_add', null, '1200', null, null, null, '0', '1', '2017-11-08 10:15:53', '2018-09-28 09:07:16', '0'), ('1202', '菜单修改', 'sys_menu_edit', null, '1200', null, null, null, '0', '1', '2017-11-08 10:16:23', '2018-09-28 09:07:18', '0'), ('1203', '菜单删除', 'sys_menu_del', null, '1200', null, null, null, '0', '1', '2017-11-08 10:16:43', '2018-09-28 09:07:22', '0'), ('1300', '角色管理', null, 'role', '1000', 'icon-jiaoseguanli', 'views/admin/role/index', '3', '0', '0', '2017-11-08 10:13:37', '2018-09-28 09:00:48', '0'), ('1301', '角色新增', 'sys_role_add', null, '1300', null, null, null, '0', '1', '2017-11-08 10:14:18', '2018-09-28 09:07:46', '0'), ('1302', '角色修改', 'sys_role_edit', null, '1300', null, null, null, '0', '1', '2017-11-08 10:14:41', '2018-09-28 09:07:49', '0'), ('1303', '角色删除', 'sys_role_del', null, '1300', null, null, null, '0', '1', '2017-11-08 10:14:59', '2018-09-28 09:07:53', '0'), ('1304', '分配权限', 'sys_role_perm', null, '1300', null, null, null, '0', '1', '2018-04-20 07:22:55', '2018-09-28 09:13:23', '0'), ('1400', '部门管理', null, 'dept', '1000', 'icon-web-icon-', 'views/admin/dept/index', '4', '0', '0', '2018-01-20 13:17:19', '2018-12-09 16:35:12', '0'), ('1401', '部门新增', 'sys_dept_add', null, '1400', null, null, null, '0', '1', '2018-01-20 14:56:16', '2018-09-28 09:08:13', '0'), ('1402', '部门修改', 'sys_dept_edit', null, '1400', null, null, null, '0', '1', '2018-01-20 14:56:59', '2018-09-28 09:08:16', '0'), ('1403', '部门删除', 'sys_dept_del', null, '1400', null, null, null, '0', '1', '2018-01-20 14:57:28', '2018-09-28 09:08:18', '0'), ('2000', '系统管理', null, '/admin', '-1', 'icon-xitongguanli', 'Layout', '1', '0', '0', '2017-11-07 20:56:00', '2018-09-28 08:53:18', '0'), ('2100', '日志管理', null, 'log', '2000', 'icon-rizhiguanli', 'views/admin/log/index', '5', '0', '0', '2017-11-20 14:06:22', '2018-09-28 09:01:52', '0'), ('2101', '日志删除', 'sys_log_del', null, '2100', null, null, null, '0', '1', '2017-11-20 20:37:37', '2018-09-28 09:08:44', '0'), ('2200', '字典管理', null, 'dict', '2000', 'icon-navicon-zdgl', 'views/admin/dict/index', '6', '0', '0', '2017-11-29 11:30:52', '2018-09-28 09:01:47', '0'), ('2201', '字典删除', 'sys_dict_del', null, '2200', null, null, null, '0', '1', '2017-11-29 11:30:11', '2018-09-28 09:09:10', '0'), ('2202', '字典新增', 'sys_dict_add', null, '2200', null, null, null, '0', '1', '2018-05-11 22:34:55', '2018-09-28 09:09:12', '0'), ('2203', '字典修改', 'sys_dict_edit', null, '2200', null, null, null, '0', '1', '2018-05-11 22:36:03', '2018-09-28 09:09:16', '0'), ('2300', '代码生成', '', 'gen', '2000', 'icon-weibiaoti46', 'views/gen/index', '8', '0', '0', '2018-01-20 13:17:19', '2018-11-24 05:21:01', '0'), ('2400', '终端管理', '', 'client', '2000', 'icon-shouji', 'views/admin/client/index', '9', '0', '0', '2018-01-20 13:17:19', '2018-09-28 09:01:43', '0'), ('2401', '客户端新增', 'sys_client_add', null, '2400', '1', null, null, '0', '1', '2018-05-15 21:35:18', '2018-09-28 09:10:25', '0'), ('2402', '客户端修改', 'sys_client_edit', null, '2400', null, null, null, '0', '1', '2018-05-15 21:37:06', '2018-09-28 09:10:27', '0'), ('2403', '客户端删除', 'sys_client_del', null, '2400', null, null, null, '0', '1', '2018-05-15 21:39:16', '2018-09-28 09:10:30', '0'), ('2500', '服务监控', null, 'http://139.224.200.249:15001', '2000', 'icon-server', null, '10', '0', '0', '2018-06-26 10:50:32', '2019-02-01 20:41:30', '0'), ('2600', '令牌管理', null, 'token', '2000', 'icon-denglvlingpai', 'views/admin/token/index', '11', '0', '0', '2018-09-04 05:58:41', '2018-09-28 09:01:38', '0'), ('2601', '令牌删除', 'sys_token_del', null, '2600', null, null, '1', '0', '1', '2018-09-04 05:59:50', '2018-09-28 09:11:24', '0'), ('5000', '一级菜单', null, '/crud', '-1', 'icon-caidanguanli', '', '4', '0', '0', '2018-08-28 01:50:22', '2018-09-28 08:58:20', '0'), ('5001', '一级菜单', null, 'index', '5000', 'icon-caidanguanli', 'views/crud/index', '1', '0', '0', '2018-08-28 01:50:48', '2018-11-21 17:48:19', '1'), ('5002', '二级菜单', null, 'crud', '5001', 'icon-caidanguanli', 'views/crud/index', '1', '0', '0', '2018-08-28 01:51:23', '2018-11-21 17:47:40', '1'), ('5003', '二级菜单', null, '', '5000', 'icon-caidanguanli', '', '1', '0', '0', '2018-11-21 17:49:18', '2018-11-21 17:53:25', '0'), ('5004', '二级菜单', null, 'index', '5003', 'icon-caidanguanli', 'views/crud/index', '1', '0', '0', '2018-11-21 17:53:51', '2018-12-20 14:26:53', '1'), ('6000', '系统官网', null, 'https://pig4cloud.com#', '-1', 'icon-guanwang', '', '5', '0', '0', '2018-09-27 02:26:36', '2018-11-17 16:18:50', '1'), ('9999', '系统官网', null, 'https://pig4cloud.com', '-1', 'icon-guanwangfangwen', null, '9', '0', '0', '2019-01-17 17:05:19', '2019-01-17 17:29:06', '0'); +COMMIT; + +-- ---------------------------- +-- Table structure for `sys_oauth_client_details` +-- ---------------------------- +DROP TABLE IF EXISTS `sys_oauth_client_details`; +CREATE TABLE `sys_oauth_client_details` ( + `client_id` varchar(32) NOT NULL, + `resource_ids` varchar(256) DEFAULT NULL, + `client_secret` varchar(256) DEFAULT NULL, + `scope` varchar(256) DEFAULT NULL, + `authorized_grant_types` varchar(256) DEFAULT NULL, + `web_server_redirect_uri` varchar(256) DEFAULT NULL, + `authorities` varchar(256) DEFAULT NULL, + `access_token_validity` int(11) DEFAULT NULL, + `refresh_token_validity` int(11) DEFAULT NULL, + `additional_information` varchar(4096) DEFAULT NULL, + `autoapprove` varchar(256) DEFAULT NULL, + PRIMARY KEY (`client_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='终端信息表'; + +-- ---------------------------- +-- Records of `sys_oauth_client_details` +-- ---------------------------- +BEGIN; +INSERT INTO `sys_oauth_client_details` VALUES ('app', null, 'app', 'server', 'password,refresh_token', null, null, null, null, null, 'true'), ('daemon', null, 'daemon', 'server', 'password,refresh_token', null, null, null, null, null, 'true'), ('gen', null, 'gen', 'server', 'password,refresh_token', null, null, null, null, null, 'true'), ('pig', null, 'pig', 'server', 'password,refresh_token,authorization_code,client_credentials', 'http://localhost:4040/sso1/login,http://localhost:4041/sso1/login', null, null, null, null, 'true'), ('test', null, 'test', 'server', 'password,refresh_token', null, null, null, null, null, 'true'); +COMMIT; + +-- ---------------------------- +-- Table structure for `sys_role` +-- ---------------------------- +DROP TABLE IF EXISTS `sys_role`; +CREATE TABLE `sys_role` ( + `role_id` int(11) NOT NULL AUTO_INCREMENT, + `role_name` varchar(64) COLLATE utf8mb4_bin NOT NULL, + `role_code` varchar(64) COLLATE utf8mb4_bin NOT NULL, + `role_desc` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, + `ds_type` char(1) COLLATE utf8mb4_bin NOT NULL DEFAULT '2' COMMENT '数据权限类型', + `ds_scope` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '数据权限范围', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, + `del_flag` char(1) COLLATE utf8mb4_bin DEFAULT '0' COMMENT '删除标识(0-正常,1-删除)', + PRIMARY KEY (`role_id`), + UNIQUE KEY `role_idx1_role_code` (`role_code`) +) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin ROW_FORMAT=DYNAMIC COMMENT='系统角色表'; + +-- ---------------------------- +-- Records of `sys_role` +-- ---------------------------- +BEGIN; +INSERT INTO `sys_role` VALUES ('1', '管理员', 'ROLE_ADMIN', '管理员', '2', '2', '2017-10-29 15:45:51', '2018-12-26 14:09:11', '0'), ('2', 'ROLE_CQQ', 'ROLE_CQQ', 'ROLE_CQQ', '2', null, '2018-11-11 19:42:26', '2018-12-26 14:09:07', '0'); +COMMIT; + +-- ---------------------------- +-- Table structure for `sys_role_dept` +-- ---------------------------- +DROP TABLE IF EXISTS `sys_role_dept`; +CREATE TABLE `sys_role_dept` ( + `id` int(20) NOT NULL AUTO_INCREMENT, + `role_id` int(20) DEFAULT NULL COMMENT '角色ID', + `dept_id` int(20) DEFAULT NULL COMMENT '部门ID', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='角色与部门对应关系'; + +-- ---------------------------- +-- Records of `sys_role_dept` +-- ---------------------------- +BEGIN; +INSERT INTO `sys_role_dept` VALUES ('1', '1', '8'); +COMMIT; + +-- ---------------------------- +-- Table structure for `sys_role_menu` +-- ---------------------------- +DROP TABLE IF EXISTS `sys_role_menu`; +CREATE TABLE `sys_role_menu` ( + `role_id` int(11) NOT NULL COMMENT '角色ID', + `menu_id` int(11) NOT NULL COMMENT '菜单ID', + PRIMARY KEY (`role_id`,`menu_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='角色菜单表'; + +-- ---------------------------- +-- Records of `sys_role_menu` +-- ---------------------------- +BEGIN; +INSERT INTO `sys_role_menu` VALUES ('1', '1000'), ('1', '1100'), ('1', '1101'), ('1', '1102'), ('1', '1103'), ('1', '1200'), ('1', '1201'), ('1', '1202'), ('1', '1203'), ('1', '1300'), ('1', '1301'), ('1', '1302'), ('1', '1303'), ('1', '1304'), ('1', '1400'), ('1', '1401'), ('1', '1402'), ('1', '1403'), ('1', '2000'), ('1', '2100'), ('1', '2101'), ('1', '2200'), ('1', '2201'), ('1', '2202'), ('1', '2203'), ('1', '2300'), ('1', '2400'), ('1', '2401'), ('1', '2402'), ('1', '2403'), ('1', '2500'), ('1', '2600'), ('1', '2601'), ('1', '9999'), ('2', '1000'), ('2', '1100'), ('2', '1101'), ('2', '1102'), ('2', '1103'), ('2', '1200'), ('2', '1201'), ('2', '1202'), ('2', '1203'), ('2', '1300'), ('2', '1301'), ('2', '1302'), ('2', '1303'), ('2', '1304'), ('2', '1400'), ('2', '1401'), ('2', '1402'), ('2', '1403'); +COMMIT; + +-- ---------------------------- +-- Table structure for `sys_user` +-- ---------------------------- +DROP TABLE IF EXISTS `sys_user`; +CREATE TABLE `sys_user` ( + `user_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID', + `username` varchar(64) COLLATE utf8mb4_bin NOT NULL COMMENT '用户名', + `password` varchar(255) COLLATE utf8mb4_bin NOT NULL, + `salt` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '随机盐', + `phone` varchar(20) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '简介', + `avatar` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '头像', + `dept_id` int(11) DEFAULT NULL COMMENT '部门ID', + `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间', + `lock_flag` char(1) COLLATE utf8mb4_bin DEFAULT '0' COMMENT '0-正常,9-锁定', + `del_flag` char(1) COLLATE utf8mb4_bin DEFAULT '0' COMMENT '0-正常,1-删除', + `wx_openid` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '微信openid', + `qq_openid` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'QQ openid', + PRIMARY KEY (`user_id`), + KEY `user_wx_openid` (`wx_openid`), + KEY `user_qq_openid` (`qq_openid`), + KEY `user_idx1_username` (`username`) +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin ROW_FORMAT=DYNAMIC COMMENT='用户表'; + +-- ---------------------------- +-- Records of `sys_user` +-- ---------------------------- +BEGIN; +INSERT INTO `sys_user` VALUES ('1', 'admin', '$2a$10$RpFJjxYiXdEsAGnWp/8fsOetMuOON96Ntk/Ym2M/RKRyU0GZseaDC', null, '17034642999', '', '1', '2018-04-20 07:15:18', '2019-01-31 14:29:07', '0', '0', 'o_0FT0uyg_H1vVy2H0JpSwlVGhWQ', null); +COMMIT; + +-- ---------------------------- +-- Table structure for `sys_user_role` +-- ---------------------------- +DROP TABLE IF EXISTS `sys_user_role`; +CREATE TABLE `sys_user_role` ( + `user_id` int(11) NOT NULL COMMENT '用户ID', + `role_id` int(11) NOT NULL COMMENT '角色ID', + PRIMARY KEY (`user_id`,`role_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='用户角色表'; + +-- ---------------------------- +-- Records of `sys_user_role` +-- ---------------------------- +BEGIN; +INSERT INTO `sys_user_role` VALUES ('1', '1'), ('2', '2'); +COMMIT; + +SET FOREIGN_KEY_CHECKS = 1; diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100755 index 00000000..217630b4 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,90 @@ +version: '2' +services: + pig-mysql: + build: + context: ./ + dockerfile: ./doc/db/Dockerfile + environment: + MYSQL_ROOT_PASSWORD: root + restart: always + container_name: pig-mysql + image: pig-mysql + ports: + - 3306:3306 + + pig-redis: + image: redis:5.0 + ports: + - 6379:6379 + restart: always + container_name: pig-redis + hostname: pig-redis + + pig-eureka: + build: + context: ./ + dockerfile: ./pig-eureka/Dockerfile + restart: always + ports: + - 8761:8761 + container_name: pig-eureka + hostname: pig-eureka + image: pig-eureka + + pig-config: + build: + context: ./ + dockerfile: ./pig-config/Dockerfile + restart: always + container_name: pig-config + hostname: pig-config + image: pig-config + + pig-gateway: + build: + context: ./ + dockerfile: ./pig-gateway/Dockerfile + restart: always + ports: + - 9999:9999 + container_name: pig-gateway + hostname: pig-gateway + image: pig-gateway + + pig-auth: + build: + context: ./ + dockerfile: ./pig-auth/Dockerfile + restart: always + container_name: pig-auth + hostname: pig-auth + image: pig-auth + + pig-upms: + build: + context: ./ + dockerfile: ./pig-upms/pig-upms-biz/Dockerfile + restart: always + container_name: pig-upms + hostname: pig-upms + image: pig-upms + + pig-monitor: + build: + context: ./ + dockerfile: ./pig-visual/pig-monitor/Dockerfile + restart: always + ports: + - 5001:5001 + container_name: pig-monitor + hostname: pig-monitor + image: pig-monitor + + pig-codegen: + build: + context: ./ + dockerfile: ./pig-visual/pig-codegen/Dockerfile + restart: always + container_name: pig-codegen + hostname: pig-codegen + image: pig-codegen diff --git a/pig-auth/Dockerfile b/pig-auth/Dockerfile new file mode 100755 index 00000000..e67a00e3 --- /dev/null +++ b/pig-auth/Dockerfile @@ -0,0 +1,15 @@ +FROM anapsix/alpine-java:8_server-jre_unlimited + +MAINTAINER wangiegie@gmail.com + +RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime + +RUN mkdir -p /pig-auth + +WORKDIR /pig-auth + +EXPOSE 3000 + +ADD ./pig-auth/target/pig-auth.jar ./ + +CMD java -Djava.security.egd=file:/dev/./urandom -jar pig-auth.jar diff --git a/pig-auth/pom.xml b/pig-auth/pom.xml new file mode 100755 index 00000000..4ed3448c --- /dev/null +++ b/pig-auth/pom.xml @@ -0,0 +1,109 @@ + + + + + 4.0.0 + + com.pig4cloud + pig + ${pig.version} + + + pig-auth + jar + + pig 认证授权中心,基于 spring security oAuth2 + + + + + org.springframework.cloud + spring-cloud-starter-config + + + + com.pig4cloud + pig-upms-api + ${pig.version} + + + + com.pig4cloud + pig-common-security + ${pig.version} + + + + org.springframework.boot + spring-boot-starter-jdbc + + + + org.springframework.cloud + spring-cloud-starter-security + + + + spring-security-oauth2 + org.springframework.security.oauth + + + + + org.springframework.security.oauth + spring-security-oauth2 + ${security.oauth.version} + + + + mysql + mysql-connector-java + + + + org.springframework.boot + spring-boot-starter-web + + + + spring-boot-starter-tomcat + org.springframework.boot + + + + + + org.springframework.boot + spring-boot-starter-undertow + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.spotify + docker-maven-plugin + + + + + diff --git a/pig-auth/src/main/java/com/pig4cloud/pig/auth/PigAuthApplication.java b/pig-auth/src/main/java/com/pig4cloud/pig/auth/PigAuthApplication.java new file mode 100755 index 00000000..1dbc24f3 --- /dev/null +++ b/pig-auth/src/main/java/com/pig4cloud/pig/auth/PigAuthApplication.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.auth; + + +import com.pig4cloud.pig.common.security.annotation.EnablePigFeignClients; +import org.springframework.boot.SpringApplication; +import org.springframework.cloud.client.SpringCloudApplication; + +/** + * @author lengleng + * @date 2018年06月21日 + * 认证授权中心 + */ +@SpringCloudApplication +@EnablePigFeignClients +public class PigAuthApplication { + + public static void main(String[] args) { + SpringApplication.run(PigAuthApplication.class, args); + } +} diff --git a/pig-auth/src/main/java/com/pig4cloud/pig/auth/config/AuthorizationServerConfig.java b/pig-auth/src/main/java/com/pig4cloud/pig/auth/config/AuthorizationServerConfig.java new file mode 100755 index 00000000..df65a7f2 --- /dev/null +++ b/pig-auth/src/main/java/com/pig4cloud/pig/auth/config/AuthorizationServerConfig.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.auth.config; + +import com.pig4cloud.pig.common.core.constant.SecurityConstants; +import com.pig4cloud.pig.common.security.component.PigWebResponseExceptionTranslator; +import com.pig4cloud.pig.common.security.service.PigClientDetailsService; +import lombok.AllArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; +import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; +import org.springframework.security.oauth2.provider.token.TokenEnhancer; +import org.springframework.security.oauth2.provider.token.TokenStore; +import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore; + +import javax.sql.DataSource; +import java.util.HashMap; +import java.util.Map; + +/** + * @author lengleng + * @date 2019/2/1 + * 认证服务器配置 + */ +@Configuration +@AllArgsConstructor +@EnableAuthorizationServer +public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { + private final DataSource dataSource; + private final org.springframework.security.core.userdetails.UserDetailsService UserDetailsService; + private final AuthenticationManager authenticationManager; + private final RedisConnectionFactory redisConnectionFactory; + + @Override + public void configure(ClientDetailsServiceConfigurer clients) throws Exception { + PigClientDetailsService clientDetailsService = new PigClientDetailsService(dataSource); + clientDetailsService.setSelectClientDetailsSql(SecurityConstants.DEFAULT_SELECT_STATEMENT); + clientDetailsService.setFindClientDetailsSql(SecurityConstants.DEFAULT_FIND_STATEMENT); + clients.withClientDetails(clientDetailsService); + } + + @Override + public void configure(AuthorizationServerSecurityConfigurer oauthServer) { + oauthServer + .allowFormAuthenticationForClients() + .checkTokenAccess("permitAll()"); + } + + @Override + public void configure(AuthorizationServerEndpointsConfigurer endpoints) { + endpoints + .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST) + .tokenStore(tokenStore()) + .tokenEnhancer(tokenEnhancer()) + .userDetailsService(UserDetailsService) + .authenticationManager(authenticationManager) + .reuseRefreshTokens(false) + .exceptionTranslator(new PigWebResponseExceptionTranslator()); + } + + + @Bean + public TokenStore tokenStore() { + RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory); + tokenStore.setPrefix(SecurityConstants.PROJECT_PREFIX + SecurityConstants.OAUTH_PREFIX); + return tokenStore; + } + + @Bean + public TokenEnhancer tokenEnhancer() { + return (accessToken, authentication) -> { + final Map additionalInfo = new HashMap<>(1); + additionalInfo.put("license", SecurityConstants.PROJECT_LICENSE); + ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo); + return accessToken; + }; + } +} diff --git a/pig-auth/src/main/java/com/pig4cloud/pig/auth/config/WebSecurityConfigurer.java b/pig-auth/src/main/java/com/pig4cloud/pig/auth/config/WebSecurityConfigurer.java new file mode 100755 index 00000000..22e3046f --- /dev/null +++ b/pig-auth/src/main/java/com/pig4cloud/pig/auth/config/WebSecurityConfigurer.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.auth.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.pig4cloud.pig.common.security.handler.MobileLoginSuccessHandler; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Lazy; +import org.springframework.context.annotation.Primary; +import org.springframework.core.annotation.Order; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.factory.PasswordEncoderFactories; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.oauth2.provider.ClientDetailsService; +import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; + +/** + * @author lengleng + * @date 2019/2/1 + * 认证相关配置 + */ +@Primary +@Order(90) +@Configuration +public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter { + @Autowired + private ObjectMapper objectMapper; + @Autowired + private ClientDetailsService clientDetailsService; + @Lazy + @Autowired + private AuthorizationServerTokenServices defaultAuthorizationServerTokenServices; + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .antMatchers( + "/actuator/**", + "/oauth/removeToken", + "/oauth/delToken/*", + "/oauth/listToken", + "/mobile/**").permitAll() + .anyRequest().authenticated() + .and().csrf().disable(); + } + + @Bean + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @Bean + public AuthenticationSuccessHandler mobileLoginSuccessHandler() { + return MobileLoginSuccessHandler.builder() + .objectMapper(objectMapper) + .clientDetailsService(clientDetailsService) + .passwordEncoder(passwordEncoder()) + .defaultAuthorizationServerTokenServices(defaultAuthorizationServerTokenServices).build(); + } + + + /** + * https://spring.io/blog/2017/11/01/spring-security-5-0-0-rc1-released#password-storage-updated + * Encoded password does not look like BCrypt + * + * @return PasswordEncoder + */ + @Bean + public PasswordEncoder passwordEncoder() { + return PasswordEncoderFactories.createDelegatingPasswordEncoder(); + } + +} diff --git a/pig-auth/src/main/java/com/pig4cloud/pig/auth/endpoint/PigTokenEndpoint.java b/pig-auth/src/main/java/com/pig4cloud/pig/auth/endpoint/PigTokenEndpoint.java new file mode 100755 index 00000000..3989e7ab --- /dev/null +++ b/pig-auth/src/main/java/com/pig4cloud/pig/auth/endpoint/PigTokenEndpoint.java @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.auth.endpoint; + +import cn.hutool.core.map.MapUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.pig4cloud.pig.common.core.constant.SecurityConstants; +import com.pig4cloud.pig.common.core.util.R; +import com.pig4cloud.pig.common.security.service.PigUser; +import lombok.AllArgsConstructor; +import org.springframework.data.redis.core.ConvertingCursor; +import org.springframework.data.redis.core.Cursor; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ScanOptions; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.http.HttpHeaders; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.common.OAuth2AccessToken; +import org.springframework.security.oauth2.provider.OAuth2Authentication; +import org.springframework.security.oauth2.provider.token.TokenStore; +import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author lengleng + * @date 2019/2/1 + * 删除token端点 + */ +@RestController +@AllArgsConstructor +@RequestMapping("/oauth") +public class PigTokenEndpoint { + private static final String PROJECT_OAUTH_ACCESS = SecurityConstants.PROJECT_PREFIX + SecurityConstants.OAUTH_PREFIX + "access:"; + private static final String CURRENT = "current"; + private static final String SIZE = "size"; + private final TokenStore tokenStore; + private final RedisTemplate redisTemplate; + + /** + * 退出token + * + * @param authHeader Authorization + */ + @GetMapping("/removeToken") + public R logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) { + if (StringUtils.hasText(authHeader)) { + String tokenValue = authHeader.replace("Bearer", "").trim(); + OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue); + if (accessToken == null || StrUtil.isBlank(accessToken.getValue())) { + return new R<>(false, "退出失败,token 为空"); + } + tokenStore.removeAccessToken(accessToken); + } + + return new R<>(Boolean.TRUE); + } + + /** + * 令牌管理调用 + * + * @param token token + * @param from 内部调用标志 + */ + @DeleteMapping("/delToken/{token}") + public R delToken(@PathVariable("token") String token, @RequestHeader(required = false) String from) { + if (StrUtil.isBlank(from)) { + return null; + } + return new R<>(redisTemplate.delete(PROJECT_OAUTH_ACCESS + token)); + } + + + /** + * 查询token + * + * @param params 分页参数 + * @param from 标志 + */ + @PostMapping("/listToken") + public R tokenList(@RequestBody Map params, @RequestHeader(required = false) String from) { + if (StrUtil.isBlank(from)) { + return null; + } + + List> list = new ArrayList<>(); + if (StringUtils.isEmpty(MapUtil.getInt(params, CURRENT)) || StringUtils.isEmpty(MapUtil.getInt(params, CURRENT))) { + params.put(CURRENT, 1); + params.put(SIZE, 20); + } + //根据分页参数获取对应数据 + List pages = findKeysForPage(PROJECT_OAUTH_ACCESS + "*", MapUtil.getInt(params, CURRENT), MapUtil.getInt(params, SIZE)); + + for (String page : pages) { + String accessToken = StrUtil.subAfter(page, PROJECT_OAUTH_ACCESS, true); + OAuth2AccessToken token = tokenStore.readAccessToken(accessToken); + Map map = new HashMap<>(8); + + + map.put("token_type", token.getTokenType()); + map.put("access_token", token.getValue()); + map.put("expires_in", token.getExpiresIn() + ""); + + + OAuth2Authentication oAuth2Auth = tokenStore.readAuthentication(token); + Authentication authentication = oAuth2Auth.getUserAuthentication(); + + map.put("client_id", oAuth2Auth.getOAuth2Request().getClientId()); + map.put("grant_type", oAuth2Auth.getOAuth2Request().getGrantType()); + + if (authentication instanceof UsernamePasswordAuthenticationToken) { + UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication; + + if (authenticationToken.getPrincipal() instanceof PigUser) { + PigUser user = (PigUser) authenticationToken.getPrincipal(); + map.put("user_id", user.getId() + ""); + map.put("username", user.getUsername() + ""); + } + } else if (authentication instanceof PreAuthenticatedAuthenticationToken) { + //刷新token方式 + PreAuthenticatedAuthenticationToken authenticationToken = (PreAuthenticatedAuthenticationToken) authentication; + if (authenticationToken.getPrincipal() instanceof PigUser) { + PigUser user = (PigUser) authenticationToken.getPrincipal(); + map.put("user_id", user.getId() + ""); + map.put("username", user.getUsername() + ""); + } + } + list.add(map); + } + + Page result = new Page(MapUtil.getInt(params, CURRENT), MapUtil.getInt(params, SIZE)); + result.setRecords(list); + result.setTotal(Long.valueOf(redisTemplate.keys(PROJECT_OAUTH_ACCESS + "*").size())); + return new R(result); + + } + + private List findKeysForPage(String patternKey, int pageNum, int pageSize) { + ScanOptions options = ScanOptions.scanOptions().match(patternKey).build(); + RedisSerializer redisSerializer = (RedisSerializer) redisTemplate.getKeySerializer(); + Cursor cursor = (Cursor) redisTemplate.executeWithStickyConnection(redisConnection -> new ConvertingCursor<>(redisConnection.scan(options), redisSerializer::deserialize)); + List result = new ArrayList<>(); + int tmpIndex = 0; + int startIndex = (pageNum - 1) * pageSize; + int end = pageNum * pageSize; + + assert cursor != null; + while (cursor.hasNext()) { + if (tmpIndex >= startIndex && tmpIndex < end) { + result.add(cursor.next().toString()); + tmpIndex++; + continue; + } + if (tmpIndex >= end) { + break; + } + tmpIndex++; + cursor.next(); + } + return result; + } +} diff --git a/pig-auth/src/main/java/com/pig4cloud/pig/auth/handler/PigAuthenticationFailureEvenHandler.java b/pig-auth/src/main/java/com/pig4cloud/pig/auth/handler/PigAuthenticationFailureEvenHandler.java new file mode 100755 index 00000000..ddea22e7 --- /dev/null +++ b/pig-auth/src/main/java/com/pig4cloud/pig/auth/handler/PigAuthenticationFailureEvenHandler.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.auth.handler; + +import com.pig4cloud.pig.common.security.handler.AuthenticationFailureEvenHandler; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.stereotype.Component; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@Slf4j +@Component +public class PigAuthenticationFailureEvenHandler extends AuthenticationFailureEvenHandler { + + /** + * 处理登录失败方法 + *

+ * + * @param authenticationException 登录的authentication 对象 + * @param authentication 登录的authenticationException 对象 + */ + @Override + public void handle(AuthenticationException authenticationException, Authentication authentication) { + log.info("用户:{} 登录失败,异常:{}", authentication.getPrincipal(), authenticationException.getLocalizedMessage()); + } +} diff --git a/pig-auth/src/main/java/com/pig4cloud/pig/auth/handler/PigAuthenticationSuccessEventHandler.java b/pig-auth/src/main/java/com/pig4cloud/pig/auth/handler/PigAuthenticationSuccessEventHandler.java new file mode 100755 index 00000000..65771954 --- /dev/null +++ b/pig-auth/src/main/java/com/pig4cloud/pig/auth/handler/PigAuthenticationSuccessEventHandler.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.auth.handler; + +import com.pig4cloud.pig.common.security.handler.AuthenticationSuccessEventHandler; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Component; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@Slf4j +@Component +public class PigAuthenticationSuccessEventHandler extends AuthenticationSuccessEventHandler { + + /** + * 处理登录成功方法 + *

+ * 获取到登录的authentication 对象 + * + * @param authentication 登录对象 + */ + @Override + public void handle(Authentication authentication) { + log.info("用户:{} 登录成功", authentication.getPrincipal()); + } +} diff --git a/pig-auth/src/main/resources/bootstrap.yml b/pig-auth/src/main/resources/bootstrap.yml new file mode 100755 index 00000000..0f7a7cd9 --- /dev/null +++ b/pig-auth/src/main/resources/bootstrap.yml @@ -0,0 +1,23 @@ +server: + port: 3000 + +spring: + application: + name: pig-auth + # 配置中心 + cloud: + config: + fail-fast: true + name: ${spring.application.name} + profile: dev + discovery: + enabled: true + service-id: pig-config + +# 注册中心配置 +eureka: + instance: + prefer-ip-address: true + client: + service-url: + defaultZone: http://pig:pig@pig-eureka:8761/eureka/ diff --git a/pig-common/pig-common-core/pom.xml b/pig-common/pig-common-core/pom.xml new file mode 100755 index 00000000..c82245d4 --- /dev/null +++ b/pig-common/pig-common-core/pom.xml @@ -0,0 +1,84 @@ + + + + + 4.0.0 + + com.pig4cloud + pig-common + ${pig.version} + + + pig-common-core + jar + + pig 公共工具类核心包 + + + + + + cn.hutool + hutool-all + ${hutool.version} + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + javax.servlet + javax.servlet-api + + + + com.baomidou + mybatis-plus-extension + ${mybatis-plus.version} + + + + io.github.openfeign + feign-okhttp + + + org.springframework.cloud + spring-cloud-starter-openfeign + + + + org.springframework.boot + spring-boot-starter-validation + + + + com.fasterxml.jackson.module + jackson-module-parameter-names + + + com.fasterxml.jackson.datatype + jackson-datatype-jdk8 + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/FilterIgnorePropertiesConfig.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/FilterIgnorePropertiesConfig.java new file mode 100755 index 00000000..e372f2e4 --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/FilterIgnorePropertiesConfig.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.core.config; + +import lombok.Data; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.context.annotation.Configuration; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author lengleng + * @date 2019/2/1 + * 放行参数配置 + */ +@Data +@Configuration +@RefreshScope +@ConditionalOnExpression("!'${ignore}'.isEmpty()") +@ConfigurationProperties(prefix = "ignore") +public class FilterIgnorePropertiesConfig { + /** + * 放行终端配置,网关不校验此处的终端 + */ + private List clients = new ArrayList<>(); + /** + * 放行url,放行的url不再被安全框架拦截 + */ + private List urls = new ArrayList<>(); + /** + * 不聚合swagger + */ + private List swaggerProviders =new ArrayList<>(); +} diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/JacksonConfig.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/JacksonConfig.java new file mode 100755 index 00000000..df4af1e9 --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/JacksonConfig.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.core.config; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; +import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; +import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer; +import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; +import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; +import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; + +/** + * JacksonConfig + * + * @author: lengleng + * @author: lishangbu + * @date: 2019/2/1 + */ +@Configuration +@ConditionalOnClass(ObjectMapper.class) +@AutoConfigureBefore(JacksonAutoConfiguration.class) +public class JacksonConfig { + /** + * 针对JDK 1.8的日期时间格式特殊处理 + * + * @return ObjectMapper + */ + @Bean + public ObjectMapper getObjectMapper() { + ObjectMapper objectMapper = new ObjectMapper(); + JavaTimeModule javaTimeModule = new JavaTimeModule(); + javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); + javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); + javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss"))); + javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); + javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); + javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss"))); + // javaTimeModule只能手动注册,参考https://github.com/FasterXML/jackson-modules-java8 + objectMapper.registerModule(javaTimeModule); + // 忽略json字符串中不识别的属性 + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + // 忽略无法转换的对象 + objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + return objectMapper; + } +} diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/RedisConfig.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/RedisConfig.java new file mode 100755 index 00000000..39496b34 --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/RedisConfig.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.core.config; + +import lombok.AllArgsConstructor; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.*; +import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +/** + * @author lengleng + * @date 2019/2/1 + * Redis 配置类 + */ +@EnableCaching +@Configuration +@AllArgsConstructor +public class RedisConfig { + private final RedisConnectionFactory factory; + + @Bean + public RedisTemplate redisTemplate() { + RedisTemplate redisTemplate = new RedisTemplate<>(); + redisTemplate.setKeySerializer(new StringRedisSerializer()); + redisTemplate.setHashKeySerializer(new StringRedisSerializer()); + redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer()); + redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer()); + redisTemplate.setConnectionFactory(factory); + return redisTemplate; + } + + @Bean + public HashOperations hashOperations(RedisTemplate redisTemplate) { + return redisTemplate.opsForHash(); + } + + @Bean + public ValueOperations valueOperations(RedisTemplate redisTemplate) { + return redisTemplate.opsForValue(); + } + + @Bean + public ListOperations listOperations(RedisTemplate redisTemplate) { + return redisTemplate.opsForList(); + } + + @Bean + public SetOperations setOperations(RedisTemplate redisTemplate) { + return redisTemplate.opsForSet(); + } + + @Bean + public ZSetOperations zSetOperations(RedisTemplate redisTemplate) { + return redisTemplate.opsForZSet(); + } +} diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/RestTemplateConfig.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/RestTemplateConfig.java new file mode 100755 index 00000000..601cf337 --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/RestTemplateConfig.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.core.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +/** + * @author lengleng + * @date 2019/2/1 + * RestTemplate + */ +@Configuration +public class RestTemplateConfig { + @Bean + public RestTemplate restTemplate() { + return new RestTemplate(); + } +} diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/constant/CommonConstants.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/constant/CommonConstants.java new file mode 100644 index 00000000..c8c2f019 --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/constant/CommonConstants.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.core.constant; + +/** + * @author lengleng + * @date 2019/2/1 + */ +public interface CommonConstants { + /** + * 删除 + */ + String STATUS_DEL = "1"; + /** + * 正常 + */ + String STATUS_NORMAL = "0"; + + /** + * 锁定 + */ + String STATUS_LOCK = "9"; + + /** + * 菜单 + */ + String MENU = "0"; + + /** + * 编码 + */ + String UTF8 = "UTF-8"; + + /** + * JSON 资源 + */ + String CONTENT_TYPE = "application/json; charset=utf-8"; + + /** + * 前端工程名 + */ + String FRONT_END_PROJECT = "pig-ui"; + + /** + * 后端工程名 + */ + String BACK_END_PROJECT = "pig"; + + /** + * 成功标记 + */ + Integer SUCCESS = 0; + /** + * 失败标记 + */ + Integer FAIL = 1; + +} diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/constant/SecurityConstants.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/constant/SecurityConstants.java new file mode 100755 index 00000000..c47f23b1 --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/constant/SecurityConstants.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.core.constant; + +/** + * @author lengleng + * @date 2019/2/1 + */ +public interface SecurityConstants { + /** + * 角色前缀 + */ + String ROLE = "ROLE_"; + /** + * 前缀 + */ + String PROJECT_PREFIX = "pig_"; + + /** + * oauth 相关前缀 + */ + String OAUTH_PREFIX = "oauth:"; + /** + * 项目的license + */ + String PROJECT_LICENSE = "made by pig"; + + /** + * 内部 + */ + String FROM_IN = "Y"; + + /** + * 标志 + */ + String FROM = "from"; + + /** + * 手机号登录URL + */ + String MOBILE_TOKEN_URL = "/mobile/token"; + + /** + * 默认登录URL + */ + String OAUTH_TOKEN_URL = "/oauth/token"; + + /** + * grant_type + */ + String REFRESH_TOKEN = "refresh_token"; + + /** + * oauth 客户端信息 + */ + String CLIENT_DETAILS_KEY = PROJECT_PREFIX+OAUTH_PREFIX+"client:details"; + + /** + * 微信获取OPENID + */ + String WX_AUTHORIZATION_CODE_URL = "https://api.weixin.qq.com/sns/oauth2/access_token" + + "?appid=%s&secret=%s&code=%s&grant_type=authorization_code"; + + /** + * {bcrypt} 加密的特征码 + */ + String BCRYPT = "{bcrypt}"; + /** + * sys_oauth_client_details 表的字段,不包括client_id、client_secret + */ + String CLIENT_FIELDS = "client_id, CONCAT('{noop}',client_secret) as client_secret, resource_ids, scope, " + + "authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, " + + "refresh_token_validity, additional_information, autoapprove"; + + /** + * JdbcClientDetailsService 查询语句 + */ + String BASE_FIND_STATEMENT = "select " + CLIENT_FIELDS + + " from sys_oauth_client_details"; + + /** + * 默认的查询语句 + */ + String DEFAULT_FIND_STATEMENT = BASE_FIND_STATEMENT + " order by client_id"; + + /** + * 按条件client_id 查询 + */ + String DEFAULT_SELECT_STATEMENT = BASE_FIND_STATEMENT + " where client_id = ?"; + +} diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/constant/ServiceNameConstants.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/constant/ServiceNameConstants.java new file mode 100644 index 00000000..8f69acbb --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/constant/ServiceNameConstants.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.core.constant; + +/** + * @author lengleng + * @date 2018年06月22日16:41:01 + * 服务名称 + */ +public interface ServiceNameConstants { + /** + * 认证服务的SERVICEID(zuul 配置的对应) + */ + String AUTH_SERVICE = "pig-auth"; + + /** + * UMPS模块 + */ + String UMPS_SERVICE = "pig-upms"; + +} diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/constant/enums/LoginTypeEnum.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/constant/enums/LoginTypeEnum.java new file mode 100644 index 00000000..f7fc158b --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/constant/enums/LoginTypeEnum.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.core.constant.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +/** + * @author lengleng + * @date 2018/8/15 + * 社交登录类型 + */ +@Getter +@AllArgsConstructor +public enum LoginTypeEnum { + /** + * 账号密码登录 + */ + PWD("PWD", "账号密码登录"), + + /** + * QQ登录 + */ + QQ("QQ", "QQ登录"), + + /** + * 微信登录 + */ + WECHAT("WX", "微信登录"); + + /** + * 类型 + */ + private final String type; + /** + * 描述 + */ + private final String description; +} diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/datascope/DataScope.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/datascope/DataScope.java new file mode 100755 index 00000000..2e925e20 --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/datascope/DataScope.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.core.datascope; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.HashMap; +import java.util.List; + +/** + * @author lengleng + * @date 2019/2/1 + * 数据权限查询参数 + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class DataScope extends HashMap { + /** + * 限制范围的字段名称 + */ + private String scopeName = "deptId"; + + /** + * 具体的数据范围 + */ + private List deptIds; + + /** + * 是否只查询本部门 + */ + private Boolean isOnly = false; +} diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/datascope/DataScopeInterceptor.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/datascope/DataScopeInterceptor.java new file mode 100755 index 00000000..cace59cb --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/datascope/DataScopeInterceptor.java @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.core.datascope; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.toolkit.PluginUtils; +import com.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler; +import lombok.extern.slf4j.Slf4j; +import org.apache.ibatis.executor.statement.StatementHandler; +import org.apache.ibatis.mapping.BoundSql; +import org.apache.ibatis.mapping.MappedStatement; +import org.apache.ibatis.mapping.SqlCommandType; +import org.apache.ibatis.plugin.*; +import org.apache.ibatis.reflection.MetaObject; +import org.apache.ibatis.reflection.SystemMetaObject; + +import java.sql.Connection; +import java.util.List; +import java.util.Map; +import java.util.Properties; + + +/** + * @author lengleng + * @date 2019/2/1 + *

+ * mybatis 数据权限拦截器 + */ +@Slf4j +@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})}) +public class DataScopeInterceptor extends AbstractSqlParserHandler implements Interceptor { + + @Override + public Object intercept(Invocation invocation) throws Throwable { + StatementHandler statementHandler = (StatementHandler) PluginUtils.realTarget(invocation.getTarget()); + MetaObject metaObject = SystemMetaObject.forObject(statementHandler); + this.sqlParser(metaObject); + // 先判断是不是SELECT操作 + MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement"); + if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) { + return invocation.proceed(); + } + + BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql"); + String originalSql = boundSql.getSql(); + Object parameterObject = boundSql.getParameterObject(); + + //查找参数中包含DataScope类型的参数 + DataScope dataScope = findDataScopeObject(parameterObject); + + if (dataScope == null) { + return invocation.proceed(); + } else { + String scopeName = dataScope.getScopeName(); + List deptIds = dataScope.getDeptIds(); + if (StrUtil.isNotBlank(scopeName) && CollectionUtil.isNotEmpty(deptIds)) { + String join = CollectionUtil.join(deptIds, ","); + originalSql = "select * from (" + originalSql + ") temp_data_scope where temp_data_scope." + scopeName + " in (" + join + ")"; + metaObject.setValue("delegate.boundSql.sql", originalSql); + } + return invocation.proceed(); + } + } + + /** + * 生成拦截对象的代理 + * + * @param target 目标对象 + * @return 代理对象 + */ + @Override + public Object plugin(Object target) { + if (target instanceof StatementHandler) { + return Plugin.wrap(target, this); + } + return target; + } + + /** + * mybatis配置的属性 + * + * @param properties mybatis配置的属性 + */ + @Override + public void setProperties(Properties properties) { + + } + + /** + * 查找参数是否包括DataScope对象 + * + * @param parameterObj 参数列表 + * @return DataScope + */ + private DataScope findDataScopeObject(Object parameterObj) { + if (parameterObj instanceof DataScope) { + return (DataScope) parameterObj; + } else if (parameterObj instanceof Map) { + for (Object val : ((Map) parameterObj).values()) { + if (val instanceof DataScope) { + return (DataScope) val; + } + } + } + return null; + } + +} diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/exception/CheckedException.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/exception/CheckedException.java new file mode 100755 index 00000000..4e4aa05f --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/exception/CheckedException.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.core.exception; + +import lombok.NoArgsConstructor; + +/** + * @author lengleng + * @date 😴2018年06月22日16:21:57 + */ +@NoArgsConstructor +public class CheckedException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public CheckedException(String message) { + super(message); + } + + public CheckedException(Throwable cause) { + super(cause); + } + + public CheckedException(String message, Throwable cause) { + super(message, cause); + } + + public CheckedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + +} diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/exception/GlobalExceptionHandler.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/exception/GlobalExceptionHandler.java new file mode 100755 index 00000000..e88e851a --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/exception/GlobalExceptionHandler.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.core.exception; + +import com.pig4cloud.pig.common.core.util.R; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.validation.BindException; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.util.List; + +/** + * @author lengleng + * @date 2019/2/1 + * 全局的的异常处理器 + */ +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + /** + * 全局异常. + * + * @param e the e + * @return R + */ + @ExceptionHandler(Exception.class) + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + public R exception(Exception e) { + log.error("全局异常信息 ex={}", e.getMessage(), e); + return new R<>(e); + } + + /** + * validation Exception + * + * @param exception + * @return R + */ + @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class}) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public R bodyValidExceptionHandler(MethodArgumentNotValidException exception) { + List fieldErrors = exception.getBindingResult().getFieldErrors(); + R result = new R(); + result.setMsg(fieldErrors.get(0).getDefaultMessage()); + log.warn(fieldErrors.get(0).getDefaultMessage()); + return result; + } + +} diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/exception/PigDeniedException.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/exception/PigDeniedException.java new file mode 100755 index 00000000..0c3599e9 --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/exception/PigDeniedException.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.core.exception; + +import lombok.NoArgsConstructor; + +/** + * @author lengleng + * @date 2018年06月22日16:22:03 + * 403 授权拒绝 + */ +@NoArgsConstructor +public class PigDeniedException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public PigDeniedException(String message) { + super(message); + } + + public PigDeniedException(Throwable cause) { + super(cause); + } + + public PigDeniedException(String message, Throwable cause) { + super(message, cause); + } + + public PigDeniedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + +} diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/exception/UnloginException.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/exception/UnloginException.java new file mode 100755 index 00000000..09737120 --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/exception/UnloginException.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.core.exception; + +import lombok.NoArgsConstructor; + +/** + * @author lengleng + * @date 2018年06月22日16:22:10 + */ +@NoArgsConstructor +public class UnloginException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public UnloginException(String message) { + super(message); + } + + public UnloginException(Throwable cause) { + super(cause); + } + + public UnloginException(String message, Throwable cause) { + super(message, cause); + } + + public UnloginException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + +} diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/exception/ValidateCodeException.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/exception/ValidateCodeException.java new file mode 100755 index 00000000..1db33b2f --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/exception/ValidateCodeException.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.core.exception; + +/** + * @author lengleng + * @date 2018年06月22日16:22:15 + */ +public class ValidateCodeException extends Exception { + private static final long serialVersionUID = -7285211528095468156L; + + public ValidateCodeException() { + } + + public ValidateCodeException(String msg) { + super(msg); + } +} diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/ClassUtils.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/ClassUtils.java new file mode 100755 index 00000000..66128ef8 --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/ClassUtils.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.core.util; + +import org.springframework.core.BridgeMethodResolver; +import org.springframework.core.DefaultParameterNameDiscoverer; +import org.springframework.core.MethodParameter; +import org.springframework.core.ParameterNameDiscoverer; +import org.springframework.core.annotation.AnnotatedElementUtils; +import org.springframework.core.annotation.SynthesizingMethodParameter; +import org.springframework.web.method.HandlerMethod; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; + +/** + * 类工具类 + * + * @author L.cm + */ +public class ClassUtils extends org.springframework.util.ClassUtils { + private static final ParameterNameDiscoverer PARAMETERNAMEDISCOVERER = new DefaultParameterNameDiscoverer(); + + /** + * 获取方法参数信息 + * + * @param constructor 构造器 + * @param parameterIndex 参数序号 + * @return {MethodParameter} + */ + public static MethodParameter getMethodParameter(Constructor constructor, int parameterIndex) { + MethodParameter methodParameter = new SynthesizingMethodParameter(constructor, parameterIndex); + methodParameter.initParameterNameDiscovery(PARAMETERNAMEDISCOVERER); + return methodParameter; + } + + /** + * 获取方法参数信息 + * + * @param method 方法 + * @param parameterIndex 参数序号 + * @return {MethodParameter} + */ + public static MethodParameter getMethodParameter(Method method, int parameterIndex) { + MethodParameter methodParameter = new SynthesizingMethodParameter(method, parameterIndex); + methodParameter.initParameterNameDiscovery(PARAMETERNAMEDISCOVERER); + return methodParameter; + } + + /** + * 获取Annotation + * + * @param method Method + * @param annotationType 注解类 + * @param 泛型标记 + * @return {Annotation} + */ + public static A getAnnotation(Method method, Class annotationType) { + Class targetClass = method.getDeclaringClass(); + // The method may be on an interface, but we need attributes from the target class. + // If the target class is null, the method will be unchanged. + Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass); + // If we are dealing with method with generic parameters, find the original method. + specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); + // 先找方法,再找方法上的类 + A annotation = AnnotatedElementUtils.findMergedAnnotation(specificMethod, annotationType); + ; + if (null != annotation) { + return annotation; + } + // 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类 + return AnnotatedElementUtils.findMergedAnnotation(specificMethod.getDeclaringClass(), annotationType); + } + + /** + * 获取Annotation + * + * @param handlerMethod HandlerMethod + * @param annotationType 注解类 + * @param 泛型标记 + * @return {Annotation} + */ + public static A getAnnotation(HandlerMethod handlerMethod, Class annotationType) { + // 先找方法,再找方法上的类 + A annotation = handlerMethod.getMethodAnnotation(annotationType); + if (null != annotation) { + return annotation; + } + // 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类 + Class beanType = handlerMethod.getBeanType(); + return AnnotatedElementUtils.findMergedAnnotation(beanType, annotationType); + } + +} diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/R.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/R.java new file mode 100755 index 00000000..6e046584 --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/R.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.core.util; + +import com.pig4cloud.pig.common.core.constant.CommonConstants; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; + + +/** + * 响应信息主体 + * + * @param + * @author lengleng + */ +@Builder +@ToString +@Accessors(chain = true) +@AllArgsConstructor +public class R implements Serializable { + private static final long serialVersionUID = 1L; + + @Getter + @Setter + private int code = CommonConstants.SUCCESS; + + @Getter + @Setter + private String msg = "success"; + + + @Getter + @Setter + private T data; + + public R() { + super(); + } + + public R(T data) { + super(); + this.data = data; + } + + public R(T data, String msg) { + super(); + this.data = data; + this.msg = msg; + } + + public R(Throwable e) { + super(); + this.msg = e.getMessage(); + this.code = CommonConstants.FAIL; + } +} diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/SpringContextHolder.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/SpringContextHolder.java new file mode 100755 index 00000000..0787af9a --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/SpringContextHolder.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.core.util; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.ApplicationEvent; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; + +/** + * @author lengleng + * @date 2019/2/1 + * Spring 工具类 + */ +@Slf4j +@Service +@Lazy(false) +public class SpringContextHolder implements ApplicationContextAware, DisposableBean { + + private static ApplicationContext applicationContext = null; + + /** + * 取得存储在静态变量中的ApplicationContext. + */ + public static ApplicationContext getApplicationContext() { + return applicationContext; + } + + /** + * 实现ApplicationContextAware接口, 注入Context到静态变量中. + */ + @Override + public void setApplicationContext(ApplicationContext applicationContext) { + SpringContextHolder.applicationContext = applicationContext; + } + + /** + * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. + */ + @SuppressWarnings("unchecked") + public static T getBean(String name) { + return (T) applicationContext.getBean(name); + } + + /** + * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. + */ + public static T getBean(Class requiredType) { + return applicationContext.getBean(requiredType); + } + + /** + * 清除SpringContextHolder中的ApplicationContext为Null. + */ + public static void clearHolder() { + if (log.isDebugEnabled()) { + log.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext); + } + applicationContext = null; + } + + /** + * 发布事件 + * + * @param event + */ + public static void publishEvent(ApplicationEvent event) { + if (applicationContext == null) { + return; + } + applicationContext.publishEvent(event); + } + + /** + * 实现DisposableBean接口, 在Context关闭时清理静态变量. + */ + @Override + public void destroy() throws Exception { + SpringContextHolder.clearHolder(); + } + +} diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/WebUtils.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/WebUtils.java new file mode 100755 index 00000000..3845c078 --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/WebUtils.java @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.core.util; + +import cn.hutool.json.JSONUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang.StringUtils; +import org.springframework.http.MediaType; +import org.springframework.util.Assert; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.method.HandlerMethod; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + + +/** + * Miscellaneous utilities for web applications. + * + * @author L.cm + */ +@Slf4j +public class WebUtils extends org.springframework.web.util.WebUtils { + + public static final String UNKNOWN = "unknown"; + + /** + * 判断是否ajax请求 + * spring ajax 返回含有 ResponseBody 或者 RestController注解 + * + * @param handlerMethod HandlerMethod + * @return 是否ajax请求 + */ + public static boolean isBody(HandlerMethod handlerMethod) { + ResponseBody responseBody = ClassUtils.getAnnotation(handlerMethod, ResponseBody.class); + return responseBody != null; + } + + /** + * 读取cookie + * + * @param name cookie name + * @return cookie value + */ + public static String getCookieVal(String name) { + HttpServletRequest request = WebUtils.getRequest(); + Assert.notNull(request, "request from RequestContextHolder is null"); + return getCookieVal(request, name); + } + + /** + * 读取cookie + * + * @param request HttpServletRequest + * @param name cookie name + * @return cookie value + */ + public static String getCookieVal(HttpServletRequest request, String name) { + Cookie cookie = getCookie(request, name); + return cookie != null ? cookie.getValue() : null; + } + + /** + * 清除 某个指定的cookie + * + * @param response HttpServletResponse + * @param key cookie key + */ + public static void removeCookie(HttpServletResponse response, String key) { + setCookie(response, key, null, 0); + } + + /** + * 设置cookie + * + * @param response HttpServletResponse + * @param name cookie name + * @param value cookie value + * @param maxAgeInSeconds maxage + */ + public static void setCookie(HttpServletResponse response, String name, String value, int maxAgeInSeconds) { + Cookie cookie = new Cookie(name, value); + cookie.setPath("/"); + cookie.setMaxAge(maxAgeInSeconds); + cookie.setHttpOnly(true); + response.addCookie(cookie); + } + + /** + * 获取 HttpServletRequest + * + * @return {HttpServletRequest} + */ + public static HttpServletRequest getRequest() { + return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + } + + /** + * 获取 HttpServletResponse + * + * @return {HttpServletResponse} + */ + public static HttpServletResponse getResponse() { + return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse(); + } + + /** + * 返回json + * + * @param response HttpServletResponse + * @param result 结果对象 + */ + public static void renderJson(HttpServletResponse response, Object result) { + renderJson(response, result, MediaType.APPLICATION_JSON_UTF8_VALUE); + } + + /** + * 返回json + * + * @param response HttpServletResponse + * @param result 结果对象 + * @param contentType contentType + */ + public static void renderJson(HttpServletResponse response, Object result, String contentType) { + response.setCharacterEncoding("UTF-8"); + response.setContentType(contentType); + try (PrintWriter out = response.getWriter()) { + out.append(JSONUtil.toJsonStr(result)); + } catch (IOException e) { + log.error(e.getMessage(), e); + } + } + + /** + * 获取ip + * + * @return {String} + */ + public static String getIP() { + return getIP(WebUtils.getRequest()); + } + + /** + * 获取ip + * + * @param request HttpServletRequest + * @return {String} + */ + public static String getIP(HttpServletRequest request) { + Assert.notNull(request, "HttpServletRequest is null"); + String ip = request.getHeader("X-Requested-For"); + if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) { + ip = request.getHeader("X-Forwarded-For"); + } + if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) { + ip = request.getHeader("HTTP_CLIENT_IP"); + } + if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) { + ip = request.getHeader("HTTP_X_FORWARDED_FOR"); + } + if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + return StringUtils.isBlank(ip) ? null : ip.split(",")[0]; + } +} + diff --git a/pig-common/pig-common-core/src/main/resources/META-INF/spring.factories b/pig-common/pig-common-core/src/main/resources/META-INF/spring.factories new file mode 100755 index 00000000..a7de3d37 --- /dev/null +++ b/pig-common/pig-common-core/src/main/resources/META-INF/spring.factories @@ -0,0 +1,7 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ + com.pig4cloud.pig.common.core.config.JacksonConfig,\ + com.pig4cloud.pig.common.core.config.RedisConfig,\ + com.pig4cloud.pig.common.core.config.RestTemplateConfig,\ + com.pig4cloud.pig.common.core.config.FilterIgnorePropertiesConfig,\ + com.pig4cloud.pig.common.core.exception.GlobalExceptionHandler,\ + com.pig4cloud.pig.common.core.util.SpringContextHolder diff --git a/pig-common/pig-common-core/src/main/resources/banner.txt b/pig-common/pig-common-core/src/main/resources/banner.txt new file mode 100755 index 00000000..63be6e1e --- /dev/null +++ b/pig-common/pig-common-core/src/main/resources/banner.txt @@ -0,0 +1,16 @@ +${AnsiColor.BRIGHT_YELLOW} + + ::::::::: ::::::::::: :::::::: ::: ::: + :+: :+: :+: :+: :+: :+: :+: + +:+ +:+ +:+ +:+ +:+ +:+ + +#++:++#+ +#+ :#: +#++:+ + +#+ +#+ +#+ +#+# +#+ +#+ + #+# #+# #+# #+# #+# #+# + ### ########### ######## ### ### + + www.pig4cloud.com + + Pig Microservice Architecture + + + diff --git a/pig-common/pig-common-core/src/main/resources/logback-spring.xml b/pig-common/pig-common-core/src/main/resources/logback-spring.xml new file mode 100755 index 00000000..70ea9fa5 --- /dev/null +++ b/pig-common/pig-common-core/src/main/resources/logback-spring.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + ${CONSOLE_LOG_PATTERN} + + + + + + ${log.path}/debug.log + + ${log.path}/%d{yyyy-MM, aux}/debug.%d{yyyy-MM-dd}.%i.log.gz + 50MB + 30 + + + %date [%thread] %-5level [%logger{50}] %file:%line - %msg%n + + + + + + ${log.path}/error.log + + ${log.path}/%d{yyyy-MM}/error.%d{yyyy-MM-dd}.%i.log.gz + 50MB + 30 + + + %date [%thread] %-5level [%logger{50}] %file:%line - %msg%n + + + ERROR + + + + + + + + + + diff --git a/pig-common/pig-common-log/pom.xml b/pig-common/pig-common-log/pom.xml new file mode 100755 index 00000000..f87ef87f --- /dev/null +++ b/pig-common/pig-common-log/pom.xml @@ -0,0 +1,56 @@ + + + + + 4.0.0 + + com.pig4cloud + pig-common + ${pig.version} + + + pig-common-log + jar + + pig 日志服务 + + + + + + com.pig4cloud + pig-common-core + ${pig.version} + + + + com.pig4cloud + pig-upms-api + ${pig.version} + + + + org.springframework.security + spring-security-core + + + org.springframework.security.oauth + spring-security-oauth2 + + + diff --git a/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/LogAutoConfiguration.java b/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/LogAutoConfiguration.java new file mode 100755 index 00000000..805c606b --- /dev/null +++ b/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/LogAutoConfiguration.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.log; + +import com.pig4cloud.pig.admin.api.feign.RemoteLogService; +import com.pig4cloud.pig.common.log.aspect.SysLogAspect; +import com.pig4cloud.pig.common.log.event.SysLogListener; +import lombok.AllArgsConstructor; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableAsync; + +/** + * @author lengleng + * @date 2019/2/1 + * 日志自动配置 + */ +@EnableAsync +@Configuration +@AllArgsConstructor +@ConditionalOnWebApplication +@EnableFeignClients({"com.pig4cloud.pig.admin.api.feign"}) +public class LogAutoConfiguration { + private final RemoteLogService remoteLogService; + + @Bean + public SysLogListener sysLogListener() { + return new SysLogListener(remoteLogService); + } + + @Bean + public SysLogAspect sysLogAspect() { + return new SysLogAspect(); + } +} diff --git a/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/annotation/SysLog.java b/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/annotation/SysLog.java new file mode 100755 index 00000000..110f8367 --- /dev/null +++ b/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/annotation/SysLog.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.log.annotation; + +import java.lang.annotation.*; + +/** + * @author lengleng + * @date 2019/2/1 + * 操作日志注解 + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface SysLog { + + /** + * 描述 + * + * @return {String} + */ + String value(); +} diff --git a/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/aspect/SysLogAspect.java b/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/aspect/SysLogAspect.java new file mode 100755 index 00000000..d62ed995 --- /dev/null +++ b/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/aspect/SysLogAspect.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.log.aspect; + +import com.pig4cloud.pig.common.core.util.SpringContextHolder; +import com.pig4cloud.pig.common.log.annotation.SysLog; +import com.pig4cloud.pig.common.log.event.SysLogEvent; +import com.pig4cloud.pig.common.log.util.SysLogUtils; +import lombok.extern.slf4j.Slf4j; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; + +/** + * 操作日志使用spring event异步入库 + * + * @author L.cm + */ +@Aspect +@Slf4j +public class SysLogAspect { + + @Around("@annotation(sysLog)") + public Object around(ProceedingJoinPoint point, SysLog sysLog) throws Throwable { + String strClassName = point.getTarget().getClass().getName(); + String strMethodName = point.getSignature().getName(); + log.debug("[类名]:{},[方法]:{}", strClassName, strMethodName); + + com.pig4cloud.pig.admin.api.entity.SysLog logVo = SysLogUtils.getSysLog(); + logVo.setTitle(sysLog.value()); + // 发送异步日志事件 + Long startTime = System.currentTimeMillis(); + Object obj = point.proceed(); + Long endTime = System.currentTimeMillis(); + logVo.setTime(endTime - startTime); + SpringContextHolder.publishEvent(new SysLogEvent(logVo)); + return obj; + } + +} diff --git a/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/event/SysLogEvent.java b/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/event/SysLogEvent.java new file mode 100755 index 00000000..1b6e6844 --- /dev/null +++ b/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/event/SysLogEvent.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.log.event; + +import com.pig4cloud.pig.admin.api.entity.SysLog; +import org.springframework.context.ApplicationEvent; + +/** + * @author lengleng + * 系统日志事件 + */ +public class SysLogEvent extends ApplicationEvent { + + public SysLogEvent(SysLog source) { + super(source); + } +} diff --git a/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/event/SysLogListener.java b/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/event/SysLogListener.java new file mode 100755 index 00000000..3989bf04 --- /dev/null +++ b/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/event/SysLogListener.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.log.event; + +import com.pig4cloud.pig.admin.api.entity.SysLog; +import com.pig4cloud.pig.admin.api.feign.RemoteLogService; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.event.EventListener; +import org.springframework.core.annotation.Order; +import org.springframework.scheduling.annotation.Async; + + +/** + * @author lengleng + * 异步监听日志事件 + */ +@Slf4j +@AllArgsConstructor +public class SysLogListener { + private final RemoteLogService remoteLogService; + + @Async + @Order + @EventListener(SysLogEvent.class) + public void saveSysLog(SysLogEvent event) { + SysLog sysLog = (SysLog) event.getSource(); + remoteLogService.saveLog(sysLog); + } +} diff --git a/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/util/SysLogUtils.java b/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/util/SysLogUtils.java new file mode 100755 index 00000000..48f16f00 --- /dev/null +++ b/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/util/SysLogUtils.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.log.util; + +import cn.hutool.core.util.URLUtil; +import cn.hutool.extra.servlet.ServletUtil; +import cn.hutool.http.HttpUtil; +import com.pig4cloud.pig.admin.api.entity.SysLog; +import com.pig4cloud.pig.common.core.constant.CommonConstants; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.provider.OAuth2Authentication; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.util.Objects; + +/** + * 系统日志工具类 + * + * @author L.cm + */ +public class SysLogUtils { + public static SysLog getSysLog() { + HttpServletRequest request = ((ServletRequestAttributes) Objects + .requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); + SysLog sysLog = new SysLog(); + sysLog.setCreateBy(Objects.requireNonNull(getUsername())); + sysLog.setType(CommonConstants.STATUS_NORMAL); + sysLog.setRemoteAddr(ServletUtil.getClientIP(request)); + sysLog.setRequestUri(URLUtil.getPath(request.getRequestURI())); + sysLog.setMethod(request.getMethod()); + sysLog.setUserAgent(request.getHeader("user-agent")); + sysLog.setParams(HttpUtil.toParams(request.getParameterMap())); + sysLog.setServiceId(getClientId()); + return sysLog; + } + + /** + * 获取客户端 + * + * @return clientId + */ + private static String getClientId() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication instanceof OAuth2Authentication) { + OAuth2Authentication auth2Authentication = (OAuth2Authentication) authentication; + return auth2Authentication.getOAuth2Request().getClientId(); + } + return null; + } + + /** + * 获取用户名称 + * + * @return username + */ + private static String getUsername() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication == null) { + return null; + } + return authentication.getName(); + } + +} diff --git a/pig-common/pig-common-log/src/main/resources/META-INF/spring.factories b/pig-common/pig-common-log/src/main/resources/META-INF/spring.factories new file mode 100755 index 00000000..032c11d8 --- /dev/null +++ b/pig-common/pig-common-log/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ + com.pig4cloud.pig.common.log.LogAutoConfiguration diff --git a/pig-common/pig-common-security/pom.xml b/pig-common/pig-common-security/pom.xml new file mode 100755 index 00000000..a194316e --- /dev/null +++ b/pig-common/pig-common-security/pom.xml @@ -0,0 +1,52 @@ + + + + + 4.0.0 + + com.pig4cloud + pig-common + ${pig.version} + + + pig-common-security + jar + + pig 安全工具类 + + + + + + com.pig4cloud + pig-common-core + ${pig.version} + + + + org.springframework.cloud + spring-cloud-starter-security + + + + com.pig4cloud + pig-upms-api + ${pig.version} + + + diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/annotation/EnablePigFeignClients.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/annotation/EnablePigFeignClients.java new file mode 100755 index 00000000..dd7ea4d7 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/annotation/EnablePigFeignClients.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.annotation; + +import org.springframework.cloud.openfeign.EnableFeignClients; + +import java.lang.annotation.*; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@EnableFeignClients +public @interface EnablePigFeignClients { + /** + * Alias for the {@link #basePackages()} attribute. Allows for more concise annotation + * declarations e.g.: {@code @ComponentScan("org.my.pkg")} instead of + * {@code @ComponentScan(basePackages="org.my.pkg")}. + * + * @return the array of 'basePackages'. + */ + String[] value() default {}; + + /** + * Base packages to scan for annotated components. + *

+ * {@link #value()} is an alias for (and mutually exclusive with) this attribute. + *

+ * Use {@link #basePackageClasses()} for a type-safe alternative to String-based + * package names. + * + * @return the array of 'basePackages'. + */ + String[] basePackages() default {"com.pig4cloud.pig"}; + + /** + * Type-safe alternative to {@link #basePackages()} for specifying the packages to + * scan for annotated components. The package of each class specified will be scanned. + *

+ * Consider creating a special no-op marker class or interface in each package that + * serves no purpose other than being referenced by this attribute. + * + * @return the array of 'basePackageClasses'. + */ + Class[] basePackageClasses() default {}; + + /** + * A custom @Configuration for all feign clients. Can contain override + * @Bean definition for the pieces that make up the client, for instance + * {@link feign.codec.Decoder}, {@link feign.codec.Encoder}, {@link feign.Contract}. + * + * @see FeignClientsConfiguration for the defaults + */ + Class[] defaultConfiguration() default {}; + + /** + * List of classes annotated with @FeignClient. If not empty, disables classpath scanning. + * + * @return + */ + Class[] clients() default {}; +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/annotation/Inner.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/annotation/Inner.java new file mode 100644 index 00000000..e28d301d --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/annotation/Inner.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.annotation; + +import java.lang.annotation.*; + +/** + * @author lengleng + * @date 2018/11/26 + *

+ * 服务调用不鉴权注解 + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface Inner { + + /** + * 是否AOP统一处理 + * + * @return false, true + */ + boolean value() default true; + + /** + * 需要特殊判空的字段(预留) + * + * @return {} + */ + String[] field() default {}; +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/BaseResourceServerConfigurerAdapter.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/BaseResourceServerConfigurerAdapter.java new file mode 100755 index 00000000..050ea408 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/BaseResourceServerConfigurerAdapter.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.component; + +import com.pig4cloud.pig.common.core.config.FilterIgnorePropertiesConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; +import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter; +import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter; +import org.springframework.security.oauth2.provider.token.RemoteTokenServices; +import org.springframework.web.client.DefaultResponseErrorHandler; +import org.springframework.web.client.RestTemplate; + +import java.io.IOException; + +/** + * @author lengleng + * @date 2019/2/1 + *

+ * 1. 支持remoteTokenServices 负载均衡 + * 2. 支持 获取用户全部信息 + */ +public abstract class BaseResourceServerConfigurerAdapter extends ResourceServerConfigurerAdapter { + @Autowired + protected ResourceAuthExceptionEntryPoint resourceAuthExceptionEntryPoint; + @Autowired + protected PigAccessDeniedHandler pigAccessDeniedHandler; + @Autowired + protected RemoteTokenServices remoteTokenServices; + @Autowired + protected UserDetailsService userDetailsService; + @Autowired + private FilterIgnorePropertiesConfig filterIgnorePropertiesConfig; + + + /** + * 默认的配置,对外暴露 + * + * @param http + * @throws Exception + */ + @Override + public void configure(HttpSecurity http) throws Exception{ + //允许使用iframe 嵌套,避免swagger-ui 不被加载的问题 + http.headers().frameOptions().disable(); + ExpressionUrlAuthorizationConfigurer + .ExpressionInterceptUrlRegistry registry = http + .authorizeRequests(); + filterIgnorePropertiesConfig.getUrls() + .forEach(url -> registry.antMatchers(url).permitAll()); + registry.anyRequest().authenticated() + .and().csrf().disable(); + } + + /** + * 提供子类重写 + *

+ * 1. 不重写,默认支持获取雍熙 + * 2. 重写notGetUser,提供性能 + *

+ * see codegen ResourceServerConfigurer + * + * @param resources + */ + @Override + public void configure(ResourceServerSecurityConfigurer resources) { + canGetUser(resources); + } + + @Bean + @Primary + @LoadBalanced + public RestTemplate lbRestTemplate() { + RestTemplate restTemplate = new RestTemplate(); + restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { + @Override + public void handleError(ClientHttpResponse response) throws IOException { + if (response.getRawStatusCode() != HttpStatus.BAD_REQUEST.value()) { + super.handleError(response); + } + } + }); + return restTemplate; + } + /** + * 不获取用户详细 只有用户名 + * + * @param resources + */ + protected void notGetUser(ResourceServerSecurityConfigurer resources) { + DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter(); + DefaultUserAuthenticationConverter userTokenConverter = new DefaultUserAuthenticationConverter(); + accessTokenConverter.setUserTokenConverter(userTokenConverter); + + remoteTokenServices.setRestTemplate(lbRestTemplate()); + remoteTokenServices.setAccessTokenConverter(accessTokenConverter); + resources.authenticationEntryPoint(resourceAuthExceptionEntryPoint) + .accessDeniedHandler(pigAccessDeniedHandler) + .tokenServices(remoteTokenServices); + } + + + /** + * 上下文中获取用户全部信息,两次调用userDetailsService,影响性能 + * + * @param resources + */ + private void canGetUser(ResourceServerSecurityConfigurer resources) { + DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter(); + DefaultUserAuthenticationConverter userTokenConverter = new DefaultUserAuthenticationConverter(); + userTokenConverter.setUserDetailsService(userDetailsService); + accessTokenConverter.setUserTokenConverter(userTokenConverter); + + remoteTokenServices.setRestTemplate(lbRestTemplate()); + remoteTokenServices.setAccessTokenConverter(accessTokenConverter); + resources.authenticationEntryPoint(resourceAuthExceptionEntryPoint) + .accessDeniedHandler(pigAccessDeniedHandler) + .tokenServices(remoteTokenServices); + } + +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PermissionService.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PermissionService.java new file mode 100755 index 00000000..b866314c --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PermissionService.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.component; + +import cn.hutool.core.util.StrUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; +import org.springframework.util.PatternMatchUtils; +import org.springframework.util.StringUtils; + +import java.util.Collection; + +/** + * @author lengleng + * @date 2019/2/1 + * 接口权限判断工具 + */ +@Slf4j +@Component("pms") +public class PermissionService { + /** + * 判断接口是否有xxx:xxx权限 + * + * @param permission 权限 + * @return {boolean} + */ + public boolean hasPermission(String permission) { + if (StrUtil.isBlank(permission)) { + return false; + } + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication == null) { + return false; + } + Collection authorities = authentication.getAuthorities(); + return authorities.stream() + .map(GrantedAuthority::getAuthority) + .filter(StringUtils::hasText) + .anyMatch(x -> PatternMatchUtils.simpleMatch(permission, x)); + } +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigAccessDeniedHandler.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigAccessDeniedHandler.java new file mode 100755 index 00000000..b320c900 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigAccessDeniedHandler.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.component; + +/** + * @author lengleng + * @date 2019/2/1 + */ + +import cn.hutool.http.HttpStatus; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.pig4cloud.pig.common.core.constant.CommonConstants; +import com.pig4cloud.pig.common.core.exception.PigDeniedException; +import com.pig4cloud.pig.common.core.util.R; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler; +import org.springframework.stereotype.Component; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +/** + * @author lengleng + * 授权拒绝处理器,覆盖默认的OAuth2AccessDeniedHandler + * 包装失败信息到PigDeniedException + */ +@Slf4j +@Component +@AllArgsConstructor +public class PigAccessDeniedHandler extends OAuth2AccessDeniedHandler { + private final ObjectMapper objectMapper; + + /** + * 授权拒绝处理,使用R包装 + * + * @param request request + * @param response response + * @param authException authException + * @throws IOException IOException + * @throws ServletException ServletException + */ + @Override + public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException { + log.info("授权失败,禁止访问 {}", request.getRequestURI()); + response.setCharacterEncoding(CommonConstants.UTF8); + response.setContentType(CommonConstants.CONTENT_TYPE); + R result = new R<>(new PigDeniedException("授权失败,禁止访问")); + response.setStatus(HttpStatus.HTTP_FORBIDDEN); + PrintWriter printWriter = response.getWriter(); + printWriter.append(objectMapper.writeValueAsString(result)); + } +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigAuth2ExceptionSerializer.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigAuth2ExceptionSerializer.java new file mode 100644 index 00000000..340bc7ec --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigAuth2ExceptionSerializer.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.component; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import com.pig4cloud.pig.common.core.constant.CommonConstants; +import com.pig4cloud.pig.common.security.exception.PigAuth2Exception; +import lombok.SneakyThrows; + +/** + * @author lengleng + * @date 2019/2/1 + *

+ * OAuth2 异常格式化 + */ +public class PigAuth2ExceptionSerializer extends StdSerializer { + public PigAuth2ExceptionSerializer() { + super(PigAuth2Exception.class); + } + + @Override + @SneakyThrows + public void serialize(PigAuth2Exception value, JsonGenerator gen, SerializerProvider provider) { + gen.writeStartObject(); + gen.writeObjectField("code", CommonConstants.FAIL); + gen.writeStringField("msg", value.getMessage()); + gen.writeStringField("data", value.getErrorCode()); + gen.writeEndObject(); + } +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigResourceServerTokenRelayAutoConfiguration.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigResourceServerTokenRelayAutoConfiguration.java new file mode 100755 index 00000000..e273df06 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigResourceServerTokenRelayAutoConfiguration.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.component; + +import org.springframework.boot.autoconfigure.AutoConfigureAfter; +import org.springframework.boot.autoconfigure.condition.AllNestedConditions; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration; +import org.springframework.cloud.security.oauth2.client.AccessTokenContextRelay; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.oauth2.client.OAuth2ClientContext; +import org.springframework.security.oauth2.config.annotation.web.configuration.OAuth2ClientConfiguration; +import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration; + +import java.lang.annotation.*; + +/** + * @author lengleng + * @date 2019/2/1 + * 注入AccessTokenContextRelay 解决feign 传递token 为空问题 + */ +@Configuration +@AutoConfigureAfter(OAuth2AutoConfiguration.class) +@ConditionalOnWebApplication +@ConditionalOnProperty("security.oauth2.client.client-id") +public class PigResourceServerTokenRelayAutoConfiguration { + + @Bean + public AccessTokenContextRelay accessTokenContextRelay(OAuth2ClientContext context) { + return new AccessTokenContextRelay(context); + } + + @Target({ElementType.TYPE, ElementType.METHOD}) + @Retention(RetentionPolicy.RUNTIME) + @Documented + @Conditional(OAuth2OnClientInResourceServerCondition.class) + @interface ConditionalOnOAuth2ClientInResourceServer { + + } + + private static class OAuth2OnClientInResourceServerCondition + extends AllNestedConditions { + + public OAuth2OnClientInResourceServerCondition() { + super(ConfigurationPhase.REGISTER_BEAN); + } + + @ConditionalOnBean(ResourceServerConfiguration.class) + static class Server { + } + + @ConditionalOnBean(OAuth2ClientConfiguration.class) + static class Client { + } + + } +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigWebResponseExceptionTranslator.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigWebResponseExceptionTranslator.java new file mode 100755 index 00000000..0a062407 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigWebResponseExceptionTranslator.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.component; + +import com.pig4cloud.pig.common.security.exception.*; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.oauth2.common.DefaultThrowableAnalyzer; +import org.springframework.security.oauth2.common.OAuth2AccessToken; +import org.springframework.security.oauth2.common.exceptions.ClientAuthenticationException; +import org.springframework.security.oauth2.common.exceptions.InsufficientScopeException; +import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; +import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; +import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator; +import org.springframework.security.web.util.ThrowableAnalyzer; +import org.springframework.web.HttpRequestMethodNotSupportedException; + +/** + * @author lengleng + * @date 2019/2/1 + * 异常处理,重写oauth 默认实现 + */ +@Slf4j +public class PigWebResponseExceptionTranslator implements WebResponseExceptionTranslator { + + private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer(); + + @Override + public ResponseEntity translate(Exception e) throws Exception { + + // Try to extract a SpringSecurityException from the stacktrace + Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e); + + Exception ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, + causeChain); + if (ase != null) { + return handleOAuth2Exception(new UnauthorizedException(e.getMessage(), e)); + } + + ase = (AccessDeniedException) throwableAnalyzer + .getFirstThrowableOfType(AccessDeniedException.class, causeChain); + if (ase != null) { + return handleOAuth2Exception(new ForbiddenException(ase.getMessage(), ase)); + } + + ase = (InvalidGrantException) throwableAnalyzer + .getFirstThrowableOfType(InvalidGrantException.class, causeChain); + if (ase != null) { + return handleOAuth2Exception(new InvalidException(ase.getMessage(), ase)); + } + + ase = (HttpRequestMethodNotSupportedException) throwableAnalyzer + .getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain); + if (ase != null) { + return handleOAuth2Exception(new MethodNotAllowed(ase.getMessage(), ase)); + } + + ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType( + OAuth2Exception.class, causeChain); + + if (ase != null) { + return handleOAuth2Exception((OAuth2Exception) ase); + } + + return handleOAuth2Exception(new ServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), e)); + + } + + + private ResponseEntity handleOAuth2Exception(OAuth2Exception e) { + + int status = e.getHttpErrorCode(); + HttpHeaders headers = new HttpHeaders(); + headers.set("Cache-Control", "no-store"); + headers.set("Pragma", "no-cache"); + if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) { + headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary())); + } + + // 客户端异常直接返回客户端,不然无法解析 + if (e instanceof ClientAuthenticationException) { + return new ResponseEntity<>(e, headers, + HttpStatus.valueOf(status)); + } + return new ResponseEntity<>(new PigAuth2Exception(e.getMessage(), e.getOAuth2ErrorCode()), headers, + HttpStatus.valueOf(status)); + + } +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigxSecurityInnerAspect.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigxSecurityInnerAspect.java new file mode 100644 index 00000000..0acc2783 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigxSecurityInnerAspect.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.component; + +import cn.hutool.core.util.StrUtil; +import com.pig4cloud.pig.common.core.constant.SecurityConstants; +import com.pig4cloud.pig.common.security.annotation.Inner; +import lombok.AllArgsConstructor; +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.stereotype.Component; + +import javax.servlet.http.HttpServletRequest; + +/** + * @author lengleng + * @date 2018/11/26 + *

+ * 服务间接口不鉴权处理逻辑 + */ +@Slf4j +@Aspect +@Component +@AllArgsConstructor +public class PigxSecurityInnerAspect { + private final HttpServletRequest request; + + @SneakyThrows + @Around("@annotation(inner)") + public Object around(ProceedingJoinPoint point, Inner inner) { + String header = request.getHeader(SecurityConstants.FROM); + if (inner.value() && !StrUtil.equals(SecurityConstants.FROM_IN, header)) { + log.warn("访问接口 {} 没有权限", point.getSignature().getName()); + throw new AccessDeniedException("Access is denied"); + } + return point.proceed(); + } + +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/ResourceAuthExceptionEntryPoint.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/ResourceAuthExceptionEntryPoint.java new file mode 100755 index 00000000..840db018 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/ResourceAuthExceptionEntryPoint.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.component; + +import cn.hutool.http.HttpStatus; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.pig4cloud.pig.common.core.constant.CommonConstants; +import com.pig4cloud.pig.common.core.util.R; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +/** + * @author lengleng + * @date 2019/2/1 + * 客户端异常处理 + * 1. 可以根据 AuthenticationException 不同细化异常处理 + */ +@Slf4j +@Component +@AllArgsConstructor +public class ResourceAuthExceptionEntryPoint implements AuthenticationEntryPoint { + private final ObjectMapper objectMapper; + + @Override + public void commence(HttpServletRequest request, HttpServletResponse response, + AuthenticationException authException) throws IOException { + response.setCharacterEncoding(CommonConstants.UTF8); + response.setContentType(CommonConstants.CONTENT_TYPE); + R result = new R<>(); + result.setCode(HttpStatus.HTTP_UNAUTHORIZED); + if (authException != null) { + result.setMsg("error"); + result.setData(authException.getMessage()); + } + response.setStatus(HttpStatus.HTTP_UNAUTHORIZED); + PrintWriter printWriter = response.getWriter(); + printWriter.append(objectMapper.writeValueAsString(result)); + } +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/exception/ForbiddenException.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/exception/ForbiddenException.java new file mode 100755 index 00000000..b4b02ca4 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/exception/ForbiddenException.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.exception; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.pig4cloud.pig.common.security.component.PigAuth2ExceptionSerializer; +import org.springframework.http.HttpStatus; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@JsonSerialize(using = PigAuth2ExceptionSerializer.class) +public class ForbiddenException extends PigAuth2Exception { + + public ForbiddenException(String msg, Throwable t) { + super(msg); + } + + @Override + public String getOAuth2ErrorCode() { + return "access_denied"; + } + + @Override + public int getHttpErrorCode() { + return HttpStatus.FORBIDDEN.value(); + } + +} + diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/exception/InvalidException.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/exception/InvalidException.java new file mode 100755 index 00000000..fe06f915 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/exception/InvalidException.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.exception; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.pig4cloud.pig.common.security.component.PigAuth2ExceptionSerializer; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@JsonSerialize(using = PigAuth2ExceptionSerializer.class) +public class InvalidException extends PigAuth2Exception { + + public InvalidException(String msg, Throwable t) { + super(msg); + } + + @Override + public String getOAuth2ErrorCode() { + return "invalid_exception"; + } + + @Override + public int getHttpErrorCode() { + return 426; + } + +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/exception/MethodNotAllowed.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/exception/MethodNotAllowed.java new file mode 100755 index 00000000..ddebd4c1 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/exception/MethodNotAllowed.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.exception; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.pig4cloud.pig.common.security.component.PigAuth2ExceptionSerializer; +import org.springframework.http.HttpStatus; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@JsonSerialize(using = PigAuth2ExceptionSerializer.class) +public class MethodNotAllowed extends PigAuth2Exception { + + public MethodNotAllowed(String msg, Throwable t) { + super(msg); + } + + @Override + public String getOAuth2ErrorCode() { + return "method_not_allowed"; + } + + @Override + public int getHttpErrorCode() { + return HttpStatus.METHOD_NOT_ALLOWED.value(); + } + +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/exception/PigAuth2Exception.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/exception/PigAuth2Exception.java new file mode 100755 index 00000000..83e827ab --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/exception/PigAuth2Exception.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.exception; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.pig4cloud.pig.common.security.component.PigAuth2ExceptionSerializer; +import lombok.Getter; +import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; + +/** + * @author lengleng + * @date 2019/2/1 + * 自定义OAuth2Exception + */ +@JsonSerialize(using = PigAuth2ExceptionSerializer.class) +public class PigAuth2Exception extends OAuth2Exception { + @Getter + private String errorCode; + + public PigAuth2Exception(String msg) { + super(msg); + } + + public PigAuth2Exception(String msg, String errorCode) { + super(msg); + this.errorCode = errorCode; + } +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/exception/ServerErrorException.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/exception/ServerErrorException.java new file mode 100755 index 00000000..39dc5804 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/exception/ServerErrorException.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.exception; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.pig4cloud.pig.common.security.component.PigAuth2ExceptionSerializer; +import org.springframework.http.HttpStatus; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@JsonSerialize(using = PigAuth2ExceptionSerializer.class) +public class ServerErrorException extends PigAuth2Exception { + + public ServerErrorException(String msg, Throwable t) { + super(msg); + } + + @Override + public String getOAuth2ErrorCode() { + return "server_error"; + } + + @Override + public int getHttpErrorCode() { + return HttpStatus.INTERNAL_SERVER_ERROR.value(); + } + +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/exception/UnauthorizedException.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/exception/UnauthorizedException.java new file mode 100755 index 00000000..101894ae --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/exception/UnauthorizedException.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.exception; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.pig4cloud.pig.common.security.component.PigAuth2ExceptionSerializer; +import org.springframework.http.HttpStatus; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@JsonSerialize(using = PigAuth2ExceptionSerializer.class) +public class UnauthorizedException extends PigAuth2Exception { + + public UnauthorizedException(String msg, Throwable t) { + super(msg); + } + + @Override + public String getOAuth2ErrorCode() { + return "unauthorized"; + } + + @Override + public int getHttpErrorCode() { + return HttpStatus.UNAUTHORIZED.value(); + } + +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/feign/PigFeignClientConfiguration.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/feign/PigFeignClientConfiguration.java new file mode 100755 index 00000000..6c1acc95 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/feign/PigFeignClientConfiguration.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.feign; + +import feign.RequestInterceptor; +import lombok.AllArgsConstructor; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.cloud.security.oauth2.client.AccessTokenContextRelay; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.oauth2.client.OAuth2ClientContext; +import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails; + +/** + * @author lengleng + * @date 2019/2/1 + * feign 拦截器传递 header 中oauth token, + * 使用hystrix 的信号量模式 + */ +@Configuration +@AllArgsConstructor +@ConditionalOnProperty("security.oauth2.client.client-id") +public class PigFeignClientConfiguration { + @Bean + public RequestInterceptor oauth2FeignRequestInterceptor(OAuth2ClientContext oAuth2ClientContext, + OAuth2ProtectedResourceDetails resource, + AccessTokenContextRelay accessTokenContextRelay) { + return new PigFeignClientInterceptor(oAuth2ClientContext, resource,accessTokenContextRelay); + } +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/feign/PigFeignClientInterceptor.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/feign/PigFeignClientInterceptor.java new file mode 100755 index 00000000..8b5cea46 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/feign/PigFeignClientInterceptor.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.feign; + +import cn.hutool.core.collection.CollUtil; +import com.pig4cloud.pig.common.core.constant.SecurityConstants; +import feign.RequestTemplate; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cloud.security.oauth2.client.AccessTokenContextRelay; +import org.springframework.cloud.security.oauth2.client.feign.OAuth2FeignRequestInterceptor; +import org.springframework.security.oauth2.client.OAuth2ClientContext; +import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails; + +import java.util.Collection; + +/** + * @author lengleng + * @date 2019/2/1 + * 扩展OAuth2FeignRequestInterceptor + */ +@Slf4j +public class PigFeignClientInterceptor extends OAuth2FeignRequestInterceptor { + private final OAuth2ClientContext oAuth2ClientContext; + private final AccessTokenContextRelay accessTokenContextRelay; + + /** + * Default constructor which uses the provided OAuth2ClientContext and Bearer tokens + * within Authorization header + * + * @param oAuth2ClientContext provided context + * @param resource type of resource to be accessed + * @param accessTokenContextRelay + */ + public PigFeignClientInterceptor(OAuth2ClientContext oAuth2ClientContext + , OAuth2ProtectedResourceDetails resource, AccessTokenContextRelay accessTokenContextRelay) { + super(oAuth2ClientContext, resource); + this.oAuth2ClientContext = oAuth2ClientContext; + this.accessTokenContextRelay = accessTokenContextRelay; + } + + + /** + * Create a template with the header of provided name and extracted extract + * 1. 如果使用 非web 请求,header 区别 + * 2. 根据authentication 还原请求token + * + * @param template + */ + @Override + public void apply(RequestTemplate template) { + Collection fromHeader = template.headers().get(SecurityConstants.FROM); + if (CollUtil.isNotEmpty(fromHeader) && fromHeader.contains(SecurityConstants.FROM_IN)) { + return; + } + + accessTokenContextRelay.copyToken(); + if (oAuth2ClientContext != null + && oAuth2ClientContext.getAccessToken() != null) { + super.apply(template); + } + } +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/AuthenticationFailureEvenHandler.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/AuthenticationFailureEvenHandler.java new file mode 100755 index 00000000..634af6c2 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/AuthenticationFailureEvenHandler.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.handler; + +import org.springframework.context.ApplicationListener; +import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; + +/** + * @author lengleng + * @date 2019/2/1 + * 认证失败事件处理器 + */ +public abstract class AuthenticationFailureEvenHandler implements ApplicationListener { + + /** + * Handle an application event. + * + * @param event the event to respond to + */ + @Override + public void onApplicationEvent(AbstractAuthenticationFailureEvent event) { + AuthenticationException authenticationException = event.getException(); + Authentication authentication = (Authentication) event.getSource(); + + handle(authenticationException, authentication); + } + + /** + * 处理登录成功方法 + *

+ * + * @param authenticationException 登录的authentication 对象 + * @param authentication 登录的authenticationException 对象 + */ + public abstract void handle(AuthenticationException authenticationException, Authentication authentication); +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/AuthenticationSuccessEventHandler.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/AuthenticationSuccessEventHandler.java new file mode 100755 index 00000000..7443f5e7 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/AuthenticationSuccessEventHandler.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.handler; + +import cn.hutool.core.collection.CollUtil; +import org.springframework.context.ApplicationListener; +import org.springframework.security.authentication.event.AuthenticationSuccessEvent; +import org.springframework.security.core.Authentication; + +/** + * @author lengleng + * @date 2019/2/1 + * 认证成功事件处理器 + */ +public abstract class AuthenticationSuccessEventHandler implements ApplicationListener { + /** + * Handle an application event. + * + * @param event the event to respond to + */ + @Override + public void onApplicationEvent(AuthenticationSuccessEvent event) { + Authentication authentication = (Authentication) event.getSource(); + if (CollUtil.isNotEmpty(authentication.getAuthorities())) { + handle(authentication); + } + } + + /** + * 处理登录成功方法 + *

+ * 获取到登录的authentication 对象 + * + * @param authentication 登录对象 + */ + public abstract void handle(Authentication authentication); +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/MobileLoginSuccessHandler.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/MobileLoginSuccessHandler.java new file mode 100755 index 00000000..5f91ad04 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/MobileLoginSuccessHandler.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.pig4cloud.pig.common.security.handler; + +import cn.hutool.core.map.MapUtil; +import cn.hutool.core.util.CharsetUtil; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.pig4cloud.pig.common.core.constant.CommonConstants; +import com.pig4cloud.pig.common.security.util.AuthUtils; +import lombok.Builder; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpHeaders; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.core.Authentication; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.oauth2.common.OAuth2AccessToken; +import org.springframework.security.oauth2.common.exceptions.InvalidClientException; +import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException; +import org.springframework.security.oauth2.provider.*; +import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestValidator; +import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +/** + * @author lengleng + * @date 2019/2/1 + * 手机号登录成功,返回oauth token + */ +@Slf4j +@Builder +public class MobileLoginSuccessHandler implements AuthenticationSuccessHandler { + private static final String BASIC_ = "Basic "; + private ObjectMapper objectMapper; + private PasswordEncoder passwordEncoder; + private ClientDetailsService clientDetailsService; + private AuthorizationServerTokenServices defaultAuthorizationServerTokenServices; + + /** + * Called when a user has been successfully authenticated. + * 调用spring security oauth API 生成 oAuth2AccessToken + * + * @param request the request which caused the successful authentication + * @param response the response + * @param authentication the Authentication object which was created during + */ + @Override + public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { + String header = request.getHeader(HttpHeaders.AUTHORIZATION); + + if (header == null || !header.startsWith(BASIC_)) { + throw new UnapprovedClientAuthenticationException("请求头中client信息为空"); + } + + try { + String[] tokens = AuthUtils.extractAndDecodeHeader(header); + assert tokens.length == 2; + String clientId = tokens[0]; + + ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId); + + //校验secret + if (!passwordEncoder.matches(tokens[1], clientDetails.getClientSecret())) { + throw new InvalidClientException("Given client ID does not match authenticated client"); + + } + + TokenRequest tokenRequest = new TokenRequest(MapUtil.newHashMap(), clientId, clientDetails.getScope(), "mobile"); + + //校验scope + new DefaultOAuth2RequestValidator().validateScope(tokenRequest, clientDetails); + OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails); + OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication); + OAuth2AccessToken oAuth2AccessToken = defaultAuthorizationServerTokenServices.createAccessToken(oAuth2Authentication); + log.info("获取token 成功:{}", oAuth2AccessToken.getValue()); + + response.setCharacterEncoding(CharsetUtil.UTF_8); + response.setContentType(CommonConstants.CONTENT_TYPE); + PrintWriter printWriter = response.getWriter(); + printWriter.append(objectMapper.writeValueAsString(oAuth2AccessToken)); + } catch (IOException e) { + throw new BadCredentialsException( + "Failed to decode basic authentication token"); + } + } + + +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/service/PigClientDetailsService.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/service/PigClientDetailsService.java new file mode 100755 index 00000000..fe8a5ec7 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/service/PigClientDetailsService.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.service; + +import com.pig4cloud.pig.common.core.constant.SecurityConstants; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.security.oauth2.common.exceptions.InvalidClientException; +import org.springframework.security.oauth2.provider.ClientDetails; +import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService; + +import javax.sql.DataSource; + +/** + * @author lengleng + * @date 2019/2/1 + *

+ * see JdbcClientDetailsService + */ +public class PigClientDetailsService extends JdbcClientDetailsService { + + public PigClientDetailsService(DataSource dataSource) { + super(dataSource); + } + + /** + * 重写原生方法支持redis缓存 + * + * @param clientId + * @return + * @throws InvalidClientException + */ + @Override + @Cacheable(value = SecurityConstants.CLIENT_DETAILS_KEY, key = "#clientId", unless = "#result == null") + public ClientDetails loadClientByClientId(String clientId) throws InvalidClientException { + return super.loadClientByClientId(clientId); + } +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/service/PigUser.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/service/PigUser.java new file mode 100755 index 00000000..8c38d57f --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/service/PigUser.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.service; + +import lombok.Getter; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.User; + +import java.util.Collection; + +/** + * @author lengleng + * @date 2019/2/1 + * 扩展用户信息 + */ +public class PigUser extends User { + /** + * 用户ID + */ + @Getter + private Integer id; + /** + * 部门ID + */ + @Getter + private Integer deptId; + + /** + * Construct the User with the details required by + * {@link DaoAuthenticationProvider}. + * + * @param id 用户ID + * @param deptId 部门ID + * @param username the username presented to the + * DaoAuthenticationProvider + * @param password the password that should be presented to the + * DaoAuthenticationProvider + * @param enabled set to true if the user is enabled + * @param accountNonExpired set to true if the account has not expired + * @param credentialsNonExpired set to true if the credentials have not + * expired + * @param accountNonLocked set to true if the account is not locked + * @param authorities the authorities that should be granted to the caller if they + * presented the correct username and password and the user is enabled. Not null. + * @throws IllegalArgumentException if a null value was passed either as + * a parameter or as an element in the GrantedAuthority collection + */ + public PigUser(Integer id, Integer deptId, String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection authorities) { + super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); + this.id = id; + this.deptId = deptId; + } +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/service/PigUserDetailsServiceImpl.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/service/PigUserDetailsServiceImpl.java new file mode 100755 index 00000000..0a5d43d9 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/service/PigUserDetailsServiceImpl.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.service; + +import cn.hutool.core.util.ArrayUtil; +import cn.hutool.core.util.StrUtil; +import com.pig4cloud.pig.admin.api.dto.UserInfo; +import com.pig4cloud.pig.admin.api.entity.SysUser; +import com.pig4cloud.pig.admin.api.feign.RemoteUserService; +import com.pig4cloud.pig.common.core.constant.CommonConstants; +import com.pig4cloud.pig.common.core.constant.SecurityConstants; +import com.pig4cloud.pig.common.core.util.R; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.AuthorityUtils; +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.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +/** + * 用户详细信息 + * + * @author lengleng + */ +@Slf4j +@Service +@AllArgsConstructor +public class PigUserDetailsServiceImpl implements UserDetailsService { + private final RemoteUserService remoteUserService; + private final CacheManager cacheManager; + + /** + * 用户密码登录 + * + * @param username 用户名 + * @return + * @throws UsernameNotFoundException + */ + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + Cache cache = cacheManager.getCache("user_details"); + if (cache != null && cache.get(username) != null) { + return (PigUser) cache.get(username).get(); + } + + R result = remoteUserService.info(username, SecurityConstants.FROM_IN); + UserDetails userDetails = getUserDetails(result); + cache.put(username, userDetails); + return userDetails; + } + + /** + * 构建userdetails + * + * @param result 用户信息 + * @return + */ + private UserDetails getUserDetails(R result) { + if (result == null || result.getData() == null) { + throw new UsernameNotFoundException("用户不存在"); + } + + UserInfo info = result.getData(); + Set dbAuthsSet = new HashSet<>(); + if (ArrayUtil.isNotEmpty(info.getRoles())) { + // 获取角色 + Arrays.stream(info.getRoles()).forEach(role -> dbAuthsSet.add(SecurityConstants.ROLE + role)); + // 获取资源 + dbAuthsSet.addAll(Arrays.asList(info.getPermissions())); + + } + Collection authorities + = AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0])); + SysUser user = info.getSysUser(); + + // 构造security用户 + return new PigUser(user.getUserId(), user.getDeptId(), user.getUsername(), SecurityConstants.BCRYPT + user.getPassword(), + StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL), true, true, true, authorities); + } +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/util/AuthUtils.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/util/AuthUtils.java new file mode 100755 index 00000000..567238a8 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/util/AuthUtils.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.util; + +import cn.hutool.core.codec.Base64; +import cn.hutool.core.util.CharsetUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpHeaders; + +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + +/** + * @author lengleng + * @date 2019/2/1 + * 认证授权相关工具类 + */ +@Slf4j +public class AuthUtils { + private static final String BASIC_ = "Basic "; + + /** + * 从header 请求中的clientId/clientsecect + * + * @param header header中的参数 + * @throws RuntimeException if the Basic header is not present or is not valid + * Base64 + */ + public static String[] extractAndDecodeHeader(String header) + throws IOException { + + byte[] base64Token = header.substring(6).getBytes("UTF-8"); + byte[] decoded; + try { + decoded = Base64.decode(base64Token); + } catch (IllegalArgumentException e) { + throw new RuntimeException( + "Failed to decode basic authentication token"); + } + + String token = new String(decoded, CharsetUtil.UTF_8); + + int delim = token.indexOf(":"); + + if (delim == -1) { + throw new RuntimeException("Invalid basic authentication token"); + } + return new String[]{token.substring(0, delim), token.substring(delim + 1)}; + } + + /** + * *从header 请求中的clientId/clientsecect + * + * @param request + * @return + * @throws IOException + */ + public static String[] extractAndDecodeHeader(HttpServletRequest request) + throws IOException { + String header = request.getHeader(HttpHeaders.AUTHORIZATION); + + if (header == null || !header.startsWith(BASIC_)) { + throw new RuntimeException("请求头中client信息为空"); + } + + return extractAndDecodeHeader(header); + } +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/util/SecurityUtils.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/util/SecurityUtils.java new file mode 100755 index 00000000..4da09b67 --- /dev/null +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/util/SecurityUtils.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.common.security.util; + + +import cn.hutool.core.util.StrUtil; +import com.pig4cloud.pig.common.core.constant.SecurityConstants; +import com.pig4cloud.pig.common.security.service.PigUser; +import lombok.experimental.UtilityClass; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * 安全工具类 + * + * @author L.cm + */ +@UtilityClass +public class SecurityUtils { + + /** + * 获取Authentication + */ + public static Authentication getAuthentication() { + return SecurityContextHolder.getContext().getAuthentication(); + } + + /** + * 获取用户 + */ + public PigUser getUser(Authentication authentication) { + Object principal = authentication.getPrincipal(); + if (principal instanceof PigUser) { + return (PigUser) principal; + } + return null; + } + + /** + * 获取用户 + */ + public PigUser getUser() { + Authentication authentication = getAuthentication(); + if (authentication == null) { + return null; + } + return getUser(authentication); + } + + /** + * 获取用户角色信息 + * + * @return 角色集合 + */ + public List getRoles() { + Authentication authentication = getAuthentication(); + Collection authorities = authentication.getAuthorities(); + + List roleIds = new ArrayList<>(); + authorities.stream() + .filter(granted -> StrUtil.startWith(granted.getAuthority(), SecurityConstants.ROLE)) + .forEach(granted -> { + String id = StrUtil.removePrefix(granted.getAuthority(), SecurityConstants.ROLE); + roleIds.add(Integer.parseInt(id)); + }); + return roleIds; + } +} diff --git a/pig-common/pig-common-security/src/main/resources/META-INF/spring.factories b/pig-common/pig-common-security/src/main/resources/META-INF/spring.factories new file mode 100755 index 00000000..8b0ebb6e --- /dev/null +++ b/pig-common/pig-common-security/src/main/resources/META-INF/spring.factories @@ -0,0 +1,7 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ + com.pig4cloud.pig.common.security.component.PermissionService,\ + com.pig4cloud.pig.common.security.component.PigAccessDeniedHandler,\ + com.pig4cloud.pig.common.security.component.ResourceAuthExceptionEntryPoint,\ + com.pig4cloud.pig.common.security.component.PigResourceServerTokenRelayAutoConfiguration,\ + com.pig4cloud.pig.common.security.feign.PigFeignClientConfiguration,\ + com.pig4cloud.pig.common.security.service.PigUserDetailsServiceImpl diff --git a/pig-common/pig-common-security/src/main/resources/org/springframework/security/messages_zh_CN.properties b/pig-common/pig-common-security/src/main/resources/org/springframework/security/messages_zh_CN.properties new file mode 100755 index 00000000..1a851941 --- /dev/null +++ b/pig-common/pig-common-security/src/main/resources/org/springframework/security/messages_zh_CN.properties @@ -0,0 +1,62 @@ +# +# Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). +#

+# Licensed under the GNU Lesser General Public License 3.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +#

+# https://www.gnu.org/licenses/lgpl.html +#

+# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +AbstractAccessDecisionManager.accessDenied=\u4E0D\u5141\u8BB8\u8BBF\u95EE +AbstractLdapAuthenticationProvider.emptyPassword=\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A +AbstractSecurityInterceptor.authenticationNotFound=\u672A\u5728SecurityContext\u4E2D\u67E5\u627E\u5230\u8BA4\u8BC1\u5BF9\u8C61 +AbstractUserDetailsAuthenticationProvider.badCredentials=\u7528\u6237\u540D\u4E0D\u5B58\u5728\u6216\u8005\u5BC6\u7801\u9519\u8BEF +AbstractUserDetailsAuthenticationProvider.noopBindAccount=\u672A\u7ED1\u5B9A\u767B\u5F55\u8D26\u53F7\uFF0C\u8BF7\u4F7F\u7528\u5BC6\u7801\u767B\u5F55\u540E\u7ED1\u5B9A +AbstractUserDetailsAuthenticationProvider.credentialsExpired=\u7528\u6237\u51ED\u8BC1\u5DF2\u8FC7\u671F +AbstractUserDetailsAuthenticationProvider.disabled=\u7528\u6237\u672A\u6FC0\u6D3B +AbstractUserDetailsAuthenticationProvider.expired=\u7528\u6237\u5E10\u53F7\u5DF2\u8FC7\u671F +AbstractUserDetailsAuthenticationProvider.locked=\u7528\u6237\u5E10\u53F7\u5DF2\u88AB\u9501\u5B9A +AbstractUserDetailsAuthenticationProvider.onlySupports=\u4EC5\u4EC5\u652F\u6301UsernamePasswordAuthenticationToken +AccountStatusUserDetailsChecker.credentialsExpired=\u7528\u6237\u51ED\u8BC1\u5DF2\u8FC7\u671F +AccountStatusUserDetailsChecker.disabled=\u7528\u6237\u672A\u6FC0\u6D3B +AccountStatusUserDetailsChecker.expired=\u7528\u6237\u5E10\u53F7\u5DF2\u8FC7\u671F +AccountStatusUserDetailsChecker.locked=\u7528\u6237\u5E10\u53F7\u5DF2\u88AB\u9501\u5B9A +AclEntryAfterInvocationProvider.noPermission=\u7ED9\u5B9A\u7684Authentication\u5BF9\u8C61({0})\u6839\u672C\u65E0\u6743\u64CD\u63A7\u9886\u57DF\u5BF9\u8C61({1}) +AnonymousAuthenticationProvider.incorrectKey=\u5C55\u793A\u7684AnonymousAuthenticationToken\u4E0D\u542B\u6709\u9884\u671F\u7684key +BindAuthenticator.badCredentials=\u5BC6\u7801\u9519\u8BEF +BindAuthenticator.emptyPassword=\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A +CasAuthenticationProvider.incorrectKey=\u5C55\u793A\u7684CasAuthenticationToken\u4E0D\u542B\u6709\u9884\u671F\u7684key +CasAuthenticationProvider.noServiceTicket=\u672A\u80FD\u591F\u6B63\u786E\u63D0\u4F9B\u5F85\u9A8C\u8BC1\u7684CAS\u670D\u52A1\u7968\u6839 +ConcurrentSessionControlAuthenticationStrategy.exceededAllowed=\u5DF2\u7ECF\u8D85\u8FC7\u4E86\u5F53\u524D\u4E3B\u4F53({0})\u88AB\u5141\u8BB8\u7684\u6700\u5927\u4F1A\u8BDD\u6570\u91CF +DigestAuthenticationFilter.incorrectRealm=\u54CD\u5E94\u7ED3\u679C\u4E2D\u7684Realm\u540D\u5B57({0})\u540C\u7CFB\u7EDF\u6307\u5B9A\u7684Realm\u540D\u5B57({1})\u4E0D\u543B\u5408 +DigestAuthenticationFilter.incorrectResponse=\u9519\u8BEF\u7684\u54CD\u5E94\u7ED3\u679C +DigestAuthenticationFilter.missingAuth=\u9057\u6F0F\u4E86\u9488\u5BF9'auth' QOP\u7684\u3001\u5FC5\u987B\u7ED9\u5B9A\u7684\u6458\u8981\u53D6\u503C; \u63A5\u6536\u5230\u7684\u5934\u4FE1\u606F\u4E3A{0} +DigestAuthenticationFilter.missingMandatory=\u9057\u6F0F\u4E86\u5FC5\u987B\u7ED9\u5B9A\u7684\u6458\u8981\u53D6\u503C; \u63A5\u6536\u5230\u7684\u5934\u4FE1\u606F\u4E3A{0} +DigestAuthenticationFilter.nonceCompromised=Nonce\u4EE4\u724C\u5DF2\u7ECF\u5B58\u5728\u95EE\u9898\u4E86\uFF0C{0} +DigestAuthenticationFilter.nonceEncoding=Nonce\u672A\u7ECF\u8FC7Base64\u7F16\u7801; \u76F8\u5E94\u7684nonce\u53D6\u503C\u4E3A {0} +DigestAuthenticationFilter.nonceExpired=Nonce\u5DF2\u7ECF\u8FC7\u671F/\u8D85\u65F6 +DigestAuthenticationFilter.nonceNotNumeric=Nonce\u4EE4\u724C\u7684\u7B2C1\u90E8\u5206\u5E94\u8BE5\u662F\u6570\u5B57\uFF0C\u4F46\u7ED3\u679C\u5374\u662F{0} +DigestAuthenticationFilter.nonceNotTwoTokens=Nonce\u5E94\u8BE5\u7531\u4E24\u90E8\u5206\u53D6\u503C\u6784\u6210\uFF0C\u4F46\u7ED3\u679C\u5374\u662F{0} +DigestAuthenticationFilter.usernameNotFound=\u7528\u6237\u540D{0}\u672A\u627E\u5230 +JdbcDaoImpl.noAuthority=\u6CA1\u6709\u4E3A\u7528\u6237{0}\u6307\u5B9A\u89D2\u8272 +JdbcDaoImpl.notFound=\u672A\u627E\u5230\u7528\u6237{0} +LdapAuthenticationProvider.badCredentials=\u574F\u7684\u51ED\u8BC1 +LdapAuthenticationProvider.credentialsExpired=\u7528\u6237\u51ED\u8BC1\u5DF2\u8FC7\u671F +LdapAuthenticationProvider.disabled=\u7528\u6237\u672A\u6FC0\u6D3B +LdapAuthenticationProvider.expired=\u7528\u6237\u5E10\u53F7\u5DF2\u8FC7\u671F +LdapAuthenticationProvider.locked=\u7528\u6237\u5E10\u53F7\u5DF2\u88AB\u9501\u5B9A +LdapAuthenticationProvider.emptyUsername=\u7528\u6237\u540D\u4E0D\u5141\u8BB8\u4E3A\u7A7A +LdapAuthenticationProvider.onlySupports=\u4EC5\u4EC5\u652F\u6301UsernamePasswordAuthenticationToken +PasswordComparisonAuthenticator.badCredentials=\u574F\u7684\u51ED\u8BC1 +ProviderManager.providerNotFound=\u672A\u67E5\u627E\u5230\u9488\u5BF9{0}\u7684AuthenticationProvider +RememberMeAuthenticationProvider.incorrectKey=\u5C55\u793ARememberMeAuthenticationToken\u4E0D\u542B\u6709\u9884\u671F\u7684key +RunAsImplAuthenticationProvider.incorrectKey=\u5C55\u793A\u7684RunAsUserToken\u4E0D\u542B\u6709\u9884\u671F\u7684key +SubjectDnX509PrincipalExtractor.noMatching=\u672A\u5728subjectDN\: {0}\u4E2D\u627E\u5230\u5339\u914D\u7684\u6A21\u5F0F +SwitchUserFilter.noCurrentUser=\u4E0D\u5B58\u5728\u5F53\u524D\u7528\u6237 +SwitchUserFilter.noOriginalAuthentication=\u4E0D\u80FD\u591F\u67E5\u627E\u5230\u539F\u5148\u7684\u5DF2\u8BA4\u8BC1\u5BF9\u8C61 diff --git a/pig-common/pom.xml b/pig-common/pom.xml new file mode 100755 index 00000000..3553d352 --- /dev/null +++ b/pig-common/pom.xml @@ -0,0 +1,37 @@ + + + + + 4.0.0 + + com.pig4cloud + pig + ${pig.version} + + + pig-common + pom + + pig 公共聚合模块 + + + pig-common-core + pig-common-log + pig-common-security + + diff --git a/pig-config/Dockerfile b/pig-config/Dockerfile new file mode 100755 index 00000000..258b05cd --- /dev/null +++ b/pig-config/Dockerfile @@ -0,0 +1,15 @@ +FROM anapsix/alpine-java:8_server-jre_unlimited + +MAINTAINER wangiegie@gmail.com + +RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime + +RUN mkdir -p /pig-config + +WORKDIR /pig-config + +EXPOSE 4001 + +ADD ./pig-config/target/pig-config.jar ./ + +CMD java -Djava.security.egd=file:/dev/./urandom -jar pig-config.jar diff --git a/pig-config/pom.xml b/pig-config/pom.xml new file mode 100755 index 00000000..a5ebd975 --- /dev/null +++ b/pig-config/pom.xml @@ -0,0 +1,71 @@ + + + + + 4.0.0 + + com.pig4cloud + pig + ${pig.version} + + + pig-config + jar + + pig 配置中心,基于spring cloud config + + + + + org.springframework.cloud + spring-cloud-config-server + + + + org.springframework.boot + spring-boot-starter-web + + + + spring-boot-starter-tomcat + org.springframework.boot + + + + + + org.springframework.boot + spring-boot-starter-undertow + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.spotify + docker-maven-plugin + + + + + diff --git a/pig-config/src/main/java/com/pig4cloud/pig/config/PigConfigApplication.java b/pig-config/src/main/java/com/pig4cloud/pig/config/PigConfigApplication.java new file mode 100755 index 00000000..856208f9 --- /dev/null +++ b/pig-config/src/main/java/com/pig4cloud/pig/config/PigConfigApplication.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.cloud.client.SpringCloudApplication; +import org.springframework.cloud.config.server.EnableConfigServer; + +/** + * @author lengleng + * @date 2018年06月22日 + * 配置中心 + */ +@EnableConfigServer +@SpringCloudApplication +public class PigConfigApplication { + + public static void main(String[] args) { + SpringApplication.run(PigConfigApplication.class, args); + } +} diff --git a/pig-config/src/main/resources/banner.txt b/pig-config/src/main/resources/banner.txt new file mode 100755 index 00000000..63be6e1e --- /dev/null +++ b/pig-config/src/main/resources/banner.txt @@ -0,0 +1,16 @@ +${AnsiColor.BRIGHT_YELLOW} + + ::::::::: ::::::::::: :::::::: ::: ::: + :+: :+: :+: :+: :+: :+: :+: + +:+ +:+ +:+ +:+ +:+ +:+ + +#++:++#+ +#+ :#: +#++:+ + +#+ +#+ +#+ +#+# +#+ +#+ + #+# #+# #+# #+# #+# #+# + ### ########### ######## ### ### + + www.pig4cloud.com + + Pig Microservice Architecture + + + diff --git a/pig-config/src/main/resources/bootstrap.yml b/pig-config/src/main/resources/bootstrap.yml new file mode 100755 index 00000000..822c7b88 --- /dev/null +++ b/pig-config/src/main/resources/bootstrap.yml @@ -0,0 +1,29 @@ +server: + port: 8888 + +spring: + application: + name: pig-config + profiles: + active: native + # 配置中心 + cloud: + config: + server: + native: + search-locations: classpath:/config/ + +# 注册中心配置 +eureka: + instance: + prefer-ip-address: true + client: + service-url: + defaultZone: http://pig:pig@pig-eureka:8761/eureka/ + +# 暴露监控端点 +management: + endpoints: + web: + exposure: + include: '*' diff --git a/pig-config/src/main/resources/config/application-dev.yml b/pig-config/src/main/resources/config/application-dev.yml new file mode 100755 index 00000000..d19c4187 --- /dev/null +++ b/pig-config/src/main/resources/config/application-dev.yml @@ -0,0 +1,76 @@ +# 加解密根密码 +jasypt: + encryptor: + password: pig #根密码 + +# Spring 相关 +spring: + redis: + password: + host: pig-redis + jackson: + time-zone: GMT+8 + date-format: yyyy-MM-dd HH:mm:ss + +# 暴露监控端点 +management: + endpoints: + web: + exposure: + include: '*' + +# feign 配置 +feign: + hystrix: + enabled: true + okhttp: + enabled: true + httpclient: + enabled: false + client: + config: + default: + connectTimeout: 10000 + readTimeout: 10000 + compression: + request: + enabled: true + response: + enabled: true + +# hystrix 配置 +hystrix: + command: + default: + execution: + isolation: + strategy: SEMAPHORE + thread: + timeoutInMilliseconds: 60000 + shareSecurityContext: true + +#请求处理的超时时间 +ribbon: + ReadTimeout: 10000 + ConnectTimeout: 10000 + +# mybaits-plus配置 +mybatis-plus: + mapper-locations: classpath:/mapper/*Mapper.xml + global-config: + banner: false + db-config: + id-type: 0 + field-strategy: 1 + table-underline: true + logic-delete-value: 1 + logic-not-delete-value: 0 + configuration: + map-underscore-to-camel-case: true + +# spring security 配置 +security: + oauth2: + resource: + loadBalanced: true + token-info-uri: http://pig-auth/oauth/check_token diff --git a/pig-config/src/main/resources/config/pig-auth-dev.yml b/pig-config/src/main/resources/config/pig-auth-dev.yml new file mode 100755 index 00000000..74c68d85 --- /dev/null +++ b/pig-config/src/main/resources/config/pig-auth-dev.yml @@ -0,0 +1,8 @@ +# 数据源 +spring: + datasource: + type: com.zaxxer.hikari.HikariDataSource + driver-class-name: com.mysql.jdbc.Driver + username: root + password: root + url: jdbc:mysql://pig-mysql:3306/pig?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai diff --git a/pig-config/src/main/resources/config/pig-codegen-dev.yml b/pig-config/src/main/resources/config/pig-codegen-dev.yml new file mode 100755 index 00000000..de7c0e35 --- /dev/null +++ b/pig-config/src/main/resources/config/pig-codegen-dev.yml @@ -0,0 +1,23 @@ +## spring security 配置 +security: + oauth2: + client: + client-id: ENC(27v1agvAug87ANOVnbKdsw==) + client-secret: ENC(VbnkopxrwgbFVKp+UxJ2pg==) + scope: server + +# 数据源配置 +spring: + datasource: + type: com.zaxxer.hikari.HikariDataSource + driver-class-name: com.mysql.jdbc.Driver + username: root + password: root + url: jdbc:mysql://pig-mysql:3306/pig?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai + resources: + static-locations: classpath:/static/,classpath:/views/ + +# 直接放行URL +ignore: + urls: + - /actuator/** diff --git a/pig-config/src/main/resources/config/pig-gateway-dev.yml b/pig-config/src/main/resources/config/pig-gateway-dev.yml new file mode 100755 index 00000000..85f7533b --- /dev/null +++ b/pig-config/src/main/resources/config/pig-gateway-dev.yml @@ -0,0 +1,44 @@ +spring: + cloud: + gateway: + locator: + enabled: true + routes: + # 认证中心 + - id: pig-auth + uri: lb://pig-auth + predicates: + - Path=/auth/** + filters: + # 验证码处理 + - ImageCodeGatewayFilter + # 前端密码解密 + - PasswordDecoderFilter + #UPMS 模块 + - id: pig-upms + uri: lb://pig-upms + predicates: + - Path=/admin/** + filters: + # 限流配置 + - name: RequestRateLimiter + args: + key-resolver: '#{@remoteAddrKeyResolver}' + redis-rate-limiter.replenishRate: 10 + redis-rate-limiter.burstCapacity: 20 + # 降级配置 + - name: Hystrix + args: + name: default + fallbackUri: 'forward:/fallback' + # 代码生成模块 + - id: pig-codegen + uri: lb://pig-codegen + predicates: + - Path=/gen/** + + +security: + encode: + # 前端密码密钥,必须16位 + key: 'thanks,pig4cloud' diff --git a/pig-config/src/main/resources/config/pig-monitor-dev.yml b/pig-config/src/main/resources/config/pig-monitor-dev.yml new file mode 100755 index 00000000..b5d23192 --- /dev/null +++ b/pig-config/src/main/resources/config/pig-monitor-dev.yml @@ -0,0 +1,6 @@ +spring: + # 安全配置 + security: + user: + name: ENC(8Hk2ILNJM8UTOuW/Xi75qg==) # pig + password: ENC(o6cuPFfUevmTbkmBnE67Ow====) # pig diff --git a/pig-config/src/main/resources/config/pig-upms-dev.yml b/pig-config/src/main/resources/config/pig-upms-dev.yml new file mode 100755 index 00000000..0d705e0f --- /dev/null +++ b/pig-config/src/main/resources/config/pig-upms-dev.yml @@ -0,0 +1,22 @@ +security: + oauth2: + client: + client-id: ENC(imENTO7M8bLO38LFSIxnzw==) + client-secret: ENC(i3cDFhs26sa2Ucrfz2hnQw==) + scope: server + +# 数据源 +spring: + datasource: + type: com.zaxxer.hikari.HikariDataSource + driver-class-name: com.mysql.jdbc.Driver + username: root + password: root + url: jdbc:mysql://pig-mysql:3306/pig?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai + +# 直接放行URL +ignore: + urls: + - /actuator/** + - /user/info/* + - /log/** diff --git a/pig-config/src/main/resources/logback-spring.xml b/pig-config/src/main/resources/logback-spring.xml new file mode 100755 index 00000000..70ea9fa5 --- /dev/null +++ b/pig-config/src/main/resources/logback-spring.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + ${CONSOLE_LOG_PATTERN} + + + + + + ${log.path}/debug.log + + ${log.path}/%d{yyyy-MM, aux}/debug.%d{yyyy-MM-dd}.%i.log.gz + 50MB + 30 + + + %date [%thread] %-5level [%logger{50}] %file:%line - %msg%n + + + + + + ${log.path}/error.log + + ${log.path}/%d{yyyy-MM}/error.%d{yyyy-MM-dd}.%i.log.gz + 50MB + 30 + + + %date [%thread] %-5level [%logger{50}] %file:%line - %msg%n + + + ERROR + + + + + + + + + + diff --git a/pig-eureka/Dockerfile b/pig-eureka/Dockerfile new file mode 100755 index 00000000..622b0c00 --- /dev/null +++ b/pig-eureka/Dockerfile @@ -0,0 +1,15 @@ +FROM anapsix/alpine-java:8_server-jre_unlimited + +MAINTAINER wangiegie@gmail.com + +RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime + +RUN mkdir -p /pig-eureka + +WORKDIR /pig-eureka + +EXPOSE 8761 + +ADD ./pig-eureka/target/pig-eureka.jar ./ + +CMD java -Djava.security.egd=file:/dev/./urandom -jar pig-eureka.jar diff --git a/pig-eureka/pom.xml b/pig-eureka/pom.xml new file mode 100755 index 00000000..fc9bb410 --- /dev/null +++ b/pig-eureka/pom.xml @@ -0,0 +1,80 @@ + + + + + 4.0.0 + + com.pig4cloud + pig + ${pig.version} + + + pig-eureka + jar + + pig 服务中心,基于eureka + + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-server + + + + org.springframework.cloud + spring-cloud-starter-security + + + + org.springframework.cloud + spring-cloud-starter-config + + + + org.springframework.boot + spring-boot-starter-web + + + + spring-boot-starter-tomcat + org.springframework.boot + + + + + + org.springframework.boot + spring-boot-starter-undertow + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.spotify + docker-maven-plugin + + + + + diff --git a/pig-eureka/src/main/java/com/pig4cloud/pig/eureka/PigEurekaApplication.java b/pig-eureka/src/main/java/com/pig4cloud/pig/eureka/PigEurekaApplication.java new file mode 100755 index 00000000..55b88f10 --- /dev/null +++ b/pig-eureka/src/main/java/com/pig4cloud/pig/eureka/PigEurekaApplication.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.eureka; + + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; + +/** + * @author lengleng + * @date 2018年06月21日 + * 服务中心 + */ +@EnableEurekaServer +@SpringBootApplication +public class PigEurekaApplication { + + public static void main(String[] args) { + SpringApplication.run(PigEurekaApplication.class, args); + } +} diff --git a/pig-eureka/src/main/java/com/pig4cloud/pig/eureka/security/WebSecurityConfig.java b/pig-eureka/src/main/java/com/pig4cloud/pig/eureka/security/WebSecurityConfig.java new file mode 100755 index 00000000..98598162 --- /dev/null +++ b/pig-eureka/src/main/java/com/pig4cloud/pig/eureka/security/WebSecurityConfig.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.eureka.security; + +/** + * @author lengleng + * @date 2019/2/1 + */ + +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.WebSecurityConfigurerAdapter; + +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable() + .authorizeRequests() + .antMatchers("/actuator/**").permitAll() + .anyRequest() + .authenticated().and().httpBasic(); + } +} diff --git a/pig-eureka/src/main/resources/banner.txt b/pig-eureka/src/main/resources/banner.txt new file mode 100755 index 00000000..63be6e1e --- /dev/null +++ b/pig-eureka/src/main/resources/banner.txt @@ -0,0 +1,16 @@ +${AnsiColor.BRIGHT_YELLOW} + + ::::::::: ::::::::::: :::::::: ::: ::: + :+: :+: :+: :+: :+: :+: :+: + +:+ +:+ +:+ +:+ +:+ +:+ + +#++:++#+ +#+ :#: +#++:+ + +#+ +#+ +#+ +#+# +#+ +#+ + #+# #+# #+# #+# #+# #+# + ### ########### ######## ### ### + + www.pig4cloud.com + + Pig Microservice Architecture + + + diff --git a/pig-eureka/src/main/resources/bootstrap.yml b/pig-eureka/src/main/resources/bootstrap.yml new file mode 100755 index 00000000..74ff0751 --- /dev/null +++ b/pig-eureka/src/main/resources/bootstrap.yml @@ -0,0 +1,35 @@ +server: + port: 8761 + +spring: + security: + user: + name: pig + password: pig + application: + name: pig-eureka + cloud: + config: + enabled: false + +# docker-compose部署时候 hostname 换成pig-eureka +# 类似的 redis 使用pig-redis ,gateway 换成 pig-gateway +eureka: + instance: + hostname: pig-eureka + prefer-ip-address: true + client: + register-with-eureka: false + fetch-registry: false + service-url: + defaultZone: http://pig:pig@${eureka.instance.hostname}:${server.port}/eureka/ + server: + eviction-interval-timer-in-ms: 4000 + enable-self-preservation: false + renewal-percent-threshold: 0.9 + +management: + endpoints: + web: + exposure: + include: '*' diff --git a/pig-eureka/src/main/resources/logback-spring.xml b/pig-eureka/src/main/resources/logback-spring.xml new file mode 100755 index 00000000..fd3233e9 --- /dev/null +++ b/pig-eureka/src/main/resources/logback-spring.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + ${CONSOLE_LOG_PATTERN} + + + + + + ${log.path}/debug.log + + ${log.path}/%d{yyyy-MM, aux}/debug.%d{yyyy-MM-dd}.%i.log.gz + 50MB + 30 + + + %date [%thread] %-5level [%logger{50}] %file:%line - %msg%n + + + + + + ${log.path}/error.log + + ${log.path}/%d{yyyy-MM}/error.%d{yyyy-MM-dd}.%i.log.gz + 50MB + 30 + + + %date [%thread] %-5level [%logger{50}] %file:%line - %msg%n + + + ERROR + + + + + + + + + + diff --git a/pig-gateway/Dockerfile b/pig-gateway/Dockerfile new file mode 100755 index 00000000..c967e938 --- /dev/null +++ b/pig-gateway/Dockerfile @@ -0,0 +1,15 @@ +FROM anapsix/alpine-java:8_server-jre_unlimited + +MAINTAINER wangiegie@gmail.com + +RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime + +RUN mkdir -p /pig-gateway + +WORKDIR /pig-gateway + +EXPOSE 9999 + +ADD ./pig-gateway/target/pig-gateway.jar ./ + +CMD java -Djava.security.egd=file:/dev/./urandom -jar pig-gateway.jar diff --git a/pig-gateway/pom.xml b/pig-gateway/pom.xml new file mode 100755 index 00000000..fde75b5a --- /dev/null +++ b/pig-gateway/pom.xml @@ -0,0 +1,74 @@ + + + + + 4.0.0 + + com.pig4cloud + pig + ${pig.version} + + + pig-gateway + jar + + pig 服务网关,基于 spring cloud gateway + + + + + org.springframework.cloud + spring-cloud-starter-gateway + + + org.springframework.boot + spring-boot-starter-data-redis-reactive + + + + org.springframework.cloud + spring-cloud-starter-config + + + + com.github.axet + kaptcha + ${kaptcha.version} + + + + com.pig4cloud + pig-common-core + ${pig.version} + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.spotify + docker-maven-plugin + + + + + diff --git a/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/PigGatewayApplication.java b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/PigGatewayApplication.java new file mode 100755 index 00000000..b3167554 --- /dev/null +++ b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/PigGatewayApplication.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.gateway; + + +import org.springframework.boot.SpringApplication; +import org.springframework.cloud.client.SpringCloudApplication; + +/** + * @author lengleng + * @date 2018年06月21日 + *

+ * 网关应用 + */ +@SpringCloudApplication +public class PigGatewayApplication { + + public static void main(String[] args) { + SpringApplication.run(PigGatewayApplication.class, args); + } +} diff --git a/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/config/KaptchaConfiguration.java b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/config/KaptchaConfiguration.java new file mode 100755 index 00000000..4a822dc0 --- /dev/null +++ b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/config/KaptchaConfiguration.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.gateway.config; + +import com.google.code.kaptcha.impl.DefaultKaptcha; +import com.google.code.kaptcha.util.Config; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.Properties; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@Configuration +public class KaptchaConfiguration { + + private static final String KAPTCHA_BORDER = "kaptcha.border"; + private static final String KAPTCHA_TEXTPRODUCER_FONT_COLOR = "kaptcha.textproducer.font.color"; + private static final String KAPTCHA_TEXTPRODUCER_CHAR_SPACE = "kaptcha.textproducer.char.space"; + private static final String KAPTCHA_IMAGE_WIDTH = "kaptcha.image.width"; + private static final String KAPTCHA_IMAGE_HEIGHT = "kaptcha.image.height"; + private static final String KAPTCHA_TEXTPRODUCER_CHAR_LENGTH = "kaptcha.textproducer.char.length"; + private static final Object KAPTCHA_IMAGE_FONT_SIZE = "kaptcha.textproducer.font.size"; + + /** + * 默认生成图形验证码宽度 + */ + private static final String DEFAULT_IMAGE_WIDTH = "100"; + + /** + * 默认生成图像验证码高度 + */ + private static final String DEFAULT_IMAGE_HEIGHT = "40"; + + /** + * 默认生成图形验证码长度 + */ + private static final String DEFAULT_IMAGE_LENGTH = "4"; + /** + * 边框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue. + */ + private static final String DEFAULT_COLOR_FONT = "black"; + + /** + * 图片边框 + */ + private static final String DEFAULT_IMAGE_BORDER = "no"; + /** + * 默认图片间隔 + */ + private static final String DEFAULT_CHAR_SPACE = "5"; + /** + * 验证码文字大小 + */ + private static final String DEFAULT_IMAGE_FONT_SIZE = "30"; + + @Bean + public DefaultKaptcha producer() { + Properties properties = new Properties(); + properties.put(KAPTCHA_BORDER, DEFAULT_IMAGE_BORDER); + properties.put(KAPTCHA_TEXTPRODUCER_FONT_COLOR, DEFAULT_COLOR_FONT); + properties.put(KAPTCHA_TEXTPRODUCER_CHAR_SPACE, DEFAULT_CHAR_SPACE); + properties.put(KAPTCHA_IMAGE_WIDTH, DEFAULT_IMAGE_WIDTH); + properties.put(KAPTCHA_IMAGE_HEIGHT, DEFAULT_IMAGE_HEIGHT); + properties.put(KAPTCHA_IMAGE_FONT_SIZE, DEFAULT_IMAGE_FONT_SIZE); + properties.put(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, DEFAULT_IMAGE_LENGTH); + Config config = new Config(properties); + DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); + defaultKaptcha.setConfig(config); + return defaultKaptcha; + } +} diff --git a/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/config/RateLimiterConfiguration.java b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/config/RateLimiterConfiguration.java new file mode 100755 index 00000000..d642289e --- /dev/null +++ b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/config/RateLimiterConfiguration.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.gateway.config; + +import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import reactor.core.publisher.Mono; + +/** + * @author lengleng + * @date 2019/2/1 + * 路由限流配置 + */ +@Configuration +public class RateLimiterConfiguration { + @Bean(value = "remoteAddrKeyResolver") + public KeyResolver remoteAddrKeyResolver() { + return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress()); + } +} diff --git a/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/config/RouterFunctionConfiguration.java b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/config/RouterFunctionConfiguration.java new file mode 100755 index 00000000..2d7f44a3 --- /dev/null +++ b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/config/RouterFunctionConfiguration.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.gateway.config; + +import com.pig4cloud.pig.gateway.handler.HystrixFallbackHandler; +import com.pig4cloud.pig.gateway.handler.ImageCodeHandler; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.MediaType; +import org.springframework.web.reactive.function.server.RequestPredicates; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; + +/** + * @author lengleng + * @date 2019/2/1 + * 路由配置信息 + */ +@Slf4j +@Configuration +@AllArgsConstructor +public class RouterFunctionConfiguration { + private final HystrixFallbackHandler hystrixFallbackHandler; + private final ImageCodeHandler imageCodeHandler; + + @Bean + public RouterFunction routerFunction() { + return RouterFunctions.route( + RequestPredicates.path("/fallback") + .and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), hystrixFallbackHandler) + .andRoute(RequestPredicates.GET("/code") + .and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), imageCodeHandler); + + } + +} diff --git a/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/filter/ImageCodeGatewayFilter.java b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/filter/ImageCodeGatewayFilter.java new file mode 100755 index 00000000..bf02c87d --- /dev/null +++ b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/filter/ImageCodeGatewayFilter.java @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.gateway.filter; + +import cn.hutool.core.codec.Base64; +import cn.hutool.core.util.CharsetUtil; +import cn.hutool.core.util.StrUtil; +import com.pig4cloud.pig.common.core.exception.CheckedException; +import com.pig4cloud.pig.common.core.exception.ValidateCodeException; +import com.pig4cloud.pig.common.core.config.FilterIgnorePropertiesConfig; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.gateway.filter.GatewayFilter; +import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.http.server.reactive.ServerHttpResponse; +import org.springframework.stereotype.Component; + +import java.io.IOException; + +/** + * @author lengleng + * @date 2019/2/1 + * 验证码处理 + */ +@Slf4j +@Component +public class ImageCodeGatewayFilter extends AbstractGatewayFilterFactory { + public static final String DEFAULT_CODE_KEY = "DEFAULT_CODE_KEY"; + public static final String OAUTH_TOKEN_URL = "/oauth/token"; + private static final String BASIC_ = "Basic "; + @Autowired + private RedisTemplate redisTemplate; + @Autowired + private FilterIgnorePropertiesConfig filterIgnorePropertiesConfig; + + /** + * 从header 请求中的clientId/clientsecect + * + * @param header header中的参数 + * @throws CheckedException if the Basic header is not present or is not valid + * Base64 + */ + public static String[] extractAndDecodeHeader(String header) + throws IOException, CheckedException { + + byte[] base64Token = header.substring(6).getBytes("UTF-8"); + byte[] decoded; + try { + decoded = Base64.decode(base64Token); + } catch (IllegalArgumentException e) { + throw new CheckedException( + "Failed to decode basic authentication token"); + } + + String token = new String(decoded, CharsetUtil.UTF_8); + + int delim = token.indexOf(":"); + + if (delim == -1) { + throw new CheckedException("Invalid basic authentication token"); + } + return new String[]{token.substring(0, delim), token.substring(delim + 1)}; + } + + /** + * *从header 请求中的clientId/clientsecect + * + * @param request + * @return + * @throws IOException + */ + public static String[] extractAndDecodeHeader(ServerHttpRequest request) + throws IOException, CheckedException { + String header = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION); + + if (header == null || !header.startsWith(BASIC_)) { + throw new CheckedException("请求头中client信息为空"); + } + + return extractAndDecodeHeader(header); + } + + @Override + public GatewayFilter apply(Object config) { + return (exchange, chain) -> { + ServerHttpRequest request = exchange.getRequest(); + + // 不是登录请求,直接向下执行 + if (!StrUtil.containsAnyIgnoreCase(request.getURI().getPath(), OAUTH_TOKEN_URL)) { + return chain.filter(exchange); + } + + // 终端设置不校验, 直接向下执行(1. 从请求参数中获取 2.从header取) + String clientId = request.getQueryParams().getFirst("client_id"); + if (StrUtil.isNotBlank(clientId)) { + if (filterIgnorePropertiesConfig.getClients().contains(clientId)) { + return chain.filter(exchange); + } + } + try { + String[] clientInfos = extractAndDecodeHeader(request); + if (filterIgnorePropertiesConfig.getClients().contains(clientInfos[0])) { + return chain.filter(exchange); + } + } catch (Exception e) { + ServerHttpResponse response = exchange.getResponse(); + response.setStatusCode(HttpStatus.PRECONDITION_REQUIRED); + return response.setComplete(); + } + + //校验验证码合法性 + try { + checkCode(request); + } catch (ValidateCodeException e) { + ServerHttpResponse response = exchange.getResponse(); + response.setStatusCode(HttpStatus.PRECONDITION_REQUIRED); + return response.setComplete(); + } + + return chain.filter(exchange); + }; + } + + /** + * 检查code + * + * @param request + * @throws ValidateCodeException 校验异常 + */ + private void checkCode(ServerHttpRequest request) throws ValidateCodeException { + String code = request.getQueryParams().getFirst("code"); + + if (StrUtil.isBlank(code)) { + throw new ValidateCodeException(); + } + + String randomStr = request.getQueryParams().getFirst("randomStr"); + if (StrUtil.isBlank(randomStr)) { + throw new ValidateCodeException(); + } + + String key = DEFAULT_CODE_KEY + randomStr; + if (!redisTemplate.hasKey(key)) { + throw new ValidateCodeException(); + } + + Object codeObj = redisTemplate.opsForValue().get(key); + + if (codeObj == null) { + throw new ValidateCodeException(); + } + + String saveCode = codeObj.toString(); + if (StrUtil.isBlank(saveCode)) { + redisTemplate.delete(key); + throw new ValidateCodeException(); + } + + if (!StrUtil.equals(saveCode, code)) { + redisTemplate.delete(key); + throw new ValidateCodeException(); + } + + redisTemplate.delete(key); + } +} diff --git a/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/filter/PasswordDecoderFilter.java b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/filter/PasswordDecoderFilter.java new file mode 100755 index 00000000..8a58cfc7 --- /dev/null +++ b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/filter/PasswordDecoderFilter.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.gateway.filter; + +import cn.hutool.core.codec.Base64; +import cn.hutool.core.util.CharsetUtil; +import cn.hutool.core.util.StrUtil; +import cn.hutool.crypto.Mode; +import cn.hutool.crypto.Padding; +import cn.hutool.crypto.symmetric.AES; +import cn.hutool.http.HttpUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.gateway.filter.GatewayFilter; +import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.stereotype.Component; +import org.springframework.web.util.UriComponentsBuilder; +import reactor.core.publisher.Mono; + +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.Map; + +/** + * @author lengleng + * @date 2019/2/1 + * 密码解密工具类 + */ +@Slf4j +@Component +public class PasswordDecoderFilter extends AbstractGatewayFilterFactory { + private static final String PASSWORD = "password"; + private static final String KEY_ALGORITHM = "AES"; + @Value("${security.encode.key:1234567812345678}") + private String encodeKey; + + private static String decryptAES(String data, String pass) throws Exception { + AES aes = new AES(Mode.CBC, Padding.NoPadding, + new SecretKeySpec(pass.getBytes(), KEY_ALGORITHM), + new IvParameterSpec(pass.getBytes())); + byte[] result = aes.decrypt(Base64.decode(data.getBytes(StandardCharsets.UTF_8))); + return new String(result, StandardCharsets.UTF_8); + } + + @Override + public GatewayFilter apply(Object config) { + return (exchange, chain) -> { + ServerHttpRequest request = exchange.getRequest(); + + // 不是登录请求,直接向下执行 + if (!StrUtil.containsAnyIgnoreCase(request.getURI().getPath(), ImageCodeGatewayFilter.OAUTH_TOKEN_URL)) { + return chain.filter(exchange); + } + + URI uri = exchange.getRequest().getURI(); + String queryParam = uri.getRawQuery(); + Map paramMap = HttpUtil.decodeParamMap(queryParam, CharsetUtil.UTF_8); + + String password = paramMap.get(PASSWORD); + if (StrUtil.isNotBlank(password)) { + try { + password = decryptAES(password, encodeKey); + } catch (Exception e) { + log.error("密码解密失败:{}", password); + return Mono.error(e); + } + paramMap.put(PASSWORD, password.trim()); + } + + URI newUri = UriComponentsBuilder.fromUri(uri) + .replaceQuery(HttpUtil.toParams(paramMap)) + .build(true) + .toUri(); + + ServerHttpRequest newRequest = exchange.getRequest().mutate().uri(newUri).build(); + return chain.filter(exchange.mutate().request(newRequest).build()); + }; + } +} diff --git a/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/filter/PigRequestGlobalFilter.java b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/filter/PigRequestGlobalFilter.java new file mode 100755 index 00000000..e85c4d72 --- /dev/null +++ b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/filter/PigRequestGlobalFilter.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.gateway.filter; + +import com.pig4cloud.pig.common.core.constant.SecurityConstants; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.cloud.gateway.filter.GlobalFilter; +import org.springframework.core.Ordered; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +import java.util.Arrays; +import java.util.stream.Collectors; + +import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR; +import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl; + +/** + * @author lengleng + * @date 2019/2/1 + *

+ * 全局拦截器,作用所有的微服务 + *

+ * 1. 对请求头中参数进行处理 from 参数进行清洗 + * 2. 重写StripPrefix = 1,支持全局 + *

+ * 支持swagger添加X-Forwarded-Prefix header (F SR2 已经支持,不需要自己维护) + */ +@Component +public class PigRequestGlobalFilter implements GlobalFilter, Ordered { + private static final String HEADER_NAME = "X-Forwarded-Prefix"; + + /** + * Process the Web request and (optionally) delegate to the next + * {@code WebFilter} through the given {@link GatewayFilterChain}. + * + * @param exchange the current server exchange + * @param chain provides a way to delegate to the next filter + * @return {@code Mono} to indicate when request processing is complete + */ + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + // 1. 清洗请求头中from 参数 + ServerHttpRequest request = exchange.getRequest().mutate() + .headers(httpHeaders -> httpHeaders.remove(SecurityConstants.FROM)) + .build(); + + // 2. 重写StripPrefix + addOriginalRequestUrl(exchange, request.getURI()); + String rawPath = request.getURI().getRawPath(); + String newPath = "/" + Arrays.stream(StringUtils.tokenizeToStringArray(rawPath, "/")) + .skip(1L).collect(Collectors.joining("/")); + ServerHttpRequest newRequest = request.mutate() + .path(newPath) + .build(); + exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI()); + + return chain.filter(exchange.mutate() + .request(newRequest.mutate() + .build()).build()); + } + + @Override + public int getOrder() { + return -1000; + } +} diff --git a/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/handler/HystrixFallbackHandler.java b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/handler/HystrixFallbackHandler.java new file mode 100755 index 00000000..ba3f4167 --- /dev/null +++ b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/handler/HystrixFallbackHandler.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.gateway.handler; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.server.HandlerFunction; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; +import reactor.core.publisher.Mono; + +import java.util.Optional; + +import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR; + +/** + * @author lengleng + * @date 2019/2/1 + * Hystrix 降级处理 + */ +@Slf4j +@Component +public class HystrixFallbackHandler implements HandlerFunction { + @Override + public Mono handle(ServerRequest serverRequest) { + Optional originalUris = serverRequest.attribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR); + + originalUris.ifPresent(originalUri -> log.error("网关执行请求:{}失败,hystrix服务降级处理", originalUri)); + + return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR.value()) + .contentType(MediaType.TEXT_PLAIN).body(BodyInserters.fromObject("服务异常")); + } +} diff --git a/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/handler/ImageCodeHandler.java b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/handler/ImageCodeHandler.java new file mode 100755 index 00000000..0620b581 --- /dev/null +++ b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/handler/ImageCodeHandler.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.gateway.handler; + +import com.google.code.kaptcha.Producer; +import com.pig4cloud.pig.gateway.filter.ImageCodeGatewayFilter; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.util.FastByteArrayOutputStream; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.server.HandlerFunction; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; +import reactor.core.publisher.Mono; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +/** + * @author lengleng + * @date 2019/2/1 + * 验证码生成逻辑处理类 + */ +@Slf4j +@Component +@AllArgsConstructor +public class ImageCodeHandler implements HandlerFunction { + private final Producer producer; + private final RedisTemplate redisTemplate; + + @Override + public Mono handle(ServerRequest serverRequest) { + //生成验证码 + String text = producer.createText(); + BufferedImage image = producer.createImage(text); + + //保存验证码信息 + String randomStr = serverRequest.queryParam("randomStr").get(); + redisTemplate.opsForValue().set(ImageCodeGatewayFilter.DEFAULT_CODE_KEY + randomStr, text, 60, TimeUnit.SECONDS); + + // 转换流信息写出 + FastByteArrayOutputStream os = new FastByteArrayOutputStream(); + try { + ImageIO.write(image, "jpeg", os); + } catch (IOException e) { + log.error("ImageIO write err", e); + return Mono.error(e); + } + + return ServerResponse + .status(HttpStatus.OK) + .contentType(MediaType.IMAGE_JPEG) + .body(BodyInserters.fromResource(new ByteArrayResource(os.toByteArray()))); + } +} diff --git a/pig-gateway/src/main/resources/bootstrap.yml b/pig-gateway/src/main/resources/bootstrap.yml new file mode 100755 index 00000000..8e65621e --- /dev/null +++ b/pig-gateway/src/main/resources/bootstrap.yml @@ -0,0 +1,27 @@ +server: + port: 9999 + +spring: + application: + name: pig-gateway + # 配置中心 + cloud: + config: + fail-fast: true + name: ${spring.application.name} + profile: ${spring.profiles.active} + discovery: + enabled: true + service-id: pig-config + profiles: + active: dev + +# 注册中心 +eureka: + instance: + prefer-ip-address: true + client: + service-url: + defaultZone: http://pig:pig@pig-eureka:8761/eureka/ + + diff --git a/pig-upms/pig-upms-api/pom.xml b/pig-upms/pig-upms-api/pom.xml new file mode 100755 index 00000000..75a2c365 --- /dev/null +++ b/pig-upms/pig-upms-api/pom.xml @@ -0,0 +1,41 @@ + + + + + 4.0.0 + + com.pig4cloud + pig-upms + ${pig.version} + + + pig-upms-api + jar + + pig 通用用户权限管理系统公共api模块 + + + + + + com.pig4cloud + pig-common-core + ${pig.version} + + + diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/dto/DeptTree.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/dto/DeptTree.java new file mode 100644 index 00000000..7429e2b6 --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/dto/DeptTree.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.dto; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * @author lengleng + * @date 2019/2/1 + * 部门树 + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class DeptTree extends TreeNode { + private String name; +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/dto/MenuTree.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/dto/MenuTree.java new file mode 100644 index 00000000..f089e779 --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/dto/MenuTree.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.dto; + +import com.pig4cloud.pig.admin.api.vo.MenuVO; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * @author lengleng + * @date 2017年11月9日23:33:27 + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class MenuTree extends TreeNode { + private String icon; + private String name; + private boolean spread = false; + private String path; + private String component; + private String authority; + private String redirect; + private String keepAlive; + private String code; + private String type; + private String label; + private Integer sort; + + public MenuTree() { + } + + public MenuTree(int id, String name, int parentId) { + this.id = id; + this.parentId = parentId; + this.name = name; + this.label = name; + } + + public MenuTree(int id, String name, MenuTree parent) { + this.id = id; + this.parentId = parent.getId(); + this.name = name; + this.label = name; + } + + public MenuTree(MenuVO menuVo) { + this.id = menuVo.getMenuId(); + this.parentId = menuVo.getParentId(); + this.icon = menuVo.getIcon(); + this.name = menuVo.getName(); + this.path = menuVo.getPath(); + this.component = menuVo.getComponent(); + this.type = menuVo.getType(); + this.label = menuVo.getName(); + this.sort = menuVo.getSort(); + this.keepAlive = menuVo.getKeepAlive(); + } +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/dto/RoleDTO.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/dto/RoleDTO.java new file mode 100755 index 00000000..55c0c036 --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/dto/RoleDTO.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.dto; + +import com.pig4cloud.pig.admin.api.entity.SysRole; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * @author lengleng + * @date 2019/2/1 + * 角色Dto + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class RoleDTO extends SysRole { + /** + * 角色部门Id + */ + private Integer roleDeptId; + + /** + * 部门名称 + */ + private String deptName; +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/dto/TreeNode.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/dto/TreeNode.java new file mode 100644 index 00000000..32040cad --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/dto/TreeNode.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.dto; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author lengleng + * @date 2017年11月9日23:33:45 + */ +@Data +public class TreeNode { + protected int id; + protected int parentId; + protected List children = new ArrayList(); + + public void add(TreeNode node) { + children.add(node); + } +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/dto/UserDTO.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/dto/UserDTO.java new file mode 100644 index 00000000..3748af15 --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/dto/UserDTO.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.dto; + +import com.pig4cloud.pig.admin.api.entity.SysUser; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.List; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class UserDTO extends SysUser { + /** + * 角色ID + */ + private List role; + + private Integer deptId; + + /** + * 新密码 + */ + private String newpassword1; +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/dto/UserInfo.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/dto/UserInfo.java new file mode 100644 index 00000000..99c23030 --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/dto/UserInfo.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.dto; + +import com.pig4cloud.pig.admin.api.entity.SysUser; +import lombok.Data; + +import java.io.Serializable; + +/** + * @author lengleng + * @date 2019/2/1 + *

+ * commit('SET_ROLES', data) + * commit('SET_NAME', data) + * commit('SET_AVATAR', data) + * commit('SET_INTRODUCTION', data) + * commit('SET_PERMISSIONS', data) + */ +@Data +public class UserInfo implements Serializable { + /** + * 用户基本信息 + */ + private SysUser sysUser; + /** + * 权限标识集合 + */ + private String[] permissions; + + /** + * 角色集合 + */ + private Integer[] roles; +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysDept.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysDept.java new file mode 100644 index 00000000..29af9373 --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysDept.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.extension.activerecord.Model; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import javax.validation.constraints.NotBlank; +import java.time.LocalDateTime; + +/** + *

+ * 部门管理 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class SysDept extends Model { + + private static final long serialVersionUID = 1L; + + @TableId(value = "dept_id", type = IdType.AUTO) + private Integer deptId; + /** + * 部门名称 + */ + @NotBlank(message = "部门名称不能为空") + private String name; + /** + * 排序 + */ + private Integer sort; + /** + * 创建时间 + */ + private LocalDateTime createTime; + /** + * 修改时间 + */ + private LocalDateTime updateTime; + + private Integer parentId; + + /** + * 是否删除 -1:已删除 0:正常 + */ + @TableLogic + private String delFlag; + +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysDeptRelation.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysDeptRelation.java new file mode 100644 index 00000000..ce9b62c2 --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysDeptRelation.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.entity; + +import com.baomidou.mybatisplus.extension.activerecord.Model; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + *

+ * 部门关系表 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class SysDeptRelation extends Model { + + private static final long serialVersionUID = 1L; + + /** + * 祖先节点 + */ + private Integer ancestor; + /** + * 后代节点 + */ + private Integer descendant; + + +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysDict.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysDict.java new file mode 100644 index 00000000..c747eb1a --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysDict.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.extension.activerecord.Model; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import javax.validation.constraints.NotBlank; +import java.time.LocalDateTime; + +/** + *

+ * 字典表 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class SysDict extends Model { + + private static final long serialVersionUID = 1L; + + /** + * 编号 + */ + @TableId(value = "id", type = IdType.AUTO) + private Integer id; + /** + * 数据值 + */ + @NotBlank(message = "字典项数据值不能为空") + private String value; + /** + * 标签名 + */ + @NotBlank(message = "字典项标签不能为空") + private String label; + /** + * 类型 + */ + @NotBlank(message = "字典项数据类型不能为空") + private String type; + /** + * 描述 + */ + private String description; + /** + * 排序(升序) + */ + private Integer sort; + /** + * 创建时间 + */ + private LocalDateTime createTime; + /** + * 更新时间 + */ + private LocalDateTime updateTime; + /** + * 备注信息 + */ + private String remarks; + /** + * 删除标记 + */ + @TableLogic + private String delFlag; + +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysLog.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysLog.java new file mode 100644 index 00000000..7b5e221c --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysLog.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableLogic; +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + *

+ * 日志表 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Data +public class SysLog implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 编号 + */ + @TableId(value = "id", type = IdType.AUTO) + private Long id; + /** + * 日志类型 + */ + @NotBlank(message = "日志类型不能为空") + private String type; + /** + * 日志标题 + */ + @NotBlank(message = "日志标题不能为空") + private String title; + /** + * 创建者 + */ + private String createBy; + /** + * 创建时间 + */ + private LocalDateTime createTime; + /** + * 更新时间 + */ + private LocalDateTime updateTime; + /** + * 操作IP地址 + */ + private String remoteAddr; + /** + * 用户代理 + */ + private String userAgent; + /** + * 请求URI + */ + private String requestUri; + /** + * 操作方式 + */ + private String method; + /** + * 操作提交的数据 + */ + private String params; + /** + * 执行时间 + */ + private Long time; + + /** + * 异常信息 + */ + private String exception; + + /** + * 服务ID + */ + private String serviceId; + + /** + * 删除标记 + */ + @TableLogic + private String delFlag; + + + +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysMenu.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysMenu.java new file mode 100644 index 00000000..6acf5e25 --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysMenu.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.extension.activerecord.Model; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.time.LocalDateTime; + +/** + *

+ * 菜单权限表 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class SysMenu extends Model { + + private static final long serialVersionUID = 1L; + + /** + * 菜单ID + */ + @NotNull(message = "菜单ID不能为空") + @TableId(value = "menu_id", type = IdType.INPUT) + private Integer menuId; + /** + * 菜单名称 + */ + @NotBlank(message = "菜单名称不能为空") + private String name; + /** + * 菜单权限标识 + */ + private String permission; + /** + * 父菜单ID + */ + @NotNull(message = "菜单父ID不能为空") + private Integer parentId; + /** + * 图标 + */ + private String icon; + /** + * VUE页面 + */ + private String component; + /** + * 排序值 + */ + private Integer sort; + /** + * 菜单类型 (0菜单 1按钮) + */ + @NotNull(message = "菜单类型不能为空") + private String type; + /** + * 路由缓冲 + */ + private String keepAlive; + /** + * 创建时间 + */ + private LocalDateTime createTime; + /** + * 更新时间 + */ + private LocalDateTime updateTime; + /** + * 0--正常 1--删除 + */ + @TableLogic + private String delFlag; + /** + * 前端URL + */ + private String path; + + +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysOauthClientDetails.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysOauthClientDetails.java new file mode 100644 index 00000000..7635c1bc --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysOauthClientDetails.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.extension.activerecord.Model; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import javax.validation.constraints.NotBlank; +import java.io.Serializable; + +/** + *

+ * 客户端信息 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class SysOauthClientDetails extends Model { + + private static final long serialVersionUID = 1L; + + /** + * 客户端ID + */ + @NotBlank(message = "client_id 不能为空") + @TableId(value = "client_id", type = IdType.INPUT) + private String clientId; + + /** + * 客户端密钥 + */ + @NotBlank(message = "client_secret 不能为空") + private String clientSecret; + + /** + * 资源ID + */ + private String resourceIds; + + /** + * 作用域 + */ + @NotBlank(message = "scope 不能为空") + private String scope; + + /** + * 授权方式(A,B,C) + */ + private String authorizedGrantTypes; + + private String webServerRedirectUri; + + private String authorities; + + /** + * 请求令牌有效时间 + */ + private Integer accessTokenValidity; + + /** + * 刷新令牌有效时间 + */ + private Integer refreshTokenValidity; + + /** + * 扩展信息 + */ + private String additionalInformation; + + /** + * 是否自动放行 + */ + private String autoapprove; + + @Override + protected Serializable pkVal() { + return this.clientId; + } + +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysRole.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysRole.java new file mode 100644 index 00000000..17e4424a --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysRole.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.extension.activerecord.Model; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + *

+ * 角色表 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class SysRole extends Model { + + private static final long serialVersionUID = 1L; + + @TableId(value = "role_id", type = IdType.AUTO) + private Integer roleId; + + @NotBlank(message = "角色名称 不能为空") + private String roleName; + + @NotBlank(message = "角色标识 不能为空") + private String roleCode; + + @NotBlank(message = "角色描述 不能为空") + private String roleDesc; + + @NotNull(message = "数据权限类型 不能为空") + private Integer dsType; + + private String dsScope; + + private LocalDateTime createTime; + private LocalDateTime updateTime; + /** + * 删除标识(0-正常,1-删除) + */ + @TableLogic + private String delFlag; + + @Override + protected Serializable pkVal() { + return this.roleId; + } + +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysRoleDept.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysRoleDept.java new file mode 100755 index 00000000..8aee767f --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysRoleDept.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.baomidou.mybatisplus.extension.activerecord.Model; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + *

+ * 角色与部门对应关系 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("sys_role_dept") +public class SysRoleDept extends Model { + + private static final long serialVersionUID = 1L; + + @TableId(value = "id", type = IdType.AUTO) + private Integer id; + /** + * 角色ID + */ + private Integer roleId; + /** + * 部门ID + */ + private Integer deptId; + +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysRoleMenu.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysRoleMenu.java new file mode 100644 index 00000000..8646411f --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysRoleMenu.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.entity; + +import com.baomidou.mybatisplus.extension.activerecord.Model; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + *

+ * 角色菜单表 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class SysRoleMenu extends Model { + + private static final long serialVersionUID = 1L; + + /** + * 角色ID + */ + private Integer roleId; + /** + * 菜单ID + */ + private Integer menuId; +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysUser.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysUser.java new file mode 100644 index 00000000..0103c89c --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysUser.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; + +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + *

+ * 用户表 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Data +public class SysUser implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 主键ID + */ + @TableId(value = "user_id", type = IdType.AUTO) + private Integer userId; + /** + * 用户名 + */ + private String username; + + private String password; + /** + * 随机盐 + */ + @JsonIgnore + private String salt; + /** + * 创建时间 + */ + private LocalDateTime createTime; + /** + * 修改时间 + */ + private LocalDateTime updateTime; + /** + * 0-正常,1-删除 + */ + @TableLogic + private String delFlag; + + /** + * 锁定标记 + */ + private String lockFlag; + + /** + * 简介 + */ + private String phone; + /** + * 头像 + */ + private String avatar; + + /** + * 部门ID + */ + private Integer deptId; + + /** + * 微信openid + */ + private String wxOpenid; + + /** + * QQ openid + */ + private String qqOpenid; + +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysUserRole.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysUserRole.java new file mode 100644 index 00000000..397b484a --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/entity/SysUserRole.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.entity; + +import com.baomidou.mybatisplus.extension.activerecord.Model; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + *

+ * 用户角色表 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class SysUserRole extends Model { + + private static final long serialVersionUID = 1L; + + /** + * 用户ID + */ + private Integer userId; + /** + * 角色ID + */ + private Integer roleId; + +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/RemoteLogService.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/RemoteLogService.java new file mode 100755 index 00000000..03e0fa04 --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/RemoteLogService.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.feign; + +import com.pig4cloud.pig.admin.api.entity.SysLog; +import com.pig4cloud.pig.admin.api.feign.factory.RemoteLogServiceFallbackFactory; +import com.pig4cloud.pig.common.core.constant.ServiceNameConstants; +import com.pig4cloud.pig.common.core.util.R; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@FeignClient(value = ServiceNameConstants.UMPS_SERVICE, fallbackFactory = RemoteLogServiceFallbackFactory.class) +public interface RemoteLogService { + /** + * 保存日志 + * + * @param sysLog 日志实体 + * @return succes、false + */ + @PostMapping("/log") + R saveLog(@RequestBody SysLog sysLog); +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/RemoteTokenService.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/RemoteTokenService.java new file mode 100755 index 00000000..3f262f50 --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/RemoteTokenService.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.feign; + +import com.pig4cloud.pig.admin.api.feign.factory.RemoteTokenServiceFallbackFactory; +import com.pig4cloud.pig.common.core.constant.SecurityConstants; +import com.pig4cloud.pig.common.core.constant.ServiceNameConstants; +import com.pig4cloud.pig.common.core.util.R; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@FeignClient(value = ServiceNameConstants.AUTH_SERVICE, fallbackFactory = RemoteTokenServiceFallbackFactory.class) +public interface RemoteTokenService { + /** + * 分页查询token 信息 + * + * @param params 分页参数 + * @param from 内部调用标志 + * @return page + */ + @PostMapping("/oauth/listToken") + R selectPage(@RequestBody Map params, @RequestHeader(SecurityConstants.FROM) String from); + + /** + * 删除token + * + * @param token token + * @param from 调用标志 + * @return + */ + @DeleteMapping("/oauth/delToken/{token}") + R deleteTokenById(@PathVariable("token") String token, @RequestHeader(SecurityConstants.FROM) String from); +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/RemoteUserService.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/RemoteUserService.java new file mode 100755 index 00000000..d6f3dd9e --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/RemoteUserService.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.feign; + +import com.pig4cloud.pig.admin.api.feign.factory.RemoteUserServiceFallbackFactory; +import com.pig4cloud.pig.admin.api.dto.UserInfo; +import com.pig4cloud.pig.common.core.constant.SecurityConstants; +import com.pig4cloud.pig.common.core.constant.ServiceNameConstants; +import com.pig4cloud.pig.common.core.util.R; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@FeignClient(value = ServiceNameConstants.UMPS_SERVICE, fallbackFactory = RemoteUserServiceFallbackFactory.class) +public interface RemoteUserService { + /** + * 通过用户名查询用户、角色信息 + * + * @param username 用户名 + * @param from 调用标志 + * @return R + */ + @GetMapping("/user/info/{username}") + R info(@PathVariable("username") String username + , @RequestHeader(SecurityConstants.FROM) String from); + + /** + * 通过社交账号查询用户、角色信息 + * + * @param inStr appid@code + * @return + */ + @GetMapping("/social/info/{inStr}") + R social(@PathVariable("inStr") String inStr); +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/factory/RemoteLogServiceFallbackFactory.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/factory/RemoteLogServiceFallbackFactory.java new file mode 100755 index 00000000..1f408fa8 --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/factory/RemoteLogServiceFallbackFactory.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.feign.factory; + +import com.pig4cloud.pig.admin.api.feign.fallback.RemoteLogServiceFallbackImpl; +import com.pig4cloud.pig.admin.api.feign.RemoteLogService; +import feign.hystrix.FallbackFactory; +import org.springframework.stereotype.Component; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@Component +public class RemoteLogServiceFallbackFactory implements FallbackFactory { + + @Override + public RemoteLogService create(Throwable throwable) { + RemoteLogServiceFallbackImpl remoteLogServiceFallback = new RemoteLogServiceFallbackImpl(); + remoteLogServiceFallback.setCause(throwable); + return remoteLogServiceFallback; + } +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/factory/RemoteTokenServiceFallbackFactory.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/factory/RemoteTokenServiceFallbackFactory.java new file mode 100755 index 00000000..4139fbe0 --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/factory/RemoteTokenServiceFallbackFactory.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.feign.factory; + +import com.pig4cloud.pig.admin.api.feign.fallback.RemoteTokenServiceFallbackImpl; +import com.pig4cloud.pig.admin.api.feign.RemoteTokenService; +import feign.hystrix.FallbackFactory; +import org.springframework.stereotype.Component; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@Component +public class RemoteTokenServiceFallbackFactory implements FallbackFactory { + + @Override + public RemoteTokenService create(Throwable throwable) { + RemoteTokenServiceFallbackImpl remoteTokenServiceFallback = new RemoteTokenServiceFallbackImpl(); + remoteTokenServiceFallback.setCause(throwable); + return remoteTokenServiceFallback; + } +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/factory/RemoteUserServiceFallbackFactory.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/factory/RemoteUserServiceFallbackFactory.java new file mode 100755 index 00000000..78d99110 --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/factory/RemoteUserServiceFallbackFactory.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.feign.factory; + +import com.pig4cloud.pig.admin.api.feign.fallback.RemoteUserServiceFallbackImpl; +import com.pig4cloud.pig.admin.api.feign.RemoteUserService; +import feign.hystrix.FallbackFactory; +import org.springframework.stereotype.Component; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@Component +public class RemoteUserServiceFallbackFactory implements FallbackFactory { + + @Override + public RemoteUserService create(Throwable throwable) { + RemoteUserServiceFallbackImpl remoteUserServiceFallback = new RemoteUserServiceFallbackImpl(); + remoteUserServiceFallback.setCause(throwable); + return remoteUserServiceFallback; + } +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/fallback/RemoteLogServiceFallbackImpl.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/fallback/RemoteLogServiceFallbackImpl.java new file mode 100755 index 00000000..3e237a49 --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/fallback/RemoteLogServiceFallbackImpl.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.feign.fallback; + +import com.pig4cloud.pig.admin.api.entity.SysLog; +import com.pig4cloud.pig.admin.api.feign.RemoteLogService; +import com.pig4cloud.pig.common.core.util.R; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@Slf4j +@Component +public class RemoteLogServiceFallbackImpl implements RemoteLogService { + @Setter + private Throwable cause; + + /** + * 保存日志 + * + * @param sysLog + * @return R + */ + @Override + public R saveLog(SysLog sysLog) { + log.error("feign 插入日志失败", cause); + return null; + } +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/fallback/RemoteTokenServiceFallbackImpl.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/fallback/RemoteTokenServiceFallbackImpl.java new file mode 100755 index 00000000..3581ad9f --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/fallback/RemoteTokenServiceFallbackImpl.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.feign.fallback; + +import com.pig4cloud.pig.admin.api.feign.RemoteTokenService; +import com.pig4cloud.pig.common.core.util.R; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import java.util.Map; + +/** + * @author lengleng + * @date 2019/2/1 + * feign token fallback + */ +@Slf4j +@Component +public class RemoteTokenServiceFallbackImpl implements RemoteTokenService { + @Setter + private Throwable cause; + + /** + * 分页查询token 信息 + * + * @param params 分页参数 + * @param from 内部调用标志 + * @return page + */ + @Override + public R selectPage(Map params, String from) { + log.error("调用认证中心查询token 失败", cause); + return null; + } + + /** + * 删除token + * + * + * @param s + * @param id + * @return + */ + @Override + public R deleteTokenById(String s, String id) { + log.error("删除token 失败 {}", id, cause); + return null; + } +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/fallback/RemoteUserServiceFallbackImpl.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/fallback/RemoteUserServiceFallbackImpl.java new file mode 100755 index 00000000..8bcff8b6 --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/feign/fallback/RemoteUserServiceFallbackImpl.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.feign.fallback; + +import com.pig4cloud.pig.admin.api.dto.UserInfo; +import com.pig4cloud.pig.admin.api.feign.RemoteUserService; +import com.pig4cloud.pig.common.core.util.R; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@Slf4j +@Component +public class RemoteUserServiceFallbackImpl implements RemoteUserService { + @Setter + private Throwable cause; + + /** + * 通过用户名查询用户、角色信息 + * + * @param username 用户名 + * @param from 内外标志 + * @return R + */ + @Override + public R info(String username, String from) { + log.error("feign 查询用户信息失败:{}", username, cause); + return null; + } + + /** + * 通过社交账号查询用户、角色信息 + * + * @param inStr appid@code + * @return + */ + @Override + public R social(String inStr) { + log.error("feign 查询用户信息失败:{}", inStr, cause); + return null; + } +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/ImageCode.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/ImageCode.java new file mode 100644 index 00000000..1f76a3a2 --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/ImageCode.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.vo; + +import lombok.Data; + +import java.awt.image.BufferedImage; +import java.io.Serializable; +import java.time.LocalDateTime; + + +/** + * @author lengleng + * @date 2019/2/1 + */ +@Data +public class ImageCode implements Serializable { + private String code; + + private LocalDateTime expireTime; + + private BufferedImage image; + + public ImageCode(BufferedImage image, String sRand, int defaultImageExpire) { + this.image = image; + this.code = sRand; + this.expireTime = LocalDateTime.now().plusSeconds(defaultImageExpire); + } +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/LogVO.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/LogVO.java new file mode 100644 index 00000000..a638f74d --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/LogVO.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.vo; + +import com.pig4cloud.pig.admin.api.entity.SysLog; +import lombok.Data; + +import java.io.Serializable; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@Data +public class LogVO implements Serializable { + private static final long serialVersionUID = 1L; + + private SysLog sysLog; + private String username; +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/MenuVO.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/MenuVO.java new file mode 100644 index 00000000..f407579f --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/MenuVO.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.vo; + +import lombok.Data; + +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + *

+ * 菜单权限表 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Data +public class MenuVO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 菜单ID + */ + private Integer menuId; + /** + * 菜单名称 + */ + private String name; + /** + * 菜单权限标识 + */ + private String permission; + /** + * 父菜单ID + */ + private Integer parentId; + /** + * 图标 + */ + private String icon; + /** + * 一个路径 + */ + private String path; + /** + * VUE页面 + */ + private String component; + /** + * 排序值 + */ + private Integer sort; + /** + * 菜单类型 (0菜单 1按钮) + */ + private String type; + /** + * 是否缓冲 + */ + private String keepAlive; + /** + * 创建时间 + */ + private LocalDateTime createTime; + /** + * 更新时间 + */ + private LocalDateTime updateTime; + /** + * 0--正常 1--删除 + */ + private String delFlag; + + + @Override + public int hashCode() { + return menuId.hashCode(); + } + + /** + * menuId 相同则相同 + * + * @param obj + * @return + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof MenuVO) { + Integer targetMenuId = ((MenuVO) obj).getMenuId(); + return menuId.equals(targetMenuId); + } + return super.equals(obj); + } +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/PreLogVo.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/PreLogVo.java new file mode 100644 index 00000000..98d42e38 --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/PreLogVo.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.vo; + +import lombok.Data; + +/** + * @author lengleng + * @date 2018/8/27 + * 前端日志vo + */ +@Data +public class PreLogVo { + private String url; + private String time; + private String user; + private String type; + private String message; + private String stack; + private String info; +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/TreeUtil.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/TreeUtil.java new file mode 100644 index 00000000..34f414fa --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/TreeUtil.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.vo; + + +import com.pig4cloud.pig.admin.api.dto.MenuTree; +import com.pig4cloud.pig.admin.api.dto.TreeNode; +import com.pig4cloud.pig.admin.api.entity.SysMenu; +import lombok.experimental.UtilityClass; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author lengleng + * @date 2017年11月9日23:34:11 + */ +@UtilityClass +public class TreeUtil { + /** + * 两层循环实现建树 + * + * @param treeNodes 传入的树节点列表 + * @return + */ + public List bulid(List treeNodes, Object root) { + + List trees = new ArrayList<>(); + + for (T treeNode : treeNodes) { + + if (root.equals(treeNode.getParentId())) { + trees.add(treeNode); + } + + for (T it : treeNodes) { + if (it.getParentId() == treeNode.getId()) { + if (treeNode.getChildren() == null) { + treeNode.setChildren(new ArrayList<>()); + } + treeNode.add(it); + } + } + } + return trees; + } + + /** + * 使用递归方法建树 + * + * @param treeNodes + * @return + */ + public List buildByRecursive(List treeNodes, Object root) { + List trees = new ArrayList(); + for (T treeNode : treeNodes) { + if (root.equals(treeNode.getParentId())) { + trees.add(findChildren(treeNode, treeNodes)); + } + } + return trees; + } + + /** + * 递归查找子节点 + * + * @param treeNodes + * @return + */ + public T findChildren(T treeNode, List treeNodes) { + for (T it : treeNodes) { + if (treeNode.getId() == it.getParentId()) { + if (treeNode.getChildren() == null) { + treeNode.setChildren(new ArrayList<>()); + } + treeNode.add(findChildren(it, treeNodes)); + } + } + return treeNode; + } + + /** + * 通过sysMenu创建树形节点 + * + * @param menus + * @param root + * @return + */ + public List bulidTree(List menus, int root) { + List trees = new ArrayList<>(); + MenuTree node; + for (SysMenu menu : menus) { + node = new MenuTree(); + node.setId(menu.getMenuId()); + node.setParentId(menu.getParentId()); + node.setName(menu.getName()); + node.setPath(menu.getPath()); + node.setCode(menu.getPermission()); + node.setLabel(menu.getName()); + node.setComponent(menu.getComponent()); + node.setIcon(menu.getIcon()); + node.setKeepAlive(menu.getKeepAlive()); + trees.add(node); + } + return TreeUtil.bulid(trees, root); + } +} diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/UserVO.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/UserVO.java new file mode 100644 index 00000000..d8014f43 --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/UserVO.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.api.vo; + +import com.pig4cloud.pig.admin.api.entity.SysRole; +import lombok.Data; + +import java.io.Serializable; +import java.time.LocalDateTime; +import java.util.List; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@Data +public class UserVO implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 主键ID + */ + private Integer userId; + /** + * 用户名 + */ + private String username; + /** + * 密码 + */ + private String password; + /** + * 随机盐 + */ + private String salt; + + /** + * 微信openid + */ + private String wxOpenid; + + /** + * QQ openid + */ + private String qqOpenid; + + /** + * 创建时间 + */ + private LocalDateTime createTime; + /** + * 修改时间 + */ + private LocalDateTime updateTime; + /** + * 0-正常,1-删除 + */ + private String delFlag; + + /** + * 锁定标记 + */ + private String lockFlag; + /** + * 简介 + */ + private String phone; + /** + * 头像 + */ + private String avatar; + + /** + * 部门ID + */ + private Integer deptId; + + /** + * 部门名称 + */ + private String deptName; + + /** + * 角色列表 + */ + private List roleList; +} diff --git a/pig-upms/pig-upms-api/src/main/resources/META-INF/spring.factories b/pig-upms/pig-upms-api/src/main/resources/META-INF/spring.factories new file mode 100755 index 00000000..8ed59881 --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/resources/META-INF/spring.factories @@ -0,0 +1,7 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ + com.pig4cloud.pig.admin.api.feign.fallback.RemoteUserServiceFallbackImpl,\ + com.pig4cloud.pig.admin.api.feign.fallback.RemoteLogServiceFallbackImpl,\ + com.pig4cloud.pig.admin.api.feign.fallback.RemoteTokenServiceFallbackImpl,\ + com.pig4cloud.pig.admin.api.feign.factory.RemoteUserServiceFallbackFactory,\ + com.pig4cloud.pig.admin.api.feign.factory.RemoteLogServiceFallbackFactory,\ + com.pig4cloud.pig.admin.api.feign.factory.RemoteTokenServiceFallbackFactory diff --git a/pig-upms/pig-upms-biz/Dockerfile b/pig-upms/pig-upms-biz/Dockerfile new file mode 100644 index 00000000..cff15405 --- /dev/null +++ b/pig-upms/pig-upms-biz/Dockerfile @@ -0,0 +1,15 @@ +FROM anapsix/alpine-java:8_server-jre_unlimited + +MAINTAINER wangiegie@gmail.com + +RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime + +RUN mkdir -p /pigx-upms + +WORKDIR /pigx-upms + +EXPOSE 4000 + +ADD ./pigx-upms/pigx-upms-biz/target/pigx-upms-biz.jar ./ + +CMD java -Djava.security.egd=file:/dev/./urandom -jar pigx-upms-biz.jar diff --git a/pig-upms/pig-upms-biz/pom.xml b/pig-upms/pig-upms-biz/pom.xml new file mode 100644 index 00000000..f2cf8c73 --- /dev/null +++ b/pig-upms/pig-upms-biz/pom.xml @@ -0,0 +1,99 @@ + + + + + 4.0.0 + + com.pig4cloud + pig-upms + ${pig.version} + + + pig-upms-biz + jar + + pig 通用用户权限管理系统业务处理模块 + + + + + com.pig4cloud + pig-upms-api + ${pig.version} + + + + com.pig4cloud + pig-common-security + ${pig.version} + + + + com.pig4cloud + pig-common-log + ${pig.version} + + + + org.springframework.cloud + spring-cloud-starter-config + + + + com.baomidou + mybatis-plus-boot-starter + ${mybatis-plus.version} + + + + mysql + mysql-connector-java + + + + org.springframework.boot + spring-boot-starter-web + + + + spring-boot-starter-tomcat + org.springframework.boot + + + + + + org.springframework.boot + spring-boot-starter-undertow + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.spotify + docker-maven-plugin + + + + + diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/PigAdminApplication.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/PigAdminApplication.java new file mode 100644 index 00000000..e8fce4a9 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/PigAdminApplication.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin; + + +import com.pig4cloud.pig.common.security.annotation.EnablePigFeignClients; +import org.springframework.boot.SpringApplication; +import org.springframework.cloud.client.SpringCloudApplication; + +/** + * @author lengleng + * @date 2018年06月21日 + * 用户统一管理系统 + */ +@EnablePigFeignClients +@SpringCloudApplication +public class PigAdminApplication { + public static void main(String[] args) { + SpringApplication.run(PigAdminApplication.class, args); + } + +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/config/MybatisPlusConfigurer.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/config/MybatisPlusConfigurer.java new file mode 100755 index 00000000..4469806d --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/config/MybatisPlusConfigurer.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.config; + +import com.baomidou.mybatisplus.core.injector.ISqlInjector; +import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector; +import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; +import com.pig4cloud.pig.common.core.datascope.DataScopeInterceptor; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@Configuration +@MapperScan("com.pig4cloud.pig.admin.mapper") +public class MybatisPlusConfigurer { + /** + * 分页插件 + * + * @return PaginationInterceptor + */ + @Bean + public PaginationInterceptor paginationInterceptor() { + return new PaginationInterceptor(); + } + + /** + * 数据权限插件 + * + * @return DataScopeInterceptor + */ + @Bean + public DataScopeInterceptor dataScopeInterceptor() { + return new DataScopeInterceptor(); + } + + /** + * 逻辑删除 + * + * @return + */ + @Bean + public ISqlInjector sqlInjector() { + return new LogicSqlInjector(); + } +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/config/ResourceServerConfigurer.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/config/ResourceServerConfigurer.java new file mode 100755 index 00000000..76d4fb08 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/config/ResourceServerConfigurer.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.config; + +import com.pig4cloud.pig.common.security.component.BaseResourceServerConfigurerAdapter; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@Configuration +@EnableResourceServer +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class ResourceServerConfigurer extends BaseResourceServerConfigurerAdapter { + +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/DeptController.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/DeptController.java new file mode 100644 index 00000000..bbc06b56 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/DeptController.java @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.controller; + +import com.pig4cloud.pig.admin.api.entity.SysDept; +import com.pig4cloud.pig.admin.service.SysDeptService; +import com.pig4cloud.pig.common.core.util.R; +import com.pig4cloud.pig.common.log.annotation.SysLog; +import lombok.AllArgsConstructor; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; +import java.time.LocalDateTime; + +/** + *

+ * 部门管理 前端控制器 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@RestController +@AllArgsConstructor +@RequestMapping("/dept") +public class DeptController { + private final SysDeptService sysDeptService; + + /** + * 通过ID查询 + * + * @param id ID + * @return SysDept + */ + @GetMapping("/{id}") + public R getById(@PathVariable Integer id) { + return new R<>(sysDeptService.getById(id)); + } + + + /** + * 返回树形菜单集合 + * + * @return 树形菜单 + */ + @GetMapping(value = "/tree") + public R getTree() { + return new R<>(sysDeptService.selectTree()); + } + + /** + * 返回当前用户树形菜单集合 + * + * @return 树形菜单 + */ + @GetMapping(value = "/user-tree") + public R getUserTree() { + return new R<>(sysDeptService.getUserTree()); + } + + /** + * 添加 + * + * @param sysDept 实体 + * @return success/false + */ + @SysLog("添加部门") + @PostMapping + @PreAuthorize("@pms.hasPermission('sys_dept_add')") + public R save(@Valid @RequestBody SysDept sysDept) { + return new R<>(sysDeptService.saveDept(sysDept)); + } + + /** + * 删除 + * + * @param id ID + * @return success/false + */ + @SysLog("删除部门") + @DeleteMapping("/{id}") + @PreAuthorize("@pms.hasPermission('sys_dept_del')") + public R removeById(@PathVariable Integer id) { + return new R<>(sysDeptService.removeDeptById(id)); + } + + /** + * 编辑 + * + * @param sysDept 实体 + * @return success/false + */ + @SysLog("编辑部门") + @PutMapping + @PreAuthorize("@pms.hasPermission('sys_dept_edit')") + public R update(@Valid @RequestBody SysDept sysDept) { + sysDept.setUpdateTime(LocalDateTime.now()); + return new R<>(sysDeptService.updateDeptById(sysDept)); + } +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/DictController.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/DictController.java new file mode 100644 index 00000000..131cf008 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/DictController.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.controller; + + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.pig4cloud.pig.admin.api.entity.SysDict; +import com.pig4cloud.pig.admin.service.SysDictService; +import com.pig4cloud.pig.common.core.util.R; +import com.pig4cloud.pig.common.log.annotation.SysLog; +import lombok.AllArgsConstructor; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; + +/** + *

+ * 字典表 前端控制器 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@RestController +@AllArgsConstructor +@RequestMapping("/dict") +public class DictController { + private final SysDictService sysDictService; + + /** + * 通过ID查询字典信息 + * + * @param id ID + * @return 字典信息 + */ + @GetMapping("/{id}") + public R getById(@PathVariable Integer id) { + return new R<>(sysDictService.getById(id)); + } + + /** + * 分页查询字典信息 + * + * @param page 分页对象 + * @return 分页对象 + */ + @GetMapping("/page") + public R getDictPage(Page page, SysDict sysDict) { + return new R<>(sysDictService.page(page, Wrappers.query(sysDict))); + } + + /** + * 通过字典类型查找字典 + * + * @param type 类型 + * @return 同类型字典 + */ + @GetMapping("/type/{type}") + @Cacheable(value = "dict_details", key = "#type") + public R getDictByType(@PathVariable String type) { + return new R<>(sysDictService.list(Wrappers + .query().lambda() + .eq(SysDict::getType, type))); + } + + /** + * 添加字典 + * + * @param sysDict 字典信息 + * @return success、false + */ + @SysLog("添加字典") + @PostMapping + @CacheEvict(value = "dict_details", key = "#sysDict.type") + @PreAuthorize("@pms.hasPermission('sys_dict_add')") + public R save(@Valid @RequestBody SysDict sysDict) { + return new R<>(sysDictService.save(sysDict)); + } + + /** + * 删除字典,并且清除字典缓存 + * + * @param id ID + * @param type 类型 + * @return R + */ + @SysLog("删除字典") + @DeleteMapping("/{id}/{type}") + @CacheEvict(value = "dict_details", key = "#type") + @PreAuthorize("@pms.hasPermission('sys_dict_del')") + public R removeById(@PathVariable Integer id, @PathVariable String type) { + return new R<>(sysDictService.removeById(id)); + } + + /** + * 修改字典 + * + * @param sysDict 字典信息 + * @return success/false + */ + @PutMapping + @SysLog("修改字典") + @CacheEvict(value = "dict_details", key = "#sysDict.type") + @PreAuthorize("@pms.hasPermission('sys_dict_edit')") + public R updateById(@Valid @RequestBody SysDict sysDict) { + return new R<>(sysDictService.updateById(sysDict)); + } +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/LogController.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/LogController.java new file mode 100644 index 00000000..870e78e0 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/LogController.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.controller; + + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.pig4cloud.pig.admin.api.entity.SysLog; +import com.pig4cloud.pig.admin.api.vo.PreLogVo; +import com.pig4cloud.pig.admin.service.SysLogService; +import com.pig4cloud.pig.common.core.util.R; +import com.pig4cloud.pig.common.security.annotation.Inner; +import lombok.AllArgsConstructor; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; +import java.util.List; + +/** + *

+ * 日志表 前端控制器 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@RestController +@AllArgsConstructor +@RequestMapping("/log") +public class LogController { + private final SysLogService sysLogService; + + /** + * 简单分页查询 + * + * @param page 分页对象 + * @param sysLog 系统日志 + * @return + */ + @GetMapping("/page") + public R getLogPage(Page page, SysLog sysLog) { + return new R<>(sysLogService.page(page, Wrappers.query(sysLog))); + } + + /** + * 删除日志 + * + * @param id ID + * @return success/false + */ + @DeleteMapping("/{id}") + @PreAuthorize("@pms.hasPermission('sys_log_del')") + public R removeById(@PathVariable Long id) { + return new R<>(sysLogService.removeById(id)); + } + + /** + * 插入日志 + * + * @param sysLog 日志实体 + * @return success/false + */ + @Inner + @PostMapping("/save") + public R save(@Valid @RequestBody SysLog sysLog) { + return new R<>(sysLogService.save(sysLog)); + } + + /** + * 批量插入前端异常日志 + * + * @param preLogVoList 日志实体 + * @return success/false + */ + @PostMapping("/logs") + public R saveBatchLogs(@RequestBody List preLogVoList) { + return new R<>(sysLogService.saveBatchLogs(preLogVoList)); + } +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/MenuController.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/MenuController.java new file mode 100644 index 00000000..7815106c --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/MenuController.java @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.controller; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.pig4cloud.pig.admin.api.dto.MenuTree; +import com.pig4cloud.pig.admin.api.entity.SysMenu; +import com.pig4cloud.pig.admin.api.vo.MenuVO; +import com.pig4cloud.pig.admin.api.vo.TreeUtil; +import com.pig4cloud.pig.admin.service.SysMenuService; +import com.pig4cloud.pig.common.core.constant.CommonConstants; +import com.pig4cloud.pig.common.core.util.R; +import com.pig4cloud.pig.common.log.annotation.SysLog; +import com.pig4cloud.pig.common.security.util.SecurityUtils; +import lombok.AllArgsConstructor; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@RestController +@AllArgsConstructor +@RequestMapping("/menu") +public class MenuController { + private final SysMenuService sysMenuService; + + /** + * 返回当前用户的树形菜单集合 + * + * @return 当前用户的树形菜单 + */ + @GetMapping + public R getUserMenu() { + // 获取符合条件的菜单 + Set all = new HashSet<>(); + SecurityUtils.getRoles() + .forEach(roleId -> all.addAll(sysMenuService.findMenuByRoleId(roleId))); + List menuTreeList = all.stream() + .filter(menuVo -> CommonConstants.MENU.equals(menuVo.getType())) + .map(MenuTree::new) + .sorted(Comparator.comparingInt(MenuTree::getSort)) + .collect(Collectors.toList()); + return new R<>(TreeUtil.bulid(menuTreeList, -1)); + } + + /** + * 返回树形菜单集合 + * + * @return 树形菜单 + */ + @GetMapping(value = "/tree") + public R getTree() { + return new R<>(TreeUtil.bulidTree(sysMenuService.list(Wrappers.emptyWrapper()), -1)); + } + + /** + * 返回角色的菜单集合 + * + * @param roleId 角色ID + * @return 属性集合 + */ + @GetMapping("/tree/{roleId}") + public List getRoleTree(@PathVariable Integer roleId) { + return sysMenuService.findMenuByRoleId(roleId) + .stream() + .map(MenuVO::getMenuId) + .collect(Collectors.toList()); + } + + /** + * 通过ID查询菜单的详细信息 + * + * @param id 菜单ID + * @return 菜单详细信息 + */ + @GetMapping("/{id}") + public R getById(@PathVariable Integer id) { + return new R<>(sysMenuService.getById(id)); + } + + /** + * 新增菜单 + * + * @param sysMenu 菜单信息 + * @return success/false + */ + @SysLog("新增菜单") + @PostMapping + @PreAuthorize("@pms.hasPermission('sys_menu_add')") + public R save(@Valid @RequestBody SysMenu sysMenu) { + return new R<>(sysMenuService.save(sysMenu)); + } + + /** + * 删除菜单 + * + * @param id 菜单ID + * @return success/false + */ + @SysLog("删除菜单") + @DeleteMapping("/{id}") + @PreAuthorize("@pms.hasPermission('sys_menu_del')") + public R removeById(@PathVariable Integer id) { + return sysMenuService.removeMenuById(id); + } + + /** + * 更新菜单 + * + * @param sysMenu + * @return + */ + @SysLog("更新菜单") + @PutMapping + @PreAuthorize("@pms.hasPermission('sys_menu_edit')") + public R update(@Valid @RequestBody SysMenu sysMenu) { + return new R<>(sysMenuService.updateMenuById(sysMenu)); + } + +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/OauthClientDetailsController.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/OauthClientDetailsController.java new file mode 100644 index 00000000..142d7b26 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/OauthClientDetailsController.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.controller; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.pig4cloud.pig.admin.api.entity.SysOauthClientDetails; +import com.pig4cloud.pig.admin.service.SysOauthClientDetailsService; +import com.pig4cloud.pig.common.core.util.R; +import com.pig4cloud.pig.common.log.annotation.SysLog; +import lombok.AllArgsConstructor; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; + +/** + *

+ * 前端控制器 + *

+ * + * @author lengleng + * @since 2018-05-15 + */ +@RestController +@AllArgsConstructor +@RequestMapping("/client") +public class OauthClientDetailsController { + private final SysOauthClientDetailsService sysOauthClientDetailsService; + + /** + * 通过ID查询 + * + * @param id ID + * @return SysOauthClientDetails + */ + @GetMapping("/{id}") + public R getById(@PathVariable Integer id) { + return new R<>(sysOauthClientDetailsService.getById(id)); + } + + + /** + * 简单分页查询 + * + * @param page 分页对象 + * @param sysOauthClientDetails 系统终端 + * @return + */ + @GetMapping("/page") + public R getOauthClientDetailsPage(Page page, SysOauthClientDetails sysOauthClientDetails) { + return new R<>(sysOauthClientDetailsService.page(page, Wrappers.query(sysOauthClientDetails))); + } + + /** + * 添加 + * + * @param sysOauthClientDetails 实体 + * @return success/false + */ + @SysLog("添加终端") + @PostMapping + @PreAuthorize("@pms.hasPermission('sys_client_add')") + public R add(@Valid @RequestBody SysOauthClientDetails sysOauthClientDetails) { + return new R<>(sysOauthClientDetailsService.save(sysOauthClientDetails)); + } + + /** + * 删除 + * + * @param id ID + * @return success/false + */ + @SysLog("删除终端") + @DeleteMapping("/{id}") + @PreAuthorize("@pms.hasPermission('sys_client_del')") + public R removeById(@PathVariable String id) { + return new R<>(sysOauthClientDetailsService.removeClientDetailsById(id)); + } + + /** + * 编辑 + * + * @param sysOauthClientDetails 实体 + * @return success/false + */ + @SysLog("编辑终端") + @PutMapping + @PreAuthorize("@pms.hasPermission('sys_client_edit')") + public R update(@Valid @RequestBody SysOauthClientDetails sysOauthClientDetails) { + return new R<>(sysOauthClientDetailsService.updateClientDetailsById(sysOauthClientDetails)); + } +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/RoleController.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/RoleController.java new file mode 100644 index 00000000..dcea4489 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/RoleController.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.controller; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.pig4cloud.pig.admin.api.entity.SysRole; +import com.pig4cloud.pig.admin.service.SysRoleMenuService; +import com.pig4cloud.pig.admin.service.SysRoleService; +import com.pig4cloud.pig.common.core.util.R; +import com.pig4cloud.pig.common.log.annotation.SysLog; +import lombok.AllArgsConstructor; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@RestController +@AllArgsConstructor +@RequestMapping("/role") +public class RoleController { + private final SysRoleService sysRoleService; + private final SysRoleMenuService sysRoleMenuService; + + /** + * 通过ID查询角色信息 + * + * @param id ID + * @return 角色信息 + */ + @GetMapping("/{id}") + public R getById(@PathVariable Integer id) { + return new R<>(sysRoleService.getById(id)); + } + + /** + * 添加角色 + * + * @param sysRole 角色信息 + * @return success、false + */ + @SysLog("添加角色") + @PostMapping + @PreAuthorize("@pms.hasPermission('sys_role_add')") + public R save(@Valid @RequestBody SysRole sysRole) { + return new R<>(sysRoleService.save(sysRole)); + } + + /** + * 修改角色 + * + * @param sysRole 角色信息 + * @return success/false + */ + @SysLog("修改角色") + @PutMapping + @PreAuthorize("@pms.hasPermission('sys_role_edit')") + public R update(@Valid @RequestBody SysRole sysRole) { + return new R<>(sysRoleService.updateById(sysRole)); + } + + /** + * 删除角色 + * + * @param id + * @return + */ + @SysLog("删除角色") + @DeleteMapping("/{id}") + @PreAuthorize("@pms.hasPermission('sys_role_del')") + public R removeById(@PathVariable Integer id) { + return new R<>(sysRoleService.removeRoleById(id)); + } + + /** + * 获取角色列表 + * + * @return 角色列表 + */ + @GetMapping("/list") + public R listRoles() { + return new R<>(sysRoleService.list(Wrappers.emptyWrapper())); + } + + /** + * 分页查询角色信息 + * + * @param page 分页对象 + * @return 分页对象 + */ + @GetMapping("/page") + public R getRolePage(Page page) { + return new R<>(sysRoleService.page(page, Wrappers.emptyWrapper())); + } + + /** + * 更新角色菜单 + * + * @param roleId 角色ID + * @param menuIds 菜单ID拼成的字符串,每个id之间根据逗号分隔 + * @return success、false + */ + @SysLog("更新角色菜单") + @PutMapping("/menu") + @PreAuthorize("@pms.hasPermission('sys_role_perm')") + public R saveRoleMenus(Integer roleId, @RequestParam(value = "menuIds", required = false) String menuIds) { + SysRole sysRole = sysRoleService.getById(roleId); + return new R<>(sysRoleMenuService.saveRoleMenus(sysRole.getRoleCode(), roleId, menuIds)); + } +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/TokenController.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/TokenController.java new file mode 100644 index 00000000..1a2290f5 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/TokenController.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.controller; + +import com.pig4cloud.pig.admin.api.feign.RemoteTokenService; +import com.pig4cloud.pig.common.core.constant.SecurityConstants; +import com.pig4cloud.pig.common.core.util.R; +import lombok.AllArgsConstructor; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +/** + * @author lengleng + * @date 2018/9/4 + * getTokenPage 管理 + */ +@RestController +@AllArgsConstructor +@RequestMapping("/token") +public class TokenController { + private final RemoteTokenService remoteTokenService; + + /** + * 分页token 信息 + * + * @param params 参数集 + * @return token集合 + */ + @GetMapping("/page") + public R token(@RequestParam Map params) { + return remoteTokenService.selectPage(params, SecurityConstants.FROM_IN); + } + + /** + * 删除 + * + * @param id ID + * @return success/false + */ + @DeleteMapping("/{id}") + @PreAuthorize("@pms.hasPermission('sys_token_del')") + public R delete(@PathVariable String id) { + return remoteTokenService.deleteTokenById(id, SecurityConstants.FROM_IN); + } +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/UserController.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/UserController.java new file mode 100644 index 00000000..0fa18fc4 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/UserController.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.controller; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.pig4cloud.pig.admin.api.dto.UserDTO; +import com.pig4cloud.pig.admin.api.entity.SysUser; +import com.pig4cloud.pig.admin.service.SysUserService; +import com.pig4cloud.pig.common.core.util.R; +import com.pig4cloud.pig.common.log.annotation.SysLog; +import com.pig4cloud.pig.common.security.annotation.Inner; +import com.pig4cloud.pig.common.security.util.SecurityUtils; +import lombok.AllArgsConstructor; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@RestController +@AllArgsConstructor +@RequestMapping("/user") +public class UserController { + private final SysUserService userService; + + /** + * 获取当前用户全部信息 + * + * @return 用户信息 + */ + @GetMapping(value = {"/info"}) + public R info() { + String username = SecurityUtils.getUser().getUsername(); + SysUser user = userService.getOne(Wrappers.query() + .lambda().eq(SysUser::getUsername, username)); + if (user == null) { + return new R<>(Boolean.FALSE, "获取当前用户信息失败"); + } + return new R<>(userService.findUserInfo(user)); + } + + /** + * 获取指定用户全部信息 + * + * @return 用户信息 + */ + @Inner + @GetMapping("/info/{username}") + public R info(@PathVariable String username) { + SysUser user = userService.getOne(Wrappers.query() + .lambda().eq(SysUser::getUsername, username)); + if (user == null) { + return new R<>(Boolean.FALSE, String.format("用户信息为空 %s", username)); + } + return new R<>(userService.findUserInfo(user)); + } + + /** + * 通过ID查询用户信息 + * + * @param id ID + * @return 用户信息 + */ + @GetMapping("/{id}") + public R user(@PathVariable Integer id) { + return new R<>(userService.selectUserVoById(id)); + } + + /** + * 根据用户名查询用户信息 + * + * @param username 用户名 + * @return + */ + @GetMapping("/details/{username}") + public R user(@PathVariable String username) { + SysUser condition = new SysUser(); + condition.setUsername(username); + return new R<>(userService.getOne(new QueryWrapper<>(condition))); + } + + /** + * 删除用户信息 + * + * @param id ID + * @return R + */ + @SysLog("删除用户信息") + @DeleteMapping("/{id}") + @PreAuthorize("@pms.hasPermission('sys_user_del')") + public R userDel(@PathVariable Integer id) { + SysUser sysUser = userService.getById(id); + return new R<>(userService.deleteUserById(sysUser)); + } + + /** + * 添加用户 + * + * @param userDto 用户信息 + * @return success/false + */ + @SysLog("添加用户") + @PostMapping + @PreAuthorize("@pms.hasPermission('sys_user_add')") + public R user(@RequestBody UserDTO userDto) { + return new R<>(userService.saveUser(userDto)); + } + + /** + * 更新用户信息 + * + * @param userDto 用户信息 + * @return R + */ + @SysLog("更新用户信息") + @PutMapping + @PreAuthorize("@pms.hasPermission('sys_user_edit')") + public R updateUser(@Valid @RequestBody UserDTO userDto) { + return new R<>(userService.updateUser(userDto)); + } + + /** + * 分页查询用户 + * + * @param page 参数集 + * @param userDTO 查询参数列表 + * @return 用户集合 + */ + @GetMapping("/page") + public R getUserPage(Page page, UserDTO userDTO) { + return new R<>(userService.getUsersWithRolePage(page, userDTO)); + } + + /** + * 修改个人信息 + * + * @param userDto userDto + * @return success/false + */ + @SysLog("修改个人信息") + @PutMapping("/edit") + public R updateUserInfo(@Valid @RequestBody UserDTO userDto) { + return userService.updateUserInfo(userDto); + } + + /** + * @param username 用户名称 + * @return 上级部门用户列表 + */ + @GetMapping("/ancestor/{username}") + public R listAncestorUsers(@PathVariable String username) { + return new R<>(userService.listAncestorUsers(username)); + } +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysDeptMapper.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysDeptMapper.java new file mode 100644 index 00000000..248df7fe --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysDeptMapper.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.pig4cloud.pig.admin.api.entity.SysDept; + +import java.util.List; + +/** + *

+ * 部门管理 Mapper 接口 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +public interface SysDeptMapper extends BaseMapper { + + /** + * 关联dept——relation + * + * @return 数据列表 + */ + List listDepts(); +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysDeptRelationMapper.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysDeptRelationMapper.java new file mode 100644 index 00000000..8e923805 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysDeptRelationMapper.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.pig4cloud.pig.admin.api.entity.SysDeptRelation; + +/** + *

+ * Mapper 接口 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +public interface SysDeptRelationMapper extends BaseMapper { + /** + * 删除部门关系表数据 + * + * @param id 部门ID + */ + void deleteDeptRelationsById(Integer id); + + /** + * 更改部分关系表数据 + * + * @param deptRelation + */ + void updateDeptRelations(SysDeptRelation deptRelation); + +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysDictMapper.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysDictMapper.java new file mode 100644 index 00000000..14af75ec --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysDictMapper.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.pig4cloud.pig.admin.api.entity.SysDict; + +/** + *

+ * 字典表 Mapper 接口 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +public interface SysDictMapper extends BaseMapper { + +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysLogMapper.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysLogMapper.java new file mode 100644 index 00000000..5910ea13 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysLogMapper.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.pig4cloud.pig.admin.api.entity.SysLog; + +/** + *

+ * 日志表 Mapper 接口 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +public interface SysLogMapper extends BaseMapper { +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysMenuMapper.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysMenuMapper.java new file mode 100644 index 00000000..ffa60597 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysMenuMapper.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.pig4cloud.pig.admin.api.entity.SysMenu; +import com.pig4cloud.pig.admin.api.vo.MenuVO; + +import java.util.List; + +/** + *

+ * 菜单权限表 Mapper 接口 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +public interface SysMenuMapper extends BaseMapper { + + /** + * 通过角色编号查询菜单 + * + * @param roleId 角色ID + * @return + */ + List listMenusByRoleId(Integer roleId); + + /** + * 通过角色ID查询权限 + * + * @param roleIds Ids + * @return + */ + List listPermissionsByRoleIds(String roleIds); +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysOauthClientDetailsMapper.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysOauthClientDetailsMapper.java new file mode 100644 index 00000000..bfd4ffa2 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysOauthClientDetailsMapper.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.mapper; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.pig4cloud.pig.admin.api.entity.SysOauthClientDetails; + +/** + *

+ * Mapper 接口 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +public interface SysOauthClientDetailsMapper extends BaseMapper { + +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysRoleMapper.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysRoleMapper.java new file mode 100644 index 00000000..e4055100 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysRoleMapper.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.pig4cloud.pig.admin.api.entity.SysRole; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +public interface SysRoleMapper extends BaseMapper { + /** + * 通过用户ID,查询角色信息 + * + * @param userId + * @return + */ + List listRolesByUserId(Integer userId); +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysRoleMenuMapper.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysRoleMenuMapper.java new file mode 100644 index 00000000..56aa71df --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysRoleMenuMapper.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.mapper; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.pig4cloud.pig.admin.api.entity.SysRoleMenu; + +/** + *

+ * 角色菜单表 Mapper 接口 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +public interface SysRoleMenuMapper extends BaseMapper { + +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysUserMapper.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysUserMapper.java new file mode 100644 index 00000000..3fc30a9f --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysUserMapper.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.pig4cloud.pig.admin.api.dto.UserDTO; +import com.pig4cloud.pig.admin.api.entity.SysUser; +import com.pig4cloud.pig.admin.api.vo.UserVO; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + *

+ * 用户表 Mapper 接口 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +public interface SysUserMapper extends BaseMapper { + /** + * 通过用户名查询用户信息(含有角色信息) + * + * @param username 用户名 + * @return userVo + */ + UserVO getUserVoByUsername(String username); + + /** + * 分页查询用户信息(含角色) + * + * @param page 分页 + * @param userDTO 查询参数 + * @return list + */ + IPage> getUserVosPage(Page page, @Param("query") UserDTO userDTO); + + /** + * 通过ID查询用户信息 + * + * @param id 用户ID + * @return userVo + */ + UserVO getUserVoById(Integer id); +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysUserRoleMapper.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysUserRoleMapper.java new file mode 100644 index 00000000..6fa85e00 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysUserRoleMapper.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.mapper; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.pig4cloud.pig.admin.api.entity.SysUserRole; +import org.apache.ibatis.annotations.Param; + +/** + *

+ * 用户角色表 Mapper 接口 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +public interface SysUserRoleMapper extends BaseMapper { + /** + * 根据用户Id删除该用户的角色关系 + * + * @param userId 用户ID + * @return boolean + * @author 寻欢·李 + * @date 2017年12月7日 16:31:38 + */ + Boolean deleteByUserId(@Param("userId") Integer userId); +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysDeptRelationService.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysDeptRelationService.java new file mode 100644 index 00000000..6c97b705 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysDeptRelationService.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.pig4cloud.pig.admin.api.entity.SysDept; +import com.pig4cloud.pig.admin.api.entity.SysDeptRelation; + +/** + *

+ * 服务类 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +public interface SysDeptRelationService extends IService { + + /** + * 新建部门关系 + * + * @param sysDept 部门 + */ + void insertDeptRelation(SysDept sysDept); + + /** + * 通过ID删除部门关系 + * + * @param id + */ + void deleteAllDeptRealtion(Integer id); + + /** + * 更新部门关系 + * + * @param relation + */ + void updateDeptRealtion(SysDeptRelation relation); +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysDeptService.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysDeptService.java new file mode 100644 index 00000000..cc0ac6d1 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysDeptService.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.pig4cloud.pig.admin.api.dto.DeptTree; +import com.pig4cloud.pig.admin.api.entity.SysDept; + +import java.util.List; + +/** + *

+ * 部门管理 服务类 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +public interface SysDeptService extends IService { + + /** + * 查询部门树菜单 + * + * @return 树 + */ + List selectTree(); + + /** + * 查询用户部门树 + * + * @return + */ + List getUserTree(); + + /** + * 添加信息部门 + * + * @param sysDept + * @return + */ + Boolean saveDept(SysDept sysDept); + + /** + * 删除部门 + * + * @param id 部门 ID + * @return 成功、失败 + */ + Boolean removeDeptById(Integer id); + + /** + * 更新部门 + * + * @param sysDept 部门信息 + * @return 成功、失败 + */ + Boolean updateDeptById(SysDept sysDept); + +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysDictService.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysDictService.java new file mode 100644 index 00000000..579a9383 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysDictService.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.pig4cloud.pig.admin.api.entity.SysDict; + +/** + *

+ * 字典表 服务类 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +public interface SysDictService extends IService { +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysLogService.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysLogService.java new file mode 100644 index 00000000..5ce22a49 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysLogService.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.pig4cloud.pig.admin.api.entity.SysLog; +import com.pig4cloud.pig.admin.api.vo.PreLogVo; + +import java.util.List; + +/** + *

+ * 日志表 服务类 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +public interface SysLogService extends IService { + + + /** + * 批量插入前端错误日志 + * + * @param preLogVoList 日志信息 + * @return true/false + */ + Boolean saveBatchLogs(List preLogVoList); +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysMenuService.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysMenuService.java new file mode 100644 index 00000000..7bebec32 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysMenuService.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.pig4cloud.pig.admin.api.entity.SysMenu; +import com.pig4cloud.pig.admin.api.vo.MenuVO; +import com.pig4cloud.pig.common.core.util.R; + +import java.util.List; + +/** + *

+ * 菜单权限表 服务类 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +public interface SysMenuService extends IService { + /** + * 通过角色编号查询URL 权限 + * + * @param roleId 角色ID + * @return 菜单列表 + */ + List findMenuByRoleId(Integer roleId); + + /** + * 级联删除菜单 + * + * @param id 菜单ID + * @return 成功、失败 + */ + R removeMenuById(Integer id); + + /** + * 更新菜单信息 + * + * @param sysMenu 菜单信息 + * @return 成功、失败 + */ + Boolean updateMenuById(SysMenu sysMenu); +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysOauthClientDetailsService.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysOauthClientDetailsService.java new file mode 100644 index 00000000..cdcf3897 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysOauthClientDetailsService.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.pig4cloud.pig.admin.api.entity.SysOauthClientDetails; + +/** + *

+ * 服务类 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +public interface SysOauthClientDetailsService extends IService { + /** + * 通过ID删除客户端 + * + * @param id + * @return + */ + Boolean removeClientDetailsById(String id); + + /** + * 根据客户端信息 + * + * @param sysOauthClientDetails + * @return + */ + Boolean updateClientDetailsById(SysOauthClientDetails sysOauthClientDetails); +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysRoleMenuService.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysRoleMenuService.java new file mode 100644 index 00000000..1dc55642 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysRoleMenuService.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.pig4cloud.pig.admin.api.entity.SysRoleMenu; + +/** + *

+ * 角色菜单表 服务类 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +public interface SysRoleMenuService extends IService { + + /** + * 更新角色菜单 + * + * @param role + * @param roleId 角色 + * @param menuIds 菜单ID拼成的字符串,每个id之间根据逗号分隔 + * @return + */ + Boolean saveRoleMenus(String role, Integer roleId, String menuIds); +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysRoleService.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysRoleService.java new file mode 100644 index 00000000..059a92dc --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysRoleService.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.pig4cloud.pig.admin.api.entity.SysRole; + +import java.util.List; + +/** + *

+ * 服务类 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +public interface SysRoleService extends IService { + + /** + * 通过用户ID,查询角色信息 + * + * @param userId + * @return + */ + List findRolesByUserId(Integer userId); + + /** + * 通过角色ID,删除角色 + * + * @param id + * @return + */ + Boolean removeRoleById(Integer id); +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysUserRoleService.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysUserRoleService.java new file mode 100644 index 00000000..9055a186 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysUserRoleService.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.pig4cloud.pig.admin.api.entity.SysUserRole; + +/** + *

+ * 用户角色表 服务类 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +public interface SysUserRoleService extends IService { + + /** + * 根据用户Id删除该用户的角色关系 + * + * @param userId 用户ID + * @return boolean + * @author 寻欢·李 + * @date 2017年12月7日 16:31:38 + */ + Boolean deleteByUserId(Integer userId); +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysUserService.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysUserService.java new file mode 100644 index 00000000..0b1bf06d --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysUserService.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import com.pig4cloud.pig.admin.api.dto.UserDTO; +import com.pig4cloud.pig.admin.api.dto.UserInfo; +import com.pig4cloud.pig.admin.api.entity.SysUser; +import com.pig4cloud.pig.admin.api.vo.UserVO; +import com.pig4cloud.pig.common.core.util.R; + +import java.util.List; + +/** + * @author lengleng + * @date 2019/2/1 + */ +public interface SysUserService extends IService { + /** + * 查询用户信息 + * + * @param sysUser 用户 + * @return userInfo + */ + UserInfo findUserInfo(SysUser sysUser); + + /** + * 分页查询用户信息(含有角色信息) + * + * @param page 分页对象 + * @param userDTO 参数列表 + * @return + */ + IPage getUsersWithRolePage(Page page, UserDTO userDTO); + + /** + * 删除用户 + * + * @param sysUser 用户 + * @return boolean + */ + Boolean deleteUserById(SysUser sysUser); + + /** + * 更新当前用户基本信息 + * + * @param userDto 用户信息 + * @return Boolean + */ + R updateUserInfo(UserDTO userDto); + + /** + * 更新指定用户信息 + * + * @param userDto 用户信息 + * @return + */ + Boolean updateUser(UserDTO userDto); + + /** + * 通过ID查询用户信息 + * + * @param id 用户ID + * @return 用户信息 + */ + UserVO selectUserVoById(Integer id); + + /** + * 查询上级部门的用户信息 + * + * @param username 用户名 + * @return R + */ + List listAncestorUsers(String username); + + /** + * 保存用户信息 + * + * @param userDto DTO 对象 + * @return success/fail + */ + Boolean saveUser(UserDTO userDto); +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysDeptRelationServiceImpl.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysDeptRelationServiceImpl.java new file mode 100644 index 00000000..75d742fc --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysDeptRelationServiceImpl.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service.impl; + +import cn.hutool.core.collection.CollUtil; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.pig4cloud.pig.admin.api.entity.SysDept; +import com.pig4cloud.pig.admin.api.entity.SysDeptRelation; +import com.pig4cloud.pig.admin.mapper.SysDeptRelationMapper; +import com.pig4cloud.pig.admin.service.SysDeptRelationService; +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.stream.Collectors; + +/** + *

+ * 服务实现类 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Service +@AllArgsConstructor +public class SysDeptRelationServiceImpl extends ServiceImpl implements SysDeptRelationService { + private final SysDeptRelationMapper sysDeptRelationMapper; + + /** + * 维护部门关系 + * + * @param sysDept 部门 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void insertDeptRelation(SysDept sysDept) { + //增加部门关系表 + SysDeptRelation condition = new SysDeptRelation(); + condition.setDescendant(sysDept.getParentId()); + List relationList = sysDeptRelationMapper + .selectList(Wrappers.query().lambda() + .eq(SysDeptRelation::getDescendant, sysDept.getParentId())) + .stream().map(relation -> { + relation.setDescendant(sysDept.getDeptId()); + return relation; + }).collect(Collectors.toList()); + if (CollUtil.isNotEmpty(relationList)) { + this.saveBatch(relationList); + } + + //自己也要维护到关系表中 + SysDeptRelation own = new SysDeptRelation(); + own.setDescendant(sysDept.getDeptId()); + own.setAncestor(sysDept.getDeptId()); + sysDeptRelationMapper.insert(own); + } + + /** + * 通过ID删除部门关系 + * + * @param id + */ + @Override + public void deleteAllDeptRealtion(Integer id) { + baseMapper.deleteDeptRelationsById(id); + } + + /** + * 更新部门关系 + * + * @param relation + */ + @Override + public void updateDeptRealtion(SysDeptRelation relation) { + baseMapper.updateDeptRelations(relation); + } + +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysDeptServiceImpl.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysDeptServiceImpl.java new file mode 100644 index 00000000..a47e78b3 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysDeptServiceImpl.java @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service.impl; + +import cn.hutool.core.collection.CollUtil; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.pig4cloud.pig.admin.api.dto.DeptTree; +import com.pig4cloud.pig.admin.api.entity.SysDept; +import com.pig4cloud.pig.admin.api.entity.SysDeptRelation; +import com.pig4cloud.pig.admin.api.vo.TreeUtil; +import com.pig4cloud.pig.admin.mapper.SysDeptMapper; +import com.pig4cloud.pig.admin.service.SysDeptRelationService; +import com.pig4cloud.pig.admin.service.SysDeptService; +import com.pig4cloud.pig.common.security.util.SecurityUtils; +import lombok.AllArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.stream.Collectors; + +/** + *

+ * 部门管理 服务实现类 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Service +@AllArgsConstructor +public class SysDeptServiceImpl extends ServiceImpl implements SysDeptService { + private final SysDeptRelationService sysDeptRelationService; + + /** + * 添加信息部门 + * + * @param dept 部门 + * @return + */ + @Override + @Transactional(rollbackFor = Exception.class) + public Boolean saveDept(SysDept dept) { + SysDept sysDept = new SysDept(); + BeanUtils.copyProperties(dept, sysDept); + this.save(sysDept); + sysDeptRelationService.insertDeptRelation(sysDept); + return Boolean.TRUE; + } + + + /** + * 删除部门 + * + * @param id 部门 ID + * @return 成功、失败 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public Boolean removeDeptById(Integer id) { + //级联删除部门 + List idList = sysDeptRelationService + .list(Wrappers.query().lambda() + .eq(SysDeptRelation::getAncestor, id)) + .stream() + .map(SysDeptRelation::getDescendant) + .collect(Collectors.toList()); + + if (CollUtil.isNotEmpty(idList)) { + this.removeByIds(idList); + } + + //删除部门级联关系 + sysDeptRelationService.deleteAllDeptRealtion(id); + return Boolean.TRUE; + } + + /** + * 更新部门 + * + * @param sysDept 部门信息 + * @return 成功、失败 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public Boolean updateDeptById(SysDept sysDept) { + //更新部门状态 + this.updateById(sysDept); + //更新部门关系 + SysDeptRelation relation = new SysDeptRelation(); + relation.setAncestor(sysDept.getParentId()); + relation.setDescendant(sysDept.getDeptId()); + sysDeptRelationService.updateDeptRealtion(relation); + return Boolean.TRUE; + } + + /** + * 查询全部部门树 + * + * @return 树 + */ + @Override + public List selectTree() { + return getDeptTree(this.list(Wrappers.emptyWrapper())); + } + + /** + * 查询用户部门树 + * + * @return + */ + @Override + public List getUserTree() { + Integer deptId = SecurityUtils.getUser().getDeptId(); + List descendantIdList = sysDeptRelationService + .list(Wrappers.query().lambda() + .eq(SysDeptRelation::getAncestor, deptId)) + .stream().map(SysDeptRelation::getDescendant) + .collect(Collectors.toList()); + + List deptList = baseMapper.selectBatchIds(descendantIdList); + return getDeptTree(deptList); + } + + /** + * 构建部门树 + * + * @param depts 部门 + * @return + */ + private List getDeptTree(List depts) { + List treeList = depts.stream() + .filter(dept -> !dept.getDeptId().equals(dept.getParentId())) + .map(dept -> { + DeptTree node = new DeptTree(); + node.setId(dept.getDeptId()); + node.setParentId(dept.getParentId()); + node.setName(dept.getName()); + return node; + }).collect(Collectors.toList()); + return TreeUtil.bulid(treeList, 0); + } +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysDictServiceImpl.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysDictServiceImpl.java new file mode 100644 index 00000000..822f4a54 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysDictServiceImpl.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.pig4cloud.pig.admin.api.entity.SysDict; +import com.pig4cloud.pig.admin.mapper.SysDictMapper; +import com.pig4cloud.pig.admin.service.SysDictService; +import org.springframework.stereotype.Service; + +/** + *

+ * 字典表 服务实现类 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Service +public class SysDictServiceImpl extends ServiceImpl implements SysDictService { + +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysLogServiceImpl.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysLogServiceImpl.java new file mode 100644 index 00000000..d8823fb4 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysLogServiceImpl.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.pig4cloud.pig.admin.api.entity.SysLog; +import com.pig4cloud.pig.admin.api.vo.PreLogVo; +import com.pig4cloud.pig.admin.mapper.SysLogMapper; +import com.pig4cloud.pig.admin.service.SysLogService; +import com.pig4cloud.pig.common.core.constant.CommonConstants; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.stream.Collectors; + +/** + *

+ * 日志表 服务实现类 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Service +public class SysLogServiceImpl extends ServiceImpl implements SysLogService { + + /** + * 批量插入前端错误日志 + * + * @param preLogVoList 日志信息 + * @return true/false + */ + @Override + public Boolean saveBatchLogs(List preLogVoList) { + List sysLogs = preLogVoList.stream() + .map(pre -> { + SysLog log = new SysLog(); + log.setType(CommonConstants.STATUS_LOCK); + log.setTitle(pre.getInfo()); + log.setException(pre.getStack()); + log.setParams(pre.getMessage()); + log.setCreateTime(LocalDateTime.now()); + log.setRequestUri(pre.getUrl()); + log.setCreateBy(pre.getUser()); + return log; + }) + .collect(Collectors.toList()); + return this.saveBatch(sysLogs); + } +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysMenuServiceImpl.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysMenuServiceImpl.java new file mode 100644 index 00000000..d8e7acd5 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysMenuServiceImpl.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service.impl; + +import cn.hutool.core.collection.CollUtil; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.pig4cloud.pig.admin.api.entity.SysMenu; +import com.pig4cloud.pig.admin.api.entity.SysRoleMenu; +import com.pig4cloud.pig.admin.api.vo.MenuVO; +import com.pig4cloud.pig.admin.mapper.SysMenuMapper; +import com.pig4cloud.pig.admin.mapper.SysRoleMenuMapper; +import com.pig4cloud.pig.admin.service.SysMenuService; +import com.pig4cloud.pig.common.core.constant.CommonConstants; +import com.pig4cloud.pig.common.core.util.R; +import lombok.AllArgsConstructor; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +/** + *

+ * 菜单权限表 服务实现类 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Service +@AllArgsConstructor +public class SysMenuServiceImpl extends ServiceImpl implements SysMenuService { + private final SysRoleMenuMapper sysRoleMenuMapper; + + @Override + @Cacheable(value = "menu_details", key = "#roleId + '_menu'") + public List findMenuByRoleId(Integer roleId) { + return baseMapper.listMenusByRoleId(roleId); + } + + @Override + @Transactional(rollbackFor = Exception.class) + @CacheEvict(value = "menu_details", allEntries = true) + public R removeMenuById(Integer id) { + // 查询父节点为当前节点的节点 + List menuList = this.list(Wrappers.query() + .lambda().eq(SysMenu::getParentId, id)); + if (CollUtil.isNotEmpty(menuList)) { + return R.builder() + .code(CommonConstants.FAIL) + .msg("菜单含有下级不能删除").build(); + } + + sysRoleMenuMapper + .delete(Wrappers.query() + .lambda().eq(SysRoleMenu::getMenuId, id)); + + //删除当前菜单及其子菜单 + return new R(this.removeById(id)); + } + + @Override + @CacheEvict(value = "menu_details", allEntries = true) + public Boolean updateMenuById(SysMenu sysMenu) { + return this.updateById(sysMenu); + } +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysOauthClientDetailsServiceImpl.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysOauthClientDetailsServiceImpl.java new file mode 100644 index 00000000..6d9974a5 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysOauthClientDetailsServiceImpl.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.pig4cloud.pig.admin.api.entity.SysOauthClientDetails; +import com.pig4cloud.pig.admin.mapper.SysOauthClientDetailsMapper; +import com.pig4cloud.pig.admin.service.SysOauthClientDetailsService; +import com.pig4cloud.pig.common.core.constant.SecurityConstants; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.stereotype.Service; + +/** + *

+ * 服务实现类 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Service +public class SysOauthClientDetailsServiceImpl extends ServiceImpl implements SysOauthClientDetailsService { + + /** + * 通过ID删除客户端 + * + * @param id + * @return + */ + @Override + @CacheEvict(value = SecurityConstants.CLIENT_DETAILS_KEY, key = "#id") + public Boolean removeClientDetailsById(String id) { + return this.removeById(id); + } + + /** + * 根据客户端信息 + * + * @param clientDetails + * @return + */ + @Override + @CacheEvict(value = SecurityConstants.CLIENT_DETAILS_KEY, key = "#clientDetails.clientId") + public Boolean updateClientDetailsById(SysOauthClientDetails clientDetails) { + return this.updateById(clientDetails); + } +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysRoleMenuServiceImpl.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysRoleMenuServiceImpl.java new file mode 100644 index 00000000..826dd5fc --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysRoleMenuServiceImpl.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service.impl; + +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.pig4cloud.pig.admin.api.entity.SysRoleMenu; +import com.pig4cloud.pig.admin.mapper.SysRoleMenuMapper; +import com.pig4cloud.pig.admin.service.SysRoleMenuService; +import lombok.AllArgsConstructor; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +/** + *

+ * 角色菜单表 服务实现类 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Service +@AllArgsConstructor +public class SysRoleMenuServiceImpl extends ServiceImpl implements SysRoleMenuService { + private final CacheManager cacheManager; + + /** + * @param role + * @param roleId 角色 + * @param menuIds 菜单ID拼成的字符串,每个id之间根据逗号分隔 + * @return + */ + @Override + @Transactional(rollbackFor = Exception.class) + @CacheEvict(value = "menu_details", key = "#roleId + '_menu'") + public Boolean saveRoleMenus(String role, Integer roleId, String menuIds) { + this.remove(Wrappers.query().lambda() + .eq(SysRoleMenu::getRoleId, roleId)); + + if (StrUtil.isBlank(menuIds)) { + return Boolean.TRUE; + } + List roleMenuList = Arrays + .stream(menuIds.split(",")) + .map(menuId -> { + SysRoleMenu roleMenu = new SysRoleMenu(); + roleMenu.setRoleId(roleId); + roleMenu.setMenuId(Integer.valueOf(menuId)); + return roleMenu; + }).collect(Collectors.toList()); + + //清空userinfo + cacheManager.getCache("user_details").clear(); + return this.saveBatch(roleMenuList); + } +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysRoleServiceImpl.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysRoleServiceImpl.java new file mode 100644 index 00000000..22fa7600 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysRoleServiceImpl.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.pig4cloud.pig.admin.api.entity.SysRole; +import com.pig4cloud.pig.admin.api.entity.SysRoleMenu; +import com.pig4cloud.pig.admin.mapper.SysRoleMapper; +import com.pig4cloud.pig.admin.mapper.SysRoleMenuMapper; +import com.pig4cloud.pig.admin.service.SysRoleService; +import lombok.AllArgsConstructor; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +/** + *

+ * 服务实现类 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Service +@AllArgsConstructor +public class SysRoleServiceImpl extends ServiceImpl implements SysRoleService { + private SysRoleMenuMapper sysRoleMenuMapper; + + /** + * 通过用户ID,查询角色信息 + * + * @param userId + * @return + */ + @Override + public List findRolesByUserId(Integer userId) { + return baseMapper.listRolesByUserId(userId); + } + + /** + * 通过角色ID,删除角色,并清空角色菜单缓存 + * + * @param id + * @return + */ + @Override + @CacheEvict(value = "menu_details", allEntries = true) + @Transactional(rollbackFor = Exception.class) + public Boolean removeRoleById(Integer id) { + sysRoleMenuMapper.delete(Wrappers + .update().lambda() + .eq(SysRoleMenu::getRoleId, id)); + return this.removeById(id); + } +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysUserRoleServiceImpl.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysUserRoleServiceImpl.java new file mode 100644 index 00000000..af7ef7bc --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysUserRoleServiceImpl.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.pig4cloud.pig.admin.api.entity.SysUserRole; +import com.pig4cloud.pig.admin.mapper.SysUserRoleMapper; +import com.pig4cloud.pig.admin.service.SysUserRoleService; +import org.springframework.stereotype.Service; + +/** + *

+ * 用户角色表 服务实现类 + *

+ * + * @author lengleng + * @since 2019/2/1 + */ +@Service +public class SysUserRoleServiceImpl extends ServiceImpl implements SysUserRoleService { + + /** + * 根据用户Id删除该用户的角色关系 + * + * @param userId 用户ID + * @return boolean + * @author 寻欢·李 + * @date 2017年12月7日 16:31:38 + */ + @Override + public Boolean deleteByUserId(Integer userId) { + return baseMapper.deleteByUserId(userId); + } +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysUserServiceImpl.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysUserServiceImpl.java new file mode 100644 index 00000000..a5502b5f --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysUserServiceImpl.java @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.admin.service.impl; + +import cn.hutool.core.util.ArrayUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.pig4cloud.pig.admin.api.dto.UserDTO; +import com.pig4cloud.pig.admin.api.dto.UserInfo; +import com.pig4cloud.pig.admin.api.entity.*; +import com.pig4cloud.pig.admin.api.vo.MenuVO; +import com.pig4cloud.pig.admin.api.vo.UserVO; +import com.pig4cloud.pig.admin.mapper.SysUserMapper; +import com.pig4cloud.pig.admin.service.*; +import com.pig4cloud.pig.common.core.constant.CommonConstants; +import com.pig4cloud.pig.common.core.util.R; +import com.pig4cloud.pig.common.security.util.SecurityUtils; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.BeanUtils; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@Slf4j +@Service +@AllArgsConstructor +public class SysUserServiceImpl extends ServiceImpl implements SysUserService { + private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder(); + private final SysMenuService sysMenuService; + private final SysRoleService sysRoleService; + private final SysDeptService sysDeptService; + private final SysUserRoleService sysUserRoleService; + private final SysDeptRelationService sysDeptRelationService; + + /** + * 保存用户信息 + * + * @param userDto DTO 对象 + * @return success/fail + */ + @Override + @Transactional(rollbackFor = Exception.class) + public Boolean saveUser(UserDTO userDto) { + SysUser sysUser = new SysUser(); + BeanUtils.copyProperties(userDto, sysUser); + sysUser.setDelFlag(CommonConstants.STATUS_NORMAL); + sysUser.setPassword(ENCODER.encode(userDto.getPassword())); + baseMapper.insert(sysUser); + List userRoleList = userDto.getRole() + .stream().map(roleId -> { + SysUserRole userRole = new SysUserRole(); + userRole.setUserId(sysUser.getUserId()); + userRole.setRoleId(roleId); + return userRole; + }).collect(Collectors.toList()); + return sysUserRoleService.saveBatch(userRoleList); + } + + /** + * 通过查用户的全部信息 + * + * @param sysUser 用户 + * @return + */ + @Override + public UserInfo findUserInfo(SysUser sysUser) { + UserInfo userInfo = new UserInfo(); + userInfo.setSysUser(sysUser); + //设置角色列表 (ID) + List roleIds = sysRoleService.findRolesByUserId(sysUser.getUserId()) + .stream() + .map(SysRole::getRoleId) + .collect(Collectors.toList()); + userInfo.setRoles(ArrayUtil.toArray(roleIds, Integer.class)); + + //设置权限列表(menu.permission) + Set permissions = new HashSet<>(); + roleIds.forEach(roleId -> { + List permissionList = sysMenuService.findMenuByRoleId(roleId) + .stream() + .filter(menuVo -> StringUtils.isNotEmpty(menuVo.getPermission())) + .map(MenuVO::getPermission) + .collect(Collectors.toList()); + permissions.addAll(permissionList); + }); + userInfo.setPermissions(ArrayUtil.toArray(permissions, String.class)); + return userInfo; + } + + /** + * 分页查询用户信息(含有角色信息) + * + * @param page 分页对象 + * @param userDTO 参数列表 + * @return + */ + @Override + public IPage getUsersWithRolePage(Page page, UserDTO userDTO) { + return baseMapper.getUserVosPage(page, userDTO); + } + + /** + * 通过ID查询用户信息 + * + * @param id 用户ID + * @return 用户信息 + */ + @Override + public UserVO selectUserVoById(Integer id) { + return baseMapper.getUserVoById(id); + } + + /** + * 删除用户 + * + * @param sysUser 用户 + * @return Boolean + */ + @Override + @CacheEvict(value = "user_details", key = "#sysUser.username") + public Boolean deleteUserById(SysUser sysUser) { + sysUserRoleService.deleteByUserId(sysUser.getUserId()); + this.removeById(sysUser.getUserId()); + return Boolean.TRUE; + } + + @Override + @CacheEvict(value = "user_details", key = "#userDto.username") + public R updateUserInfo(UserDTO userDto) { + UserVO userVO = baseMapper.getUserVoByUsername(userDto.getUsername()); + SysUser sysUser = new SysUser(); + if (StrUtil.isNotBlank(userDto.getPassword()) + && StrUtil.isNotBlank(userDto.getNewpassword1())) { + if (ENCODER.matches(userDto.getPassword(), userVO.getPassword())) { + sysUser.setPassword(ENCODER.encode(userDto.getNewpassword1())); + } else { + log.warn("原密码错误,修改密码失败:{}", userDto.getUsername()); + return new R<>(Boolean.FALSE, "原密码错误,修改失败"); + } + } + sysUser.setPhone(userDto.getPhone()); + sysUser.setUserId(userVO.getUserId()); + sysUser.setAvatar(userDto.getAvatar()); + return new R<>(this.updateById(sysUser)); + } + + @Override + @CacheEvict(value = "user_details", key = "#userDto.username") + public Boolean updateUser(UserDTO userDto) { + SysUser sysUser = new SysUser(); + BeanUtils.copyProperties(userDto, sysUser); + sysUser.setUpdateTime(LocalDateTime.now()); + + if (StrUtil.isNotBlank(userDto.getPassword())) { + sysUser.setPassword(ENCODER.encode(userDto.getPassword())); + } + this.updateById(sysUser); + + sysUserRoleService.remove(Wrappers.update().lambda() + .eq(SysUserRole::getUserId, userDto.getUserId())); + userDto.getRole().forEach(roleId -> { + SysUserRole userRole = new SysUserRole(); + userRole.setUserId(sysUser.getUserId()); + userRole.setRoleId(roleId); + userRole.insert(); + }); + return Boolean.TRUE; + } + + /** + * 查询上级部门的用户信息 + * + * @param username 用户名 + * @return R + */ + @Override + public List listAncestorUsers(String username) { + SysUser sysUser = this.getOne(Wrappers.query().lambda() + .eq(SysUser::getUsername, username)); + + SysDept sysDept = sysDeptService.getById(sysUser.getDeptId()); + if (sysDept == null) { + return null; + } + + Integer parentId = sysDept.getParentId(); + return this.list(Wrappers.query().lambda() + .eq(SysUser::getDeptId, parentId)); + } + + /** + * 获取当前用户的子部门信息 + * + * @return 子部门列表 + */ + private List getChildDepts() { + Integer deptId = SecurityUtils.getUser().getDeptId(); + //获取当前部门的子部门 + return sysDeptRelationService + .list(Wrappers.query().lambda() + .eq(SysDeptRelation::getAncestor, deptId)) + .stream() + .map(SysDeptRelation::getDescendant) + .collect(Collectors.toList()); + } + +} diff --git a/pig-upms/pig-upms-biz/src/main/resources/bootstrap.yml b/pig-upms/pig-upms-biz/src/main/resources/bootstrap.yml new file mode 100644 index 00000000..aa60fb73 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/resources/bootstrap.yml @@ -0,0 +1,24 @@ +server: + port: 4000 + +spring: + application: + name: pig-upms + # 配置中心 + cloud: + config: + fail-fast: true + name: ${spring.application.name} + profile: ${spring.profiles.active} + discovery: + enabled: true + service-id: pig-config + profiles: + active: dev +# 注册中心配置 +eureka: + instance: + prefer-ip-address: true + client: + service-url: + defaultZone: http://pig:pig@pig-eureka:8761/eureka/ diff --git a/pig-upms/pig-upms-biz/src/main/resources/mapper/SysDeptMapper.xml b/pig-upms/pig-upms-biz/src/main/resources/mapper/SysDeptMapper.xml new file mode 100644 index 00000000..71c78b0d --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/resources/mapper/SysDeptMapper.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + dept_id AS deptId, parent_id AS parentId, name, sort, create_time AS createTime, update_time AS updateTime, del_flag AS delFlag + + + + + diff --git a/pig-upms/pig-upms-biz/src/main/resources/mapper/SysDeptRelationMapper.xml b/pig-upms/pig-upms-biz/src/main/resources/mapper/SysDeptRelationMapper.xml new file mode 100644 index 00000000..79dd6bb2 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/resources/mapper/SysDeptRelationMapper.xml @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + ancestor, descendant + + + + + DELETE FROM sys_dept_relation + WHERE + descendant IN ( SELECT temp.descendant FROM + ( SELECT descendant FROM sys_dept_relation WHERE ancestor = #{descendant} ) temp ) + AND ancestor IN ( SELECT temp.ancestor FROM ( SELECT ancestor FROM + sys_dept_relation WHERE descendant = #{descendant} AND ancestor != descendant ) temp ); + + INSERT INTO sys_dept_relation (ancestor, descendant) + SELECT a.ancestor, b.descendant + FROM sys_dept_relation a + CROSS JOIN sys_dept_relation b + WHERE a.descendant = #{ancestor} + AND b.ancestor = #{descendant}; + + + + + DELETE + FROM + sys_dept_relation + WHERE + descendant IN ( + SELECT + temp.descendant + FROM + ( + SELECT + descendant + FROM + sys_dept_relation + WHERE + ancestor = #{id} + ) temp + ) + + diff --git a/pig-upms/pig-upms-biz/src/main/resources/mapper/SysDictMapper.xml b/pig-upms/pig-upms-biz/src/main/resources/mapper/SysDictMapper.xml new file mode 100644 index 00000000..4dd448ef --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/resources/mapper/SysDictMapper.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/pig-upms/pig-upms-biz/src/main/resources/mapper/SysLogMapper.xml b/pig-upms/pig-upms-biz/src/main/resources/mapper/SysLogMapper.xml new file mode 100644 index 00000000..e58a6a27 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/resources/mapper/SysLogMapper.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pig-upms/pig-upms-biz/src/main/resources/mapper/SysMenuMapper.xml b/pig-upms/pig-upms-biz/src/main/resources/mapper/SysMenuMapper.xml new file mode 100644 index 00000000..083ab98b --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/resources/mapper/SysMenuMapper.xml @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pig-upms/pig-upms-biz/src/main/resources/mapper/SysOauthClientDetailsMapper.xml b/pig-upms/pig-upms-biz/src/main/resources/mapper/SysOauthClientDetailsMapper.xml new file mode 100644 index 00000000..6a46c404 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/resources/mapper/SysOauthClientDetailsMapper.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/pig-upms/pig-upms-biz/src/main/resources/mapper/SysRoleMapper.xml b/pig-upms/pig-upms-biz/src/main/resources/mapper/SysRoleMapper.xml new file mode 100644 index 00000000..9c8d19d6 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/resources/mapper/SysRoleMapper.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/pig-upms/pig-upms-biz/src/main/resources/mapper/SysUserMapper.xml b/pig-upms/pig-upms-biz/src/main/resources/mapper/SysUserMapper.xml new file mode 100644 index 00000000..43d3c0c3 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/resources/mapper/SysUserMapper.xml @@ -0,0 +1,164 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + `user`.user_id, + `user`.username, + `user`.`password`, + `user`.salt, + `user`.phone, + `user`.avatar, + `user`.wx_openid, + `user`.qq_openid, + `user`.dept_id, + `user`.create_time AS ucreate_time, + `user`.update_time AS uupdate_time, + `user`.del_flag AS udel_flag, + `user`.lock_flag AS lock_flag, + `user`.dept_id AS deptId, + r.role_id, + r.role_name, + r.role_code, + r.role_desc, + r.create_time AS rcreate_time, + r.update_time AS rupdate_time + + + + `user`.user_id, + `user`.username, + `user`.`password`, + `user`.salt, + `user`.phone, + `user`.avatar, + `user`.wx_openid, + `user`.qq_openid, + `user`.create_time AS ucreate_time, + `user`.update_time AS uupdate_time, + `user`.del_flag AS udel_flag, + `user`.lock_flag AS lock_flag, + r.role_id, + r.role_name, + r.role_code, + r.role_desc, + r.create_time AS rcreate_time, + r.update_time AS rupdate_time, + d.name AS deptName, + d.dept_id AS deptId + + + + + + + + diff --git a/pig-upms/pig-upms-biz/src/main/resources/mapper/SysUserRoleMapper.xml b/pig-upms/pig-upms-biz/src/main/resources/mapper/SysUserRoleMapper.xml new file mode 100644 index 00000000..6fa6f422 --- /dev/null +++ b/pig-upms/pig-upms-biz/src/main/resources/mapper/SysUserRoleMapper.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + DELETE FROM sys_user_role WHERE user_id = #{userId} + + + diff --git a/pig-upms/pom.xml b/pig-upms/pom.xml new file mode 100755 index 00000000..f8e991db --- /dev/null +++ b/pig-upms/pom.xml @@ -0,0 +1,36 @@ + + + + + 4.0.0 + + com.pig4cloud + pig + ${pig.version} + + + pig-upms + + pig 通用用户权限管理聚合模块 + pom + + + pig-upms-api + pig-upms-biz + + diff --git a/pig-visual/pig-codegen/Dockerfile b/pig-visual/pig-codegen/Dockerfile new file mode 100755 index 00000000..4f7c052f --- /dev/null +++ b/pig-visual/pig-codegen/Dockerfile @@ -0,0 +1,15 @@ +FROM anapsix/alpine-java:8_server-jre_unlimited + +MAINTAINER wangiegie@gmail.com + +RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime + +RUN mkdir -p /pig-codegen + +WORKDIR /pig-codegen + +EXPOSE 5003 + +ADD ./pig-visual/pig-codegen/target/pig-codegen.jar ./ + +CMD java -Djava.security.egd=file:/dev/./urandom -jar pig-codegen.jar diff --git a/pig-visual/pig-codegen/pom.xml b/pig-visual/pig-codegen/pom.xml new file mode 100755 index 00000000..31a2f619 --- /dev/null +++ b/pig-visual/pig-codegen/pom.xml @@ -0,0 +1,98 @@ + + + + + 4.0.0 + + + com.pig4cloud + pig-visual + ${pig.version} + + + pig-codegen + jar + + 代码生成模块 + + + + + org.springframework.cloud + spring-cloud-starter-config + + + + com.baomidou + mybatis-plus-boot-starter + ${mybatis-plus.version} + + + mysql + mysql-connector-java + + + + com.pig4cloud + pig-common-core + ${pig.version} + + + + com.pig4cloud + pig-common-security + ${pig.version} + + + + velocity + org.apache.velocity + ${velocity.version} + + + + org.springframework.boot + spring-boot-starter-web + + + + spring-boot-starter-tomcat + org.springframework.boot + + + + + + org.springframework.boot + spring-boot-starter-undertow + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.spotify + docker-maven-plugin + + + + diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/PigCodeGenApplication.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/PigCodeGenApplication.java new file mode 100755 index 00000000..d26b6e23 --- /dev/null +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/PigCodeGenApplication.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.codegen; + +import com.pig4cloud.pig.common.security.annotation.EnablePigFeignClients; +import org.springframework.boot.SpringApplication; +import org.springframework.cloud.client.SpringCloudApplication; + +/** + * @author lengleng + * @date 2019/2/1 + * 代码生成模块 + */ +@SpringCloudApplication +@EnablePigFeignClients +public class PigCodeGenApplication { + + public static void main(String[] args) { + SpringApplication.run(PigCodeGenApplication.class, args); + } +} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/config/MybatisPlusConfigurer.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/config/MybatisPlusConfigurer.java new file mode 100755 index 00000000..49a26aa6 --- /dev/null +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/config/MybatisPlusConfigurer.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.codegen.config; + +import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@Configuration +@MapperScan("com.pig4cloud.pig.codegen.mapper") +public class MybatisPlusConfigurer { + /** + * 分页插件 + * + * @return PaginationInterceptor + */ + @Bean + public PaginationInterceptor paginationInterceptor() { + return new PaginationInterceptor(); + } +} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/config/ResourceServerConfigurer.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/config/ResourceServerConfigurer.java new file mode 100755 index 00000000..1b3c24fc --- /dev/null +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/config/ResourceServerConfigurer.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.codegen.config; + +import com.pig4cloud.pig.common.security.component.BaseResourceServerConfigurerAdapter; +import lombok.AllArgsConstructor; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; +import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; + +/** + * @author lengleng + * @date 2019/2/1 + */ +@Configuration +@EnableResourceServer +@AllArgsConstructor +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class ResourceServerConfigurer extends BaseResourceServerConfigurerAdapter { + + /** + * 重写抽象类实现,不需要调用feign 获取 userDetailsService + * + * @param resources + */ + @Override + public void configure(ResourceServerSecurityConfigurer resources) { + notGetUser(resources); + } +} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/SysGeneratorController.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/SysGeneratorController.java new file mode 100755 index 00000000..847ab9fa --- /dev/null +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/SysGeneratorController.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.codegen.controller; + +import cn.hutool.core.io.IoUtil; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.pig4cloud.pig.codegen.entity.GenConfig; +import com.pig4cloud.pig.codegen.service.SysGeneratorService; +import com.pig4cloud.pig.common.core.util.R; +import lombok.AllArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * 代码生成器 + * + * @author lengleng + * @date 2019/2/1 + */ +@RestController +@AllArgsConstructor +@RequestMapping("/generator") +public class SysGeneratorController { + private final SysGeneratorService sysGeneratorService; + + /** + * 列表 + * + * @param tableName 参数集 + * @return 数据库表 + */ + @GetMapping("/page") + public R list(Page page, String tableName) { + return new R<>(sysGeneratorService.queryPage(page,tableName)); + } + + /** + * 生成代码 + */ + @PostMapping("/code") + public void code(@RequestBody GenConfig genConfig, HttpServletResponse response) throws IOException { + byte[] data = sysGeneratorService.generatorCode(genConfig); + + response.reset(); + response.setHeader("Content-Disposition", String.format("attachment; filename=%s.zip", genConfig.getTableName())); + response.addHeader("Content-Length", "" + data.length); + response.setContentType("application/octet-stream; charset=UTF-8"); + + IoUtil.write(response.getOutputStream(), Boolean.TRUE, data); + } +} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/ColumnEntity.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/ColumnEntity.java new file mode 100755 index 00000000..b6aba1c2 --- /dev/null +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/ColumnEntity.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.codegen.entity; + +import lombok.Data; + +/** + * @author lengleng + * @date 2019/2/1 + * 列属性: https://blog.csdn.net/lkforce/article/details/79557482 + */ +@Data +public class ColumnEntity { + /** + * 列表 + */ + private String columnName; + /** + * 数据类型 + */ + private String dataType; + /** + * 备注 + */ + private String comments; + + /** + * 驼峰属性 + */ + private String caseAttrName; + /** + * 普通属性 + */ + private String lowerAttrName; + /** + * 属性类型 + */ + private String attrType; + /** + * 其他信息。 + */ + private String extra; +} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/GenConfig.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/GenConfig.java new file mode 100755 index 00000000..f787ffaa --- /dev/null +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/GenConfig.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.codegen.entity; + +import lombok.Data; + +/** + * @author lengleng + * @date 2019/2/1 + * 生成配置 + */ +@Data +public class GenConfig { + /** + * 包名 + */ + private String packageName; + /** + * 作者 + */ + private String author; + /** + * 模块名称 + */ + private String moduleName; + /** + * 表前缀 + */ + private String tablePrefix; + + /** + * 表名称 + */ + private String tableName; + + /** + * 表备注 + */ + private String comments; +} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/TableEntity.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/TableEntity.java new file mode 100755 index 00000000..fb72c455 --- /dev/null +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/TableEntity.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.codegen.entity; + +import lombok.Data; + +import java.util.List; + +/** + * @author lengleng + * @date 2019/2/1 + * 表属性: https://blog.csdn.net/lkforce/article/details/79557482 + */ +@Data +public class TableEntity { + /** + * 名称 + */ + private String tableName; + /** + * 备注 + */ + private String comments; + /** + * 主键 + */ + private ColumnEntity pk; + /** + * 列名 + */ + private List columns; + /** + * 驼峰类型 + */ + private String caseClassName; + /** + * 普通类型 + */ + private String lowerClassName; +} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/mapper/SysGeneratorMapper.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/mapper/SysGeneratorMapper.java new file mode 100755 index 00000000..0101b48d --- /dev/null +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/mapper/SysGeneratorMapper.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.codegen.mapper; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +/** + * 代码生成器 + * + * @author lengleng + * @date 2019/2/1 + */ +public interface SysGeneratorMapper { + + /** + * 分页查询表格 + * + * @param page + * @param tableName + * @return + */ + IPage>> queryList(Page page, @Param("tableName") String tableName); + + /** + * 查询表信息 + * + * @param tableName 表名称 + * @return + */ + Map queryTable(String tableName); + + /** + * 查询表列信息 + * + * @param tableName 表名称 + * @return + */ + List> queryColumns(String tableName); +} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/SysGeneratorService.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/SysGeneratorService.java new file mode 100755 index 00000000..2af536f7 --- /dev/null +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/SysGeneratorService.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.codegen.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.pig4cloud.pig.codegen.entity.GenConfig; + +import java.util.List; +import java.util.Map; + +/** + * @author lengleng + * @date 2019/2/1 + */ +public interface SysGeneratorService { + /** + * 生成代码 + * + * @param tableNames 表名称 + * @return + */ + byte[] generatorCode(GenConfig tableNames); + + /** + * 分页查询表 + * @param tableName 表名 + * @return + */ + IPage>> queryPage(Page page, String tableName); +} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/SysGeneratorServiceImpl.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/SysGeneratorServiceImpl.java new file mode 100755 index 00000000..b10545ff --- /dev/null +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/SysGeneratorServiceImpl.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.codegen.service.impl; + +import cn.hutool.core.io.IoUtil; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.pig4cloud.pig.codegen.entity.GenConfig; +import com.pig4cloud.pig.codegen.util.GenUtils; +import com.pig4cloud.pig.codegen.mapper.SysGeneratorMapper; +import com.pig4cloud.pig.codegen.service.SysGeneratorService; +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Service; + +import java.io.ByteArrayOutputStream; +import java.util.List; +import java.util.Map; +import java.util.zip.ZipOutputStream; + +/** + * 代码生成器 + * + * @author lengleng + * @date 2019/2/1 + */ +@Service +@AllArgsConstructor +public class SysGeneratorServiceImpl implements SysGeneratorService { + private final SysGeneratorMapper sysGeneratorMapper; + + + /** + * 分页查询表 + * + * @param tableName 查询条件 + * @return + */ + @Override + public IPage>> queryPage(Page page, String tableName) { + return sysGeneratorMapper.queryList(page,tableName); + } + + /** + * 生成代码 + * + * @param genConfig 生成配置 + * @return + */ + @Override + public byte[] generatorCode(GenConfig genConfig) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ZipOutputStream zip = new ZipOutputStream(outputStream); + + //查询表信息 + Map table = queryTable(genConfig.getTableName()); + //查询列信息 + List> columns = queryColumns(genConfig.getTableName()); + //生成代码 + GenUtils.generatorCode(genConfig, table, columns, zip); + IoUtil.close(zip); + return outputStream.toByteArray(); + } + + private Map queryTable(String tableName) { + return sysGeneratorMapper.queryTable(tableName); + } + + private List> queryColumns(String tableName) { + return sysGeneratorMapper.queryColumns(tableName); + } +} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/GenUtils.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/GenUtils.java new file mode 100755 index 00000000..1d3125bb --- /dev/null +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/GenUtils.java @@ -0,0 +1,291 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.codegen.util; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.io.IoUtil; +import cn.hutool.core.util.CharsetUtil; +import cn.hutool.core.util.StrUtil; +import com.pig4cloud.pig.codegen.entity.GenConfig; +import com.pig4cloud.pig.codegen.entity.TableEntity; +import com.pig4cloud.pig.codegen.entity.ColumnEntity; +import com.pig4cloud.pig.common.core.constant.CommonConstants; +import com.pig4cloud.pig.common.core.exception.CheckedException; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.configuration.Configuration; +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.configuration.PropertiesConfiguration; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.WordUtils; +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.Velocity; + +import java.io.File; +import java.io.IOException; +import java.io.StringWriter; +import java.util.*; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +/** + * 代码生成器 工具类 + * + * @author lengleng + * @date 2019/2/1 + */ +@Slf4j +public class GenUtils { + + private static final String ENTITY_JAVA_VM = "Entity.java.vm"; + private static final String MAPPER_JAVA_VM = "Mapper.java.vm"; + private static final String SERVICE_JAVA_VM = "Service.java.vm"; + private static final String SERVICE_IMPL_JAVA_VM = "ServiceImpl.java.vm"; + private static final String CONTROLLER_JAVA_VM = "Controller.java.vm"; + private static final String MAPPER_XML_VM = "Mapper.xml.vm"; + private static final String MENU_SQL_VM = "menu.sql.vm"; + private static final String INDEX_VUE_VM = "index.vue.vm"; + private static final String API_JS_VM = "api.js.vm"; + private static final String CRUD_JS_VM = "crud.js.vm"; + + private static List getTemplates() { + List templates = new ArrayList<>(); + templates.add("template/Entity.java.vm"); + templates.add("template/Mapper.java.vm"); + templates.add("template/Mapper.xml.vm"); + templates.add("template/Service.java.vm"); + templates.add("template/ServiceImpl.java.vm"); + templates.add("template/Controller.java.vm"); + templates.add("template/menu.sql.vm"); + + templates.add("template/index.vue.vm"); + templates.add("template/api.js.vm"); + templates.add("template/crud.js.vm"); + return templates; + } + + /** + * 生成代码 + */ + public static void generatorCode(GenConfig genConfig, Map table, + List> columns, ZipOutputStream zip) { + //配置信息 + Configuration config = getConfig(); + boolean hasBigDecimal = false; + //表信息 + TableEntity tableEntity = new TableEntity(); + tableEntity.setTableName(table.get("tableName")); + + if (StrUtil.isNotBlank(genConfig.getComments())) { + tableEntity.setComments(genConfig.getComments()); + } else { + tableEntity.setComments(table.get("tableComment")); + } + + String tablePrefix; + if (StrUtil.isNotBlank(genConfig.getTablePrefix())) { + tablePrefix = genConfig.getTablePrefix(); + } else { + tablePrefix = config.getString("tablePrefix"); + } + + //表名转换成Java类名 + String className = tableToJava(tableEntity.getTableName(), tablePrefix); + tableEntity.setCaseClassName(className); + tableEntity.setLowerClassName(StringUtils.uncapitalize(className)); + + //列信息 + List columnList = new ArrayList<>(); + for (Map column : columns) { + ColumnEntity columnEntity = new ColumnEntity(); + columnEntity.setColumnName(column.get("columnName")); + columnEntity.setDataType(column.get("dataType")); + columnEntity.setComments(column.get("columnComment")); + columnEntity.setExtra(column.get("extra")); + + //列名转换成Java属性名 + String attrName = columnToJava(columnEntity.getColumnName()); + columnEntity.setCaseAttrName(attrName); + columnEntity.setLowerAttrName(StringUtils.uncapitalize(attrName)); + + //列的数据类型,转换成Java类型 + String attrType = config.getString(columnEntity.getDataType(), "unknowType"); + columnEntity.setAttrType(attrType); + if (!hasBigDecimal && "BigDecimal".equals(attrType)) { + hasBigDecimal = true; + } + //是否主键 + if ("PRI".equalsIgnoreCase(column.get("columnKey")) && tableEntity.getPk() == null) { + tableEntity.setPk(columnEntity); + } + + columnList.add(columnEntity); + } + tableEntity.setColumns(columnList); + + //没主键,则第一个字段为主键 + if (tableEntity.getPk() == null) { + tableEntity.setPk(tableEntity.getColumns().get(0)); + } + + //设置velocity资源加载器 + Properties prop = new Properties(); + prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); + Velocity.init(prop); + //封装模板数据 + Map map = new HashMap<>(16); + map.put("tableName", tableEntity.getTableName()); + map.put("pk", tableEntity.getPk()); + map.put("className", tableEntity.getCaseClassName()); + map.put("classname", tableEntity.getLowerClassName()); + map.put("pathName", tableEntity.getLowerClassName().toLowerCase()); + map.put("columns", tableEntity.getColumns()); + map.put("hasBigDecimal", hasBigDecimal); + map.put("datetime", DateUtil.now()); + + if (StrUtil.isNotBlank(genConfig.getComments())) { + map.put("comments", genConfig.getComments()); + } else { + map.put("comments", tableEntity.getComments()); + } + + if (StrUtil.isNotBlank(genConfig.getAuthor())) { + map.put("author", genConfig.getAuthor()); + } else { + map.put("author", config.getString("author")); + } + + if (StrUtil.isNotBlank(genConfig.getModuleName())) { + map.put("moduleName", genConfig.getModuleName()); + } else { + map.put("moduleName", config.getString("moduleName")); + } + + if (StrUtil.isNotBlank(genConfig.getPackageName())) { + map.put("package", genConfig.getPackageName()); + map.put("mainPath", genConfig.getPackageName()); + } else { + map.put("package", config.getString("package")); + map.put("mainPath", config.getString("mainPath")); + } + VelocityContext context = new VelocityContext(map); + + //获取模板列表 + List templates = getTemplates(); + for (String template : templates) { + //渲染模板 + StringWriter sw = new StringWriter(); + Template tpl = Velocity.getTemplate(template, CharsetUtil.UTF_8); + tpl.merge(context, sw); + + try { + //添加到zip + zip.putNextEntry(new ZipEntry(Objects + .requireNonNull(getFileName(template, tableEntity.getCaseClassName() + , map.get("package").toString(), map.get("moduleName").toString())))); + IoUtil.write(zip, CharsetUtil.UTF_8, false, sw.toString()); + IoUtil.close(sw); + zip.closeEntry(); + } catch (IOException e) { + throw new CheckedException("渲染模板失败,表名:" + tableEntity.getTableName(), e); + } + } + } + + + /** + * 列名转换成Java属性名 + */ + private static String columnToJava(String columnName) { + return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", ""); + } + + /** + * 表名转换成Java类名 + */ + private static String tableToJava(String tableName, String tablePrefix) { + if (StringUtils.isNotBlank(tablePrefix)) { + tableName = tableName.replace(tablePrefix, ""); + } + return columnToJava(tableName); + } + + /** + * 获取配置信息 + */ + private static Configuration getConfig() { + try { + return new PropertiesConfiguration("generator.properties"); + } catch (ConfigurationException e) { + throw new CheckedException("获取配置文件失败,", e); + } + } + + /** + * 获取文件名 + */ + private static String getFileName(String template, String className, String packageName, String moduleName) { + String packagePath = CommonConstants.BACK_END_PROJECT + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator; + if (StringUtils.isNotBlank(packageName)) { + packagePath += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator; + } + + if (template.contains(ENTITY_JAVA_VM)) { + return packagePath + "entity" + File.separator + className + ".java"; + } + + if (template.contains(MAPPER_JAVA_VM)) { + return packagePath + "mapper" + File.separator + className + "Mapper.java"; + } + + if (template.contains(SERVICE_JAVA_VM)) { + return packagePath + "service" + File.separator + className + "Service.java"; + } + + if (template.contains(SERVICE_IMPL_JAVA_VM)) { + return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java"; + } + + if (template.contains(CONTROLLER_JAVA_VM)) { + return packagePath + "controller" + File.separator + className + "Controller.java"; + } + + if (template.contains(MAPPER_XML_VM)) { + return CommonConstants.BACK_END_PROJECT + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "mapper" + File.separator + className + "Mapper.xml"; + } + + if (template.contains(MENU_SQL_VM)) { + return className.toLowerCase() + "_menu.sql"; + } + + if (template.contains(INDEX_VUE_VM)) { + return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "views" + + File.separator + moduleName + File.separator + className.toLowerCase() + File.separator + "index.vue"; + } + + if (template.contains(API_JS_VM)) { + return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "api" + File.separator + className.toLowerCase() + ".js"; + } + + if (template.contains(CRUD_JS_VM)) { + return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "const" + + File.separator + "crud" + File.separator + className.toLowerCase() + ".js"; + } + + return null; + } +} diff --git a/pig-visual/pig-codegen/src/main/resources/bootstrap.yml b/pig-visual/pig-codegen/src/main/resources/bootstrap.yml new file mode 100755 index 00000000..717cb824 --- /dev/null +++ b/pig-visual/pig-codegen/src/main/resources/bootstrap.yml @@ -0,0 +1,26 @@ +server: + port: 5003 + +spring: + application: + name: pig-codegen + #配置中心 + cloud: + config: + fail-fast: true + name: ${spring.application.name} + profile: dev + discovery: + enabled: true + service-id: pig-config + +# 注册中心配置 +eureka: + instance: + prefer-ip-address: true + client: + service-url: + defaultZone: http://pig:pig@pig-eureka:8761/eureka/ +logging: + level: + root: info diff --git a/pig-visual/pig-codegen/src/main/resources/generator.properties b/pig-visual/pig-codegen/src/main/resources/generator.properties new file mode 100755 index 00000000..f04d2145 --- /dev/null +++ b/pig-visual/pig-codegen/src/main/resources/generator.properties @@ -0,0 +1,50 @@ +# +# Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). +#

+# Licensed under the GNU Lesser General Public License 3.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +#

+# https://www.gnu.org/licenses/lgpl.html +#

+# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +#\u4EE3\u7801\u751F\u6210\u5668\uFF0C\u914D\u7F6E\u4FE1\u606F + +mainPath=com.pig4cloud.pig +#\u5305\u540D +package=com.pig4cloud.pig +moduleName=generator +#\u4F5C\u8005 +author=pig code generator + +#\u8868\u524D\u7F00(\u7C7B\u540D\u4E0D\u4F1A\u5305\u542B\u8868\u524D\u7F00) +tablePrefix=tb_ + +#\u7C7B\u578B\u8F6C\u6362\uFF0C\u914D\u7F6E\u4FE1\u606F +tinyint=Integer +smallint=Integer +mediumint=Integer +int=Integer +integer=Integer +bigint=Long +float=Float +double=Double +decimal=BigDecimal +bit=Boolean + +char=String +varchar=String +tinytext=String +text=String +mediumtext=String +longtext=String + +date=LocalDateTime +datetime=LocalDateTime +timestamp=LocalDateTime diff --git a/pig-visual/pig-codegen/src/main/resources/mapper/SysGeneratorMapper.xml b/pig-visual/pig-codegen/src/main/resources/mapper/SysGeneratorMapper.xml new file mode 100755 index 00000000..c56b9f71 --- /dev/null +++ b/pig-visual/pig-codegen/src/main/resources/mapper/SysGeneratorMapper.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + diff --git a/pig-visual/pig-codegen/src/main/resources/template/Controller.java.vm b/pig-visual/pig-codegen/src/main/resources/template/Controller.java.vm new file mode 100755 index 00000000..4431259d --- /dev/null +++ b/pig-visual/pig-codegen/src/main/resources/template/Controller.java.vm @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2018-2025, lengleng All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of the pig4cloud.com developer nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * Author: lengleng (wangiegie@gmail.com) + */ +package ${package}.${moduleName}.controller; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.pig4cloud.pig.common.core.util.R; +import com.pig4cloud.pig.common.log.annotation.SysLog; +import ${package}.${moduleName}.entity.${className}; +import ${package}.${moduleName}.service.${className}Service; +import lombok.AllArgsConstructor; +import org.springframework.web.bind.annotation.*; + + +/** + * ${comments} + * + * @author ${author} + * @date ${datetime} + */ +@RestController +@AllArgsConstructor +@RequestMapping("/${pathName}") +public class ${className}Controller { + + private final ${className}Service ${classname}Service; + + /** + * 简单分页查询 + * @param page 分页对象 + * @param ${classname} ${comments} + * @return + */ + @GetMapping("/page") + public R> get${className}Page(Page<${className}> page, ${className} ${classname}) { + return new R<>(${classname}Service.get${className}Page(page,${classname})); + } + + + /** + * 通过id查询单条记录 + * @param ${pk.lowerAttrName} + * @return R + */ + @GetMapping("/{${pk.lowerAttrName}}") + public R<${className}> getById(@PathVariable("${pk.lowerAttrName}") ${pk.attrType} ${pk.lowerAttrName}){ + return new R<>(${classname}Service.getById(${pk.lowerAttrName})); + } + + /** + * 新增记录 + * @param ${classname} + * @return R + */ + @SysLog("新增${comments}") + @PostMapping + public R save(@RequestBody ${className} ${classname}){ + return new R<>(${classname}Service.save(${classname})); + } + + /** + * 修改记录 + * @param ${classname} + * @return R + */ + @SysLog("修改${comments}") + @PutMapping + public R update(@RequestBody ${className} ${classname}){ + return new R<>(${classname}Service.updateById(${classname})); + } + + /** + * 通过id删除一条记录 + * @param ${pk.lowerAttrName} + * @return R + */ + @SysLog("删除${comments}") + @DeleteMapping("/{${pk.lowerAttrName}}") + public R removeById(@PathVariable ${pk.attrType} ${pk.lowerAttrName}){ + return new R<>(${classname}Service.removeById(${pk.lowerAttrName})); + } + +} diff --git a/pig-visual/pig-codegen/src/main/resources/template/Entity.java.vm b/pig-visual/pig-codegen/src/main/resources/template/Entity.java.vm new file mode 100755 index 00000000..0b2d2361 --- /dev/null +++ b/pig-visual/pig-codegen/src/main/resources/template/Entity.java.vm @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2018-2025, lengleng All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of the pig4cloud.com developer nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * Author: lengleng (wangiegie@gmail.com) + */ +package ${package}.${moduleName}.entity; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.baomidou.mybatisplus.extension.activerecord.Model; +import lombok.Data; +import lombok.EqualsAndHashCode; +#if(${hasBigDecimal}) +import java.math.BigDecimal; +#end +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + * ${comments} + * + * @author ${author} + * @date ${datetime} + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("${tableName}") +public class ${className} extends Model<${className}> { +private static final long serialVersionUID = 1L; + + #foreach ($column in $columns) + /** + * $column.comments + */ + #if($column.columnName == $pk.columnName) + @TableId + #end + private $column.attrType $column.lowerAttrName; + #end + +} diff --git a/pig-visual/pig-codegen/src/main/resources/template/Mapper.java.vm b/pig-visual/pig-codegen/src/main/resources/template/Mapper.java.vm new file mode 100755 index 00000000..d1f584b6 --- /dev/null +++ b/pig-visual/pig-codegen/src/main/resources/template/Mapper.java.vm @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2018-2025, lengleng All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of the pig4cloud.com developer nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * Author: lengleng (wangiegie@gmail.com) + */ +package ${package}.${moduleName}.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import ${package}.${moduleName}.entity.${className}; +import org.apache.ibatis.annotations.Param; + +/** + * ${comments} + * + * @author ${author} + * @date ${datetime} + */ +public interface ${className}Mapper extends BaseMapper<${className}> { + /** + * ${comments}简单分页查询 + * @param ${classname} ${comments} + * @return + */ + IPage<${className}> get${className}Page(Page page, @Param("${classname}") ${className} ${classname}); + + +} diff --git a/pig-visual/pig-codegen/src/main/resources/template/Mapper.xml.vm b/pig-visual/pig-codegen/src/main/resources/template/Mapper.xml.vm new file mode 100755 index 00000000..634139d3 --- /dev/null +++ b/pig-visual/pig-codegen/src/main/resources/template/Mapper.xml.vm @@ -0,0 +1,58 @@ + + + + + + + + + + #foreach($column in $columns) + #if($column.lowerAttrName==$pk.lowerAttrName) + + #else + + #end + #end + + + + + + + + diff --git a/pig-visual/pig-codegen/src/main/resources/template/Service.java.vm b/pig-visual/pig-codegen/src/main/resources/template/Service.java.vm new file mode 100755 index 00000000..9ea358cd --- /dev/null +++ b/pig-visual/pig-codegen/src/main/resources/template/Service.java.vm @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2018-2025, lengleng All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of the pig4cloud.com developer nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * Author: lengleng (wangiegie@gmail.com) + */ +package ${package}.${moduleName}.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import ${package}.${moduleName}.entity.${className}; + +/** + * ${comments} + * + * @author ${author} + * @date ${datetime} + */ +public interface ${className}Service extends IService<${className}> { + + /** + * ${comments}简单分页查询 + * @param ${classname} ${comments} + * @return + */ + IPage<${className}> get${className}Page(Page<${className}> page, ${className} ${classname}); + + +} diff --git a/pig-visual/pig-codegen/src/main/resources/template/ServiceImpl.java.vm b/pig-visual/pig-codegen/src/main/resources/template/ServiceImpl.java.vm new file mode 100755 index 00000000..01921580 --- /dev/null +++ b/pig-visual/pig-codegen/src/main/resources/template/ServiceImpl.java.vm @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2018-2025, lengleng All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of the pig4cloud.com developer nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * Author: lengleng (wangiegie@gmail.com) + */ +package ${package}.${moduleName}.service.impl; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import ${package}.${moduleName}.entity.${className}; +import ${package}.${moduleName}.service.${className}Service; +import org.springframework.stereotype.Service; + +/** + * ${comments} + * + * @author ${author} + * @date ${datetime} + */ +@Service("${classname}Service") +public class ${className}ServiceImpl extends ServiceImpl<${className}Mapper, ${className}> implements ${className}Service { + + /** + * ${comments}简单分页查询 + * @param ${classname} ${comments} + * @return + */ + @Override + public IPage<${className}> get${className}Page(Page<${className}> page, ${className} ${classname}){ + return baseMapper.get${className}Page(page,${classname}); + } + +} diff --git a/pig-visual/pig-codegen/src/main/resources/template/api.js.vm b/pig-visual/pig-codegen/src/main/resources/template/api.js.vm new file mode 100755 index 00000000..e257ce76 --- /dev/null +++ b/pig-visual/pig-codegen/src/main/resources/template/api.js.vm @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2018-2025, lengleng All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of the pig4cloud.com developer nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * Author: lengleng (wangiegie@gmail.com) + */ + +import request from '@/router/axios' + +export function fetchList(query) { + return request({ + url: '/${moduleName}/${pathName}/page', + method: 'get', + params: query + }) +} + +export function addObj(obj) { + return request({ + url: '/${moduleName}/${pathName}', + method: 'post', + data: obj + }) +} + +export function getObj(id) { + return request({ + url: '/${moduleName}/${pathName}/' + id, + method: 'get' + }) +} + +export function delObj(id) { + return request({ + url: '/${moduleName}/${pathName}/' + id, + method: 'delete' + }) +} + +export function putObj(obj) { + return request({ + url: '/${moduleName}/${pathName}', + method: 'put', + data: obj + }) +} diff --git a/pig-visual/pig-codegen/src/main/resources/template/crud.js.vm b/pig-visual/pig-codegen/src/main/resources/template/crud.js.vm new file mode 100755 index 00000000..11acbe1e --- /dev/null +++ b/pig-visual/pig-codegen/src/main/resources/template/crud.js.vm @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2018-2025, lengleng All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of the pig4cloud.com developer nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * Author: lengleng (wangiegie@gmail.com) + */ + +export const tableOption = { + 'border': true, + 'index': true, + 'indexLabel': '序号', + 'stripe': true, + 'menuAlign': "center", + 'align': "center", + 'editBtn': false, + 'delBtn': false, + 'addBtn': false, + 'dic': [], + 'column': [ +#foreach ($column in $columns) + { + label: '$column.comments', + prop: '$column.lowerAttrName' + }, +#end + ] +} diff --git a/pig-visual/pig-codegen/src/main/resources/template/index.vue.vm b/pig-visual/pig-codegen/src/main/resources/template/index.vue.vm new file mode 100755 index 00000000..1ea1d095 --- /dev/null +++ b/pig-visual/pig-codegen/src/main/resources/template/index.vue.vm @@ -0,0 +1,171 @@ + + + + + + diff --git a/pig-visual/pig-codegen/src/main/resources/template/menu.sql.vm b/pig-visual/pig-codegen/src/main/resources/template/menu.sql.vm new file mode 100755 index 00000000..44ac11a3 --- /dev/null +++ b/pig-visual/pig-codegen/src/main/resources/template/menu.sql.vm @@ -0,0 +1,13 @@ +-- 该脚本不要执行,请完善 ID 对应关系,注意层级关系 !!!! + +-- 菜单SQL +insert into `sys_menu` ( `parent_id`, `component`, `permission`, `type`, `path`, `icon`, `menu_id`, `del_flag`, `create_time`, `sort`, `update_time`, `name`) + values ( '父菜单ID', 'views/${moduleName}/${pathName}/index', '', '0', '${pathName}', 'icon-bangzhushouji', '菜单ID', '0', '2018-01-20 13:17:19', '8', '2018-07-29 13:38:19', '${comments}管理'); + +-- 菜单对应按钮SQL +insert into `sys_menu` ( `parent_id`, `component`, `permission`, `type`, `path`, `icon`, `menu_id`, `del_flag`, `create_time`, `sort`, `update_time`, `name`) + values ( '菜单ID', null, '${moduleName}_${pathName}_add', '1', null, '1', '子按钮ID1', '0', '2018-05-15 21:35:18', '0', '2018-07-29 13:38:59', '${comments}新增'); +insert into `sys_menu` ( `parent_id`, `component`, `permission`, `type`, `path`, `icon`, `menu_id`, `del_flag`, `create_time`, `sort`, `update_time`, `name`) + values ( '菜单ID', null, '${moduleName}_${pathName}_edit', '1', null, '1', '子按钮ID2', '0', '2018-05-15 21:35:18', '1', '2018-07-29 13:38:59', '${comments}修改'); +insert into `sys_menu` ( `parent_id`, `component`, `permission`, `type`, `path`, `icon`, `menu_id`, `del_flag`, `create_time`, `sort`, `update_time`, `name`) + values ( '菜单ID', null, '${moduleName}_${pathName}_del', '1', null, '1', '子按钮ID3', '0', '2018-05-15 21:35:18', '2', '2018-07-29 13:38:59', '${comments}删除'); diff --git a/pig-visual/pig-monitor/Dockerfile b/pig-visual/pig-monitor/Dockerfile new file mode 100755 index 00000000..abcaf4f7 --- /dev/null +++ b/pig-visual/pig-monitor/Dockerfile @@ -0,0 +1,15 @@ +FROM anapsix/alpine-java:8_server-jre_unlimited + +MAINTAINER wangiegie@gmail.com + +RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime + +RUN mkdir -p /pig-monitor + +WORKDIR /pig-monitor + +EXPOSE 5001 + +ADD ./pig-visual/pig-monitor/target/pig-monitor.jar ./ + +CMD java -Djava.security.egd=file:/dev/./urandom -jar pig-monitor.jar diff --git a/pig-visual/pig-monitor/pom.xml b/pig-visual/pig-monitor/pom.xml new file mode 100755 index 00000000..f6595c65 --- /dev/null +++ b/pig-visual/pig-monitor/pom.xml @@ -0,0 +1,81 @@ + + + + + 4.0.0 + + com.pig4cloud + pig-visual + ${pig.version} + + + pig-monitor + jar + + pig 监控模块,基于 spring boot admin + + + + + de.codecentric + spring-boot-admin-starter-server + ${spring-boot-admin.version} + + + + org.springframework.cloud + spring-cloud-starter-config + + + + org.springframework.boot + spring-boot-starter-web + + + + spring-boot-starter-tomcat + org.springframework.boot + + + + + + org.springframework.boot + spring-boot-starter-undertow + + + + org.springframework.boot + spring-boot-starter-security + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.spotify + docker-maven-plugin + + + + + diff --git a/pig-visual/pig-monitor/src/main/java/com/pig4cloud/pig/monitor/PigMonitorApplication.java b/pig-visual/pig-monitor/src/main/java/com/pig4cloud/pig/monitor/PigMonitorApplication.java new file mode 100755 index 00000000..367fac7c --- /dev/null +++ b/pig-visual/pig-monitor/src/main/java/com/pig4cloud/pig/monitor/PigMonitorApplication.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.monitor; + + +import de.codecentric.boot.admin.server.config.EnableAdminServer; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * @author lengleng + * @date 2018年06月21日 + * 监控中心 + */ +@EnableAdminServer +@SpringBootApplication +public class PigMonitorApplication { + + public static void main(String[] args) { + SpringApplication.run(PigMonitorApplication.class, args); + } +} diff --git a/pig-visual/pig-monitor/src/main/java/com/pig4cloud/pig/monitor/config/WebSecurityConfigurer.java b/pig-visual/pig-monitor/src/main/java/com/pig4cloud/pig/monitor/config/WebSecurityConfigurer.java new file mode 100755 index 00000000..053f557d --- /dev/null +++ b/pig-visual/pig-monitor/src/main/java/com/pig4cloud/pig/monitor/config/WebSecurityConfigurer.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com). + *

+ * Licensed under the GNU Lesser General Public License 3.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.gnu.org/licenses/lgpl.html + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.monitor.config; + +import de.codecentric.boot.admin.server.config.AdminServerProperties; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; + +/** + * WebSecurityConfigurer + * + * @author lishangbu + * @date 2019/2/1 + */ +@Configuration +public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter { + private final String adminContextPath; + + public WebSecurityConfigurer(AdminServerProperties adminServerProperties) { + this.adminContextPath = adminServerProperties.getContextPath(); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + // @formatter:off + SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler(); + successHandler.setTargetUrlParameter("redirectTo"); + successHandler.setDefaultTargetUrl(adminContextPath + "/"); + + http + .headers().frameOptions().disable() + .and().authorizeRequests() + .antMatchers(adminContextPath + "/assets/**" + , adminContextPath + "/login" + , adminContextPath + "/actuator/**" + ).permitAll() + .anyRequest().authenticated() + .and() + .formLogin().loginPage(adminContextPath + "/login") + .successHandler(successHandler).and() + .logout().logoutUrl(adminContextPath + "/logout") + .and() + .httpBasic().and() + .csrf() + .disable(); + // @formatter:on + } +} diff --git a/pig-visual/pig-monitor/src/main/resources/bootstrap.yml b/pig-visual/pig-monitor/src/main/resources/bootstrap.yml new file mode 100755 index 00000000..d6602f43 --- /dev/null +++ b/pig-visual/pig-monitor/src/main/resources/bootstrap.yml @@ -0,0 +1,23 @@ +server: + port: 5001 + +spring: + application: + name: pig-monitor + #配置中心 + cloud: + config: + fail-fast: true + name: ${spring.application.name} + profile: dev + discovery: + enabled: true + service-id: pig-config + +# 注册中心配置 +eureka: + instance: + prefer-ip-address: true + client: + service-url: + defaultZone: http://pig:pig@pig-eureka:8761/eureka/ diff --git a/pig-visual/pom.xml b/pig-visual/pom.xml new file mode 100755 index 00000000..2eede87f --- /dev/null +++ b/pig-visual/pom.xml @@ -0,0 +1,35 @@ + + + + + 4.0.0 + + com.pig4cloud + pig + ${pig.version} + + + pig-visual + pig 图形化功能模块 + pom + + + pig-codegen + pig-monitor + + diff --git a/pom.xml b/pom.xml new file mode 100755 index 00000000..667a6ba3 --- /dev/null +++ b/pom.xml @@ -0,0 +1,212 @@ + + + + + 4.0.0 + + com.pig4cloud + pig + ${pig.version} + ${project.artifactId} + pom + https://www.pig4cloud.com + + + 2.0.0 + 2.0.8.RELEASE + Finchley.SR2 + Cairo-SR5 + UTF-8 + 1.8 + 1.8 + 2.0.4 + 4.4.3 + 3.0.6 + 0.0.9 + 1.7 + 2.1.0 + 2.3.3.RELEASE + 2.9.6 + http://192.168.0.13:4243 + 192.168.0.13:5000 + + + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + + + + org.springframework.boot + spring-boot-configuration-processor + true + + + com.github.ulisesbocchio + jasypt-spring-boot-starter + ${jasypt.version} + + + + org.springframework.boot + spring-boot-starter-actuator + + + + de.codecentric + spring-boot-admin-starter-client + ${spring-boot-admin.version} + + + + org.springframework.cloud + spring-cloud-starter-netflix-hystrix + + + + org.projectlombok + lombok + provided + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + pig-eureka + pig-config + pig-gateway + pig-auth + pig-upms + pig-common + pig-visual + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + io.spring.platform + platform-bom + ${spring-platform.version} + pom + import + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + com.fasterxml.jackson.module + jackson-modules-java8 + ${jackson.modules} + pom + import + + + + + + ${project.name} + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + ${project.build.finalName} + + + + + repackage + + + + + + com.spotify + docker-maven-plugin + 0.4.12 + + ${registry.url}/${project.name}:0.0.1 + ${docker.url} + ${project.basedir} + + + / + ${project.build.directory} + ${project.build.finalName}.jar + + + docker-hub + https://index.docker.io/v1/ + + + + + + + maven-compiler-plugin + 3.8.0 + + ${maven.compiler.target} + ${maven.compiler.source} + ${project.build.sourceEncoding} + + + + pl.project13.maven + git-commit-id-plugin + 2.2.5 + + + + + + + + aliyun + aliyun + http://maven.aliyun.com/nexus/content/groups/public/ + + + + spring-milestones + Spring Milestones + https://repo.spring.io/libs-milestone + + +