xiongzhu 4 жил өмнө
commit
f2f9178b7e
100 өөрчлөгдсөн 5844 нэмэгдсэн , 0 устгасан
  1. 33 0
      .gitignore
  2. 114 0
      .mvn/wrapper/MavenWrapperDownloader.java
  3. BIN
      .mvn/wrapper/maven-wrapper.jar
  4. 1 0
      .mvn/wrapper/maven-wrapper.properties
  5. 431 0
      awesome_admin_v2.sql
  6. 7 0
      build.sh
  7. 16 0
      install-jar.sh
  8. BIN
      lib/mozjpeg4j-1.1.jar
  9. BIN
      lib/pngquant4j-1.0.jar
  10. BIN
      libs/org/libjpegturbo/mozjpeg4j/1.1/mozjpeg4j-1.1.jar
  11. 9 0
      libs/org/libjpegturbo/mozjpeg4j/1.1/mozjpeg4j-1.1.pom
  12. 12 0
      libs/org/libjpegturbo/mozjpeg4j/maven-metadata-local.xml
  13. BIN
      libs/org/pngquant/pngquant4j/1.0/pngquant4j-1.0.jar
  14. 9 0
      libs/org/pngquant/pngquant4j/1.0/pngquant4j-1.0.pom
  15. 12 0
      libs/org/pngquant/pngquant4j/maven-metadata-local.xml
  16. 286 0
      mvnw
  17. 161 0
      mvnw.cmd
  18. 291 0
      pom.xml
  19. 21 0
      src/main/java/com/izouma/nineth/Application.java
  20. 14 0
      src/main/java/com/izouma/nineth/annotations/OperLog.java
  21. 12 0
      src/main/java/com/izouma/nineth/annotations/Searchable.java
  22. 188 0
      src/main/java/com/izouma/nineth/aspect/OperLogAspect.java
  23. 17 0
      src/main/java/com/izouma/nineth/config/CacheConfig.java
  24. 17 0
      src/main/java/com/izouma/nineth/config/Constants.java
  25. 148 0
      src/main/java/com/izouma/nineth/config/DateConfig.java
  26. 36 0
      src/main/java/com/izouma/nineth/config/LocalDateTimeSerializerConfig.java
  27. 24 0
      src/main/java/com/izouma/nineth/config/SpringSecurityAuditorAware.java
  28. 76 0
      src/main/java/com/izouma/nineth/config/WebMvcConfig.java
  29. 30 0
      src/main/java/com/izouma/nineth/config/WxMaConfiguration.java
  30. 14 0
      src/main/java/com/izouma/nineth/config/WxMaProperties.java
  31. 74 0
      src/main/java/com/izouma/nineth/config/WxMpConfiguration.java
  32. 13 0
      src/main/java/com/izouma/nineth/config/WxMpProperties.java
  33. 47 0
      src/main/java/com/izouma/nineth/config/WxPayConfiguration.java
  34. 97 0
      src/main/java/com/izouma/nineth/config/WxPayProperties.java
  35. 24 0
      src/main/java/com/izouma/nineth/converter/FileObjectConverter.java
  36. 25 0
      src/main/java/com/izouma/nineth/converter/FileObjectListConverter.java
  37. 28 0
      src/main/java/com/izouma/nineth/converter/JSONObjectConverter.java
  38. 26 0
      src/main/java/com/izouma/nineth/converter/LongArrayConverter.java
  39. 25 0
      src/main/java/com/izouma/nineth/converter/StringArrayConverter.java
  40. 24 0
      src/main/java/com/izouma/nineth/converter/StringToMapConverter.java
  41. 83 0
      src/main/java/com/izouma/nineth/domain/AuditedEntity.java
  42. 93 0
      src/main/java/com/izouma/nineth/domain/BaseEntity.java
  43. 49 0
      src/main/java/com/izouma/nineth/domain/District.java
  44. 71 0
      src/main/java/com/izouma/nineth/domain/ExceptionLog.java
  45. 10 0
      src/main/java/com/izouma/nineth/domain/FileObject.java
  46. 71 0
      src/main/java/com/izouma/nineth/domain/Menu.java
  47. 63 0
      src/main/java/com/izouma/nineth/domain/OperationLog.java
  48. 32 0
      src/main/java/com/izouma/nineth/domain/SmsRecord.java
  49. 57 0
      src/main/java/com/izouma/nineth/domain/SuperUser.java
  50. 40 0
      src/main/java/com/izouma/nineth/domain/SysConfig.java
  51. 17 0
      src/main/java/com/izouma/nineth/domain/TestClass.java
  52. 71 0
      src/main/java/com/izouma/nineth/domain/User.java
  53. 11 0
      src/main/java/com/izouma/nineth/dto/Captcha.java
  54. 23 0
      src/main/java/com/izouma/nineth/dto/MenuDTO.java
  55. 15 0
      src/main/java/com/izouma/nineth/dto/PageQuery.java
  56. 37 0
      src/main/java/com/izouma/nineth/dto/UserRegister.java
  57. 354 0
      src/main/java/com/izouma/nineth/dto/gen/GenCode.java
  58. 55 0
      src/main/java/com/izouma/nineth/dto/gen/Subtable.java
  59. 163 0
      src/main/java/com/izouma/nineth/dto/gen/TableField.java
  60. 16 0
      src/main/java/com/izouma/nineth/enums/AuthorityName.java
  61. 18 0
      src/main/java/com/izouma/nineth/enums/DistrictLevel.java
  62. 7 0
      src/main/java/com/izouma/nineth/exception/AuthenticationException.java
  63. 45 0
      src/main/java/com/izouma/nineth/exception/BusinessException.java
  64. 149 0
      src/main/java/com/izouma/nineth/exception/GlobalExceptionHandler.java
  65. 23 0
      src/main/java/com/izouma/nineth/mpHandler/LogHandler.java
  66. 7 0
      src/main/java/com/izouma/nineth/repo/AuthorityRepo.java
  67. 8 0
      src/main/java/com/izouma/nineth/repo/DistrictRepo.java
  68. 8 0
      src/main/java/com/izouma/nineth/repo/ExceptionLogRepo.java
  69. 35 0
      src/main/java/com/izouma/nineth/repo/MenuRepo.java
  70. 8 0
      src/main/java/com/izouma/nineth/repo/OperationLogRepo.java
  71. 24 0
      src/main/java/com/izouma/nineth/repo/SmsRecordRepo.java
  72. 11 0
      src/main/java/com/izouma/nineth/repo/SysConfigRepo.java
  73. 16 0
      src/main/java/com/izouma/nineth/repo/TestClassRepo.java
  74. 26 0
      src/main/java/com/izouma/nineth/repo/UserRepo.java
  75. 64 0
      src/main/java/com/izouma/nineth/security/Authority.java
  76. 25 0
      src/main/java/com/izouma/nineth/security/JwtAuthenticationEntryPoint.java
  77. 87 0
      src/main/java/com/izouma/nineth/security/JwtAuthorizationTokenFilter.java
  78. 12 0
      src/main/java/com/izouma/nineth/security/JwtConfig.java
  79. 125 0
      src/main/java/com/izouma/nineth/security/JwtTokenUtil.java
  80. 81 0
      src/main/java/com/izouma/nineth/security/JwtUser.java
  81. 26 0
      src/main/java/com/izouma/nineth/security/JwtUserDetailsService.java
  82. 28 0
      src/main/java/com/izouma/nineth/security/JwtUserFactory.java
  83. 110 0
      src/main/java/com/izouma/nineth/security/WebSecurityConfig.java
  84. 47 0
      src/main/java/com/izouma/nineth/service/CaptchaService.java
  85. 121 0
      src/main/java/com/izouma/nineth/service/DistrictService.java
  86. 13 0
      src/main/java/com/izouma/nineth/service/ExceptionLogService.java
  87. 173 0
      src/main/java/com/izouma/nineth/service/GenCodeService.java
  88. 13 0
      src/main/java/com/izouma/nineth/service/OperationLogService.java
  89. 53 0
      src/main/java/com/izouma/nineth/service/SysConfigService.java
  90. 20 0
      src/main/java/com/izouma/nineth/service/TestClassService.java
  91. 184 0
      src/main/java/com/izouma/nineth/service/UserService.java
  92. 94 0
      src/main/java/com/izouma/nineth/service/sms/AliSmsService.java
  93. 20 0
      src/main/java/com/izouma/nineth/service/sms/SmsService.java
  94. 70 0
      src/main/java/com/izouma/nineth/service/storage/AliStorageService.java
  95. 63 0
      src/main/java/com/izouma/nineth/service/storage/LocalStorageService.java
  96. 9 0
      src/main/java/com/izouma/nineth/service/storage/StorageService.java
  97. 45 0
      src/main/java/com/izouma/nineth/utils/DateTimeUtils.java
  98. 204 0
      src/main/java/com/izouma/nineth/utils/FileUtils.java
  99. 71 0
      src/main/java/com/izouma/nineth/utils/IPUtils.java
  100. 8 0
      src/main/java/com/izouma/nineth/utils/ImageUtils.java

+ 33 - 0
.gitignore

@@ -0,0 +1,33 @@
+HELP.md
+target/
+!.mvn/wrapper/maven-wrapper.jar
+!**/src/main/**
+!**/src/test/**
+
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+
+### IntelliJ IDEA ###
+.idea
+*.iws
+*.iml
+*.ipr
+
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+build/
+
+### VS Code ###
+.vscode/
+
+.DS_Store

+ 114 - 0
.mvn/wrapper/MavenWrapperDownloader.java

@@ -0,0 +1,114 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
+
+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.
+*/
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.net.URL;
+import java.nio.channels.Channels;
+import java.nio.channels.ReadableByteChannel;
+import java.util.Properties;
+
+public class MavenWrapperDownloader {
+
+    /**
+     * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
+     */
+    private static final String DEFAULT_DOWNLOAD_URL =
+            "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
+
+    /**
+     * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
+     * use instead of the default one.
+     */
+    private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
+            ".mvn/wrapper/maven-wrapper.properties";
+
+    /**
+     * Path where the maven-wrapper.jar will be saved to.
+     */
+    private static final String MAVEN_WRAPPER_JAR_PATH =
+            ".mvn/wrapper/maven-wrapper.jar";
+
+    /**
+     * Name of the property which should be used to override the default download url for the wrapper.
+     */
+    private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
+
+    public static void main(String args[]) {
+        System.out.println("- Downloader started");
+        File baseDirectory = new File(args[0]);
+        System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
+
+        // If the maven-wrapper.properties exists, read it and check if it contains a custom
+        // wrapperUrl parameter.
+        File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
+        String url = DEFAULT_DOWNLOAD_URL;
+        if (mavenWrapperPropertyFile.exists()) {
+            FileInputStream mavenWrapperPropertyFileInputStream = null;
+            try {
+                mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
+                Properties mavenWrapperProperties = new Properties();
+                mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
+                url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
+            } catch (IOException e) {
+                System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
+            } finally {
+                try {
+                    if (mavenWrapperPropertyFileInputStream != null) {
+                        mavenWrapperPropertyFileInputStream.close();
+                    }
+                } catch (IOException e) {
+                    // Ignore ...
+                }
+            }
+        }
+        System.out.println("- Downloading from: : " + url);
+
+        File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
+        if (!outputFile.getParentFile().exists()) {
+            if (!outputFile.getParentFile().mkdirs()) {
+                System.out.println(
+                        "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
+            }
+        }
+        System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
+        try {
+            downloadFileFromURL(url, outputFile);
+            System.out.println("Done");
+            System.exit(0);
+        } catch (Throwable e) {
+            System.out.println("- Error downloading");
+            e.printStackTrace();
+            System.exit(1);
+        }
+    }
+
+    private static void downloadFileFromURL(String urlString, File destination) throws Exception {
+        URL website = new URL(urlString);
+        ReadableByteChannel rbc;
+        rbc = Channels.newChannel(website.openStream());
+        FileOutputStream fos = new FileOutputStream(destination);
+        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
+        fos.close();
+        rbc.close();
+    }
+
+}

BIN
.mvn/wrapper/maven-wrapper.jar


+ 1 - 0
.mvn/wrapper/maven-wrapper.properties

@@ -0,0 +1 @@
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip

+ 431 - 0
awesome_admin_v2.sql

@@ -0,0 +1,431 @@
+/*
+ Navicat Premium Data Transfer
+
+ Source Server         : 微球
+ Source Server Type    : MySQL
+ Source Server Version : 50616
+ Source Host           : rdsave1o67m1ido6gwp6public.mysql.rds.aliyuncs.com:3306
+ Source Schema         : awesome_admin_v2
+
+ Target Server Type    : MySQL
+ Target Server Version : 50616
+ File Encoding         : 65001
+
+ Date: 07/08/2020 17:51:04
+*/
+
+SET NAMES utf8mb4;
+SET FOREIGN_KEY_CHECKS = 0;
+
+-- ----------------------------
+-- Table structure for authority
+-- ----------------------------
+DROP TABLE IF EXISTS `authority`;
+CREATE TABLE `authority` (
+  `name` varchar(50) NOT NULL,
+  `description` varchar(50) NOT NULL,
+  PRIMARY KEY (`name`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Records of authority
+-- ----------------------------
+BEGIN;
+INSERT INTO `authority` VALUES ('ROLE_ADMIN', '管理员');
+INSERT INTO `authority` VALUES ('ROLE_DEV', '开发者');
+INSERT INTO `authority` VALUES ('ROLE_USER', '普通用户');
+COMMIT;
+
+-- ----------------------------
+-- Table structure for child
+-- ----------------------------
+DROP TABLE IF EXISTS `child`;
+CREATE TABLE `child` (
+  `id` bigint(20) NOT NULL,
+  `created_at` datetime DEFAULT NULL,
+  `created_by` varchar(255) DEFAULT NULL,
+  `modified_at` datetime DEFAULT NULL,
+  `modified_by` varchar(255) DEFAULT NULL,
+  `child_name` varchar(255) DEFAULT NULL,
+  `parent_id` bigint(20) DEFAULT NULL,
+  PRIMARY KEY (`id`),
+  KEY `FK7dag1cncltpyhoc2mbwka356h` (`parent_id`),
+  CONSTRAINT `FK7dag1cncltpyhoc2mbwka356h` FOREIGN KEY (`parent_id`) REFERENCES `parent` (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Records of child
+-- ----------------------------
+BEGIN;
+INSERT INTO `child` VALUES (3, '2019-12-25 11:17:02', 'system', '2019-12-25 11:17:02', 'system', '222', 2);
+INSERT INTO `child` VALUES (5, '2019-12-25 11:18:19', 'system', '2019-12-25 11:18:19', 'system', '222', 4);
+INSERT INTO `child` VALUES (7, '2019-12-25 14:50:50', 'system', '2019-12-25 14:50:50', 'system', '222', 6);
+COMMIT;
+
+-- ----------------------------
+-- Table structure for city
+-- ----------------------------
+DROP TABLE IF EXISTS `city`;
+CREATE TABLE `city` (
+  `id` bigint(20) NOT NULL,
+  `created_at` datetime DEFAULT NULL,
+  `created_by` varchar(255) DEFAULT NULL,
+  `modified_at` datetime DEFAULT NULL,
+  `modified_by` varchar(255) DEFAULT NULL,
+  `name` varchar(255) DEFAULT NULL,
+  `remark` varchar(255) DEFAULT NULL,
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Table structure for district
+-- ----------------------------
+DROP TABLE IF EXISTS `district`;
+CREATE TABLE `district` (
+  `id` bigint(20) NOT NULL,
+  `created_at` datetime DEFAULT NULL,
+  `created_by` varchar(255) DEFAULT NULL,
+  `modified_at` datetime DEFAULT NULL,
+  `modified_by` varchar(255) DEFAULT NULL,
+  `full_name` varchar(255) DEFAULT NULL,
+  `lat` double NOT NULL,
+  `leaf` bit(1) NOT NULL,
+  `level` int(11) NOT NULL,
+  `lng` double NOT NULL,
+  `name` varchar(255) DEFAULT NULL,
+  `parent` bigint(20) DEFAULT NULL,
+  `pinyin` varchar(255) DEFAULT NULL,
+  `child_count` int(11) NOT NULL,
+  `city_code` varchar(10) DEFAULT NULL,
+  `city_count` int(11) NOT NULL,
+  `district_count` int(11) NOT NULL,
+  `street_count` int(11) NOT NULL,
+  `del` bit(1) NOT NULL,
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Table structure for guid_package
+-- ----------------------------
+DROP TABLE IF EXISTS `guid_package`;
+CREATE TABLE `guid_package` (
+  `id` bigint(20) NOT NULL,
+  `created_at` datetime DEFAULT NULL,
+  `created_by` varchar(255) DEFAULT NULL,
+  `modified_at` datetime DEFAULT NULL,
+  `modified_by` varchar(255) DEFAULT NULL,
+  `name` varchar(255) DEFAULT NULL,
+  `price` decimal(10,2) DEFAULT NULL,
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Table structure for guide
+-- ----------------------------
+DROP TABLE IF EXISTS `guide`;
+CREATE TABLE `guide` (
+  `id` bigint(20) NOT NULL,
+  `created_at` datetime DEFAULT NULL,
+  `created_by` varchar(255) DEFAULT NULL,
+  `modified_at` datetime DEFAULT NULL,
+  `modified_by` varchar(255) DEFAULT NULL,
+  `pic` varchar(255) DEFAULT NULL,
+  `sort` int(11) NOT NULL,
+  `text` text,
+  `type` varchar(255) DEFAULT NULL,
+  `video` varchar(255) DEFAULT NULL,
+  `voice` varchar(255) DEFAULT NULL,
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Table structure for hibernate_sequence
+-- ----------------------------
+DROP TABLE IF EXISTS `hibernate_sequence`;
+CREATE TABLE `hibernate_sequence` (
+  `next_val` bigint(20) DEFAULT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Records of hibernate_sequence
+-- ----------------------------
+BEGIN;
+INSERT INTO `hibernate_sequence` VALUES (15);
+INSERT INTO `hibernate_sequence` VALUES (15);
+INSERT INTO `hibernate_sequence` VALUES (15);
+COMMIT;
+
+-- ----------------------------
+-- Table structure for menu
+-- ----------------------------
+DROP TABLE IF EXISTS `menu`;
+CREATE TABLE `menu` (
+  `id` bigint(20) NOT NULL,
+  `created_at` datetime DEFAULT NULL,
+  `created_by` varchar(255) DEFAULT NULL,
+  `modified_at` datetime DEFAULT NULL,
+  `modified_by` varchar(255) DEFAULT NULL,
+  `active` bit(1) DEFAULT NULL,
+  `enabled` bit(1) DEFAULT NULL,
+  `icon` varchar(255) DEFAULT NULL,
+  `name` varchar(255) DEFAULT NULL,
+  `parent` bigint(20) DEFAULT NULL,
+  `path` varchar(255) DEFAULT NULL,
+  `root` bit(1) DEFAULT NULL,
+  `sort` int(11) DEFAULT NULL,
+  `category` varchar(255) DEFAULT NULL,
+  `del` bit(1) NOT NULL,
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Records of menu
+-- ----------------------------
+BEGIN;
+INSERT INTO `menu` VALUES (3, NULL, NULL, '2020-07-31 14:31:40', '管理员(1)', b'1', b'1', 'fas fa-desktop', '开发', 2, '', b'1', 4, '开发', b'0');
+INSERT INTO `menu` VALUES (4, NULL, NULL, '2020-07-31 14:31:51', '管理员(1)', b'1', b'1', 'fas fa-code', '代码生成', 3, '/genCodeList', b'0', 5, '开发', b'0');
+INSERT INTO `menu` VALUES (5, NULL, NULL, '2020-07-31 14:31:56', '管理员(1)', b'1', b'1', 'fas fa-bug', '接口调试', 3, '/api', b'0', 6, '开发', b'0');
+INSERT INTO `menu` VALUES (6, NULL, NULL, '2020-07-09 15:01:05', '管理员(1)', b'1', b'1', 'fas fa-user', '用户管理', 2, '/userList', b'1', 2, '用户', b'0');
+INSERT INTO `menu` VALUES (8, '2020-07-09 15:01:40', NULL, '2020-07-09 15:01:45', '管理员(1)', b'1', b'1', '', '菜单权限', 9, '/menuAuthority', b'0', 8, NULL, b'0');
+INSERT INTO `menu` VALUES (9, NULL, NULL, '2020-07-09 15:01:10', '管理员(1)', b'1', b'1', 'fas fa-cog', '配置', 2, '', b'1', 3, '系统', b'0');
+INSERT INTO `menu` VALUES (10, NULL, NULL, '2020-07-29 16:54:21', '管理员(1)', b'1', b'1', '', '菜单配置', 9, '/menus', b'0', 7, '系统', b'0');
+INSERT INTO `menu` VALUES (14, NULL, NULL, '2020-07-09 15:01:45', '管理员(1)', b'1', b'1', '', '参数配置', 9, '/sysConfigList', b'0', 9, '系统', b'0');
+COMMIT;
+
+-- ----------------------------
+-- Table structure for menu_authority
+-- ----------------------------
+DROP TABLE IF EXISTS `menu_authority`;
+CREATE TABLE `menu_authority` (
+  `menu_id` bigint(20) NOT NULL,
+  `authority` varchar(50) NOT NULL,
+  PRIMARY KEY (`menu_id`,`authority`),
+  KEY `FKlj7sftrck7uk1kcjsy0doo56` (`authority`),
+  CONSTRAINT `FK4hopjqfvkhdagmk110y1jk17q` FOREIGN KEY (`menu_id`) REFERENCES `menu` (`id`),
+  CONSTRAINT `FKlj7sftrck7uk1kcjsy0doo56` FOREIGN KEY (`authority`) REFERENCES `authority` (`name`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Records of menu_authority
+-- ----------------------------
+BEGIN;
+INSERT INTO `menu_authority` VALUES (6, 'ROLE_ADMIN');
+INSERT INTO `menu_authority` VALUES (8, 'ROLE_ADMIN');
+INSERT INTO `menu_authority` VALUES (9, 'ROLE_ADMIN');
+INSERT INTO `menu_authority` VALUES (10, 'ROLE_ADMIN');
+INSERT INTO `menu_authority` VALUES (14, 'ROLE_ADMIN');
+INSERT INTO `menu_authority` VALUES (3, 'ROLE_DEV');
+INSERT INTO `menu_authority` VALUES (4, 'ROLE_DEV');
+INSERT INTO `menu_authority` VALUES (5, 'ROLE_DEV');
+COMMIT;
+
+-- ----------------------------
+-- Table structure for parent
+-- ----------------------------
+DROP TABLE IF EXISTS `parent`;
+CREATE TABLE `parent` (
+  `id` bigint(20) NOT NULL,
+  `created_at` datetime DEFAULT NULL,
+  `created_by` varchar(255) DEFAULT NULL,
+  `modified_at` datetime DEFAULT NULL,
+  `modified_by` varchar(255) DEFAULT NULL,
+  `parent_name` varchar(255) DEFAULT NULL,
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Records of parent
+-- ----------------------------
+BEGIN;
+INSERT INTO `parent` VALUES (2, '2019-12-25 11:17:02', 'system', '2019-12-25 11:17:02', 'system', '111');
+INSERT INTO `parent` VALUES (4, '2019-12-25 11:18:19', 'system', '2019-12-25 11:18:19', 'system', '111');
+INSERT INTO `parent` VALUES (6, '2019-12-25 14:50:49', 'system', '2019-12-25 14:50:49', 'system', '111');
+COMMIT;
+
+-- ----------------------------
+-- Table structure for scenic
+-- ----------------------------
+DROP TABLE IF EXISTS `scenic`;
+CREATE TABLE `scenic` (
+  `id` bigint(20) NOT NULL,
+  `created_at` datetime DEFAULT NULL,
+  `created_by` varchar(255) DEFAULT NULL,
+  `modified_at` datetime DEFAULT NULL,
+  `modified_by` varchar(255) DEFAULT NULL,
+  `city_id` bigint(20) DEFAULT NULL,
+  `name` varchar(255) DEFAULT NULL,
+  `pic` varchar(255) DEFAULT NULL,
+  `remark` varchar(255) DEFAULT NULL,
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Table structure for scenic_spot
+-- ----------------------------
+DROP TABLE IF EXISTS `scenic_spot`;
+CREATE TABLE `scenic_spot` (
+  `id` bigint(20) NOT NULL,
+  `created_at` datetime DEFAULT NULL,
+  `created_by` varchar(255) DEFAULT NULL,
+  `modified_at` datetime DEFAULT NULL,
+  `modified_by` varchar(255) DEFAULT NULL,
+  `city_id` bigint(20) DEFAULT NULL,
+  `name` varchar(255) DEFAULT NULL,
+  `pic` varchar(255) DEFAULT NULL,
+  `remark` varchar(255) DEFAULT NULL,
+  `scenic_id` bigint(20) DEFAULT NULL,
+  `x` int(11) NOT NULL,
+  `y` int(11) NOT NULL,
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Table structure for sms_record
+-- ----------------------------
+DROP TABLE IF EXISTS `sms_record`;
+CREATE TABLE `sms_record` (
+  `id` bigint(20) NOT NULL,
+  `created_at` datetime DEFAULT NULL,
+  `created_by` varchar(255) DEFAULT NULL,
+  `modified_at` datetime DEFAULT NULL,
+  `modified_by` varchar(255) DEFAULT NULL,
+  `code` varchar(255) DEFAULT NULL,
+  `expired` bit(1) DEFAULT NULL,
+  `expires_at` datetime DEFAULT NULL,
+  `phone` varchar(255) DEFAULT NULL,
+  `scope` varchar(255) DEFAULT NULL,
+  `session_id` varchar(255) DEFAULT NULL,
+  `del` bit(1) NOT NULL,
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Table structure for spot
+-- ----------------------------
+DROP TABLE IF EXISTS `spot`;
+CREATE TABLE `spot` (
+  `user_id` bigint(20) NOT NULL,
+  `authority_name` varchar(50) NOT NULL,
+  PRIMARY KEY (`user_id`,`authority_name`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Table structure for spot_guid
+-- ----------------------------
+DROP TABLE IF EXISTS `spot_guid`;
+CREATE TABLE `spot_guid` (
+  `spot_id` bigint(20) NOT NULL,
+  `guid_id` bigint(20) NOT NULL,
+  PRIMARY KEY (`spot_id`,`guid_id`),
+  KEY `FKbftxye4brw7vfq05d7rv0mtca` (`guid_id`),
+  CONSTRAINT `FK5xnrr1sk76u0xy3j15p6r96q9` FOREIGN KEY (`spot_id`) REFERENCES `scenic_spot` (`id`),
+  CONSTRAINT `FKbftxye4brw7vfq05d7rv0mtca` FOREIGN KEY (`guid_id`) REFERENCES `guide` (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Table structure for super_user
+-- ----------------------------
+DROP TABLE IF EXISTS `super_user`;
+CREATE TABLE `super_user` (
+  `id` bigint(20) NOT NULL,
+  `created_at` datetime DEFAULT NULL,
+  `created_by` varchar(255) DEFAULT NULL,
+  `modified_at` datetime DEFAULT NULL,
+  `modified_by` varchar(255) DEFAULT NULL,
+  `avatar` varchar(255) DEFAULT NULL,
+  `enabled` bit(1) NOT NULL,
+  `nickname` varchar(255) DEFAULT NULL,
+  `password` varchar(255) DEFAULT NULL,
+  `phone` varchar(255) DEFAULT NULL,
+  `username` varchar(50) NOT NULL,
+  `del` bit(1) NOT NULL,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `UK_jfokkpxg19r117eil158ooo9d` (`username`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Table structure for super_user_authority
+-- ----------------------------
+DROP TABLE IF EXISTS `super_user_authority`;
+CREATE TABLE `super_user_authority` (
+  `user_id` bigint(20) NOT NULL,
+  `authority_name` varchar(50) NOT NULL,
+  PRIMARY KEY (`user_id`,`authority_name`),
+  KEY `FKxjxyodse6n0n00ewvoq8xv8` (`authority_name`),
+  CONSTRAINT `FK7p0vq0b1vy9f0sqvgrdqw1q70` FOREIGN KEY (`user_id`) REFERENCES `super_user` (`id`),
+  CONSTRAINT `FKxjxyodse6n0n00ewvoq8xv8` FOREIGN KEY (`authority_name`) REFERENCES `authority` (`name`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Table structure for sys_config
+-- ----------------------------
+DROP TABLE IF EXISTS `sys_config`;
+CREATE TABLE `sys_config` (
+  `name` varchar(25) NOT NULL,
+  `created_at` datetime DEFAULT NULL,
+  `created_by` varchar(255) DEFAULT NULL,
+  `modified_at` datetime DEFAULT NULL,
+  `modified_by` varchar(255) DEFAULT NULL,
+  `description` varchar(255) DEFAULT NULL,
+  `type` varchar(255) DEFAULT NULL,
+  `value` varchar(255) DEFAULT NULL,
+  `del` bit(1) NOT NULL,
+  PRIMARY KEY (`name`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Table structure for user
+-- ----------------------------
+DROP TABLE IF EXISTS `user`;
+CREATE TABLE `user` (
+  `id` bigint(20) NOT NULL,
+  `created_at` datetime DEFAULT NULL,
+  `created_by` varchar(255) DEFAULT NULL,
+  `modified_at` datetime DEFAULT NULL,
+  `modified_by` varchar(255) DEFAULT NULL,
+  `avatar` varchar(255) DEFAULT NULL,
+  `city` varchar(255) DEFAULT NULL,
+  `country` varchar(255) DEFAULT NULL,
+  `email` varchar(255) DEFAULT NULL,
+  `language` varchar(255) DEFAULT NULL,
+  `nickname` varchar(255) DEFAULT NULL,
+  `open_id` varchar(255) DEFAULT NULL,
+  `password` varchar(255) DEFAULT NULL,
+  `phone` varchar(255) DEFAULT NULL,
+  `province` varchar(255) DEFAULT NULL,
+  `sex` varchar(255) DEFAULT NULL,
+  `username` varchar(50) NOT NULL,
+  `del` bit(1) NOT NULL,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `UK_sb8bbouer5wak8vyiiy4pf2bx` (`username`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Records of user
+-- ----------------------------
+BEGIN;
+INSERT INTO `user` VALUES (1, '2020-03-07 18:34:36', NULL, '2020-07-31 14:32:10', '管理员(1)', 'https://zhumj.oss-cn-hangzhou.aliyuncs.com/image/user.jpg', NULL, NULL, NULL, NULL, '管理员', NULL, '$2a$10$ztJSpmth7fPgDK0I5stwnO59e5ht2copnDL8lyt2xif6lXBzk/ZdO', NULL, NULL, NULL, 'root', b'0');
+COMMIT;
+
+-- ----------------------------
+-- Table structure for user_authority
+-- ----------------------------
+DROP TABLE IF EXISTS `user_authority`;
+CREATE TABLE `user_authority` (
+  `user_id` bigint(20) NOT NULL,
+  `authority_name` varchar(50) NOT NULL,
+  PRIMARY KEY (`user_id`,`authority_name`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+-- ----------------------------
+-- Records of user_authority
+-- ----------------------------
+BEGIN;
+INSERT INTO `user_authority` VALUES (1, 'ROLE_ADMIN');
+INSERT INTO `user_authority` VALUES (1, 'ROLE_DEV');
+INSERT INTO `user_authority` VALUES (1, 'ROLE_USER');
+INSERT INTO `user_authority` VALUES (11, 'ROLE_USER');
+INSERT INTO `user_authority` VALUES (14, 'ROLE_ADMIN');
+COMMIT;
+
+SET FOREIGN_KEY_CHECKS = 1;

+ 7 - 0
build.sh

@@ -0,0 +1,7 @@
+git checkout
+git pull
+#(cd src/main/vue && npm run build)
+mvn clean package
+systemctl stop zmj
+cp target/zhumj-0.0.1-SNAPSHOT.jar /var/www/zmj/zhumj-0.0.1-SNAPSHOT.jar
+systemctl start zmj

+ 16 - 0
install-jar.sh

@@ -0,0 +1,16 @@
+
+mvn org.apache.maven.plugins:maven-install-plugin:2.5.1:install-file \
+-DgroupId=org.libjpegturbo \
+-DartifactId=mozjpeg4j \
+-Dpackaging=jar \
+-Dversion=1.1 \
+-Dfile=lib/mozjpeg4j-1.1.jar \
+-DlocalRepositoryPath=libs
+
+mvn org.apache.maven.plugins:maven-install-plugin:2.5.1:install-file \
+-DgroupId=org.pngquant \
+-DartifactId=pngquant4j \
+-Dpackaging=jar \
+-Dversion=1.0 \
+-Dfile=lib/pngquant4j-1.0.jar \
+-DlocalRepositoryPath=libs

BIN
lib/mozjpeg4j-1.1.jar


BIN
lib/pngquant4j-1.0.jar


BIN
libs/org/libjpegturbo/mozjpeg4j/1.1/mozjpeg4j-1.1.jar


+ 9 - 0
libs/org/libjpegturbo/mozjpeg4j/1.1/mozjpeg4j-1.1.pom

@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.libjpegturbo</groupId>
+  <artifactId>mozjpeg4j</artifactId>
+  <version>1.1</version>
+  <description>POM was created from install:install-file</description>
+</project>

+ 12 - 0
libs/org/libjpegturbo/mozjpeg4j/maven-metadata-local.xml

@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<metadata>
+  <groupId>org.libjpegturbo</groupId>
+  <artifactId>mozjpeg4j</artifactId>
+  <versioning>
+    <release>1.1</release>
+    <versions>
+      <version>1.1</version>
+    </versions>
+    <lastUpdated>20210319095742</lastUpdated>
+  </versioning>
+</metadata>

BIN
libs/org/pngquant/pngquant4j/1.0/pngquant4j-1.0.jar


+ 9 - 0
libs/org/pngquant/pngquant4j/1.0/pngquant4j-1.0.pom

@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.pngquant</groupId>
+  <artifactId>pngquant4j</artifactId>
+  <version>1.0</version>
+  <description>POM was created from install:install-file</description>
+</project>

+ 12 - 0
libs/org/pngquant/pngquant4j/maven-metadata-local.xml

@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<metadata>
+  <groupId>org.pngquant</groupId>
+  <artifactId>pngquant4j</artifactId>
+  <versioning>
+    <release>1.0</release>
+    <versions>
+      <version>1.0</version>
+    </versions>
+    <lastUpdated>20210319095744</lastUpdated>
+  </versioning>
+</metadata>

+ 286 - 0
mvnw

@@ -0,0 +1,286 @@
+#!/bin/sh
+# ----------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
+#
+# 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.
+# ----------------------------------------------------------------------------
+
+# ----------------------------------------------------------------------------
+# Maven2 Start Up Batch script
+#
+# Required ENV vars:
+# ------------------
+#   JAVA_HOME - location of a JDK home dir
+#
+# Optional ENV vars
+# -----------------
+#   M2_HOME - location of maven2's installed home dir
+#   MAVEN_OPTS - parameters passed to the Java VM when running Maven
+#     e.g. to debug Maven itself, use
+#       set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+#   MAVEN_SKIP_RC - flag to disable loading of mavenrc files
+# ----------------------------------------------------------------------------
+
+if [ -z "$MAVEN_SKIP_RC" ] ; then
+
+  if [ -f /etc/mavenrc ] ; then
+    . /etc/mavenrc
+  fi
+
+  if [ -f "$HOME/.mavenrc" ] ; then
+    . "$HOME/.mavenrc"
+  fi
+
+fi
+
+# OS specific support.  $var _must_ be set to either true or false.
+cygwin=false;
+darwin=false;
+mingw=false
+case "`uname`" in
+  CYGWIN*) cygwin=true ;;
+  MINGW*) mingw=true;;
+  Darwin*) darwin=true
+    # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
+    # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
+    if [ -z "$JAVA_HOME" ]; then
+      if [ -x "/usr/libexec/java_home" ]; then
+        export JAVA_HOME="`/usr/libexec/java_home`"
+      else
+        export JAVA_HOME="/Library/Java/Home"
+      fi
+    fi
+    ;;
+esac
+
+if [ -z "$JAVA_HOME" ] ; then
+  if [ -r /etc/gentoo-release ] ; then
+    JAVA_HOME=`java-config --jre-home`
+  fi
+fi
+
+if [ -z "$M2_HOME" ] ; then
+  ## resolve links - $0 may be a link to maven's home
+  PRG="$0"
+
+  # need this for relative symlinks
+  while [ -h "$PRG" ] ; do
+    ls=`ls -ld "$PRG"`
+    link=`expr "$ls" : '.*-> \(.*\)$'`
+    if expr "$link" : '/.*' > /dev/null; then
+      PRG="$link"
+    else
+      PRG="`dirname "$PRG"`/$link"
+    fi
+  done
+
+  saveddir=`pwd`
+
+  M2_HOME=`dirname "$PRG"`/..
+
+  # make it fully qualified
+  M2_HOME=`cd "$M2_HOME" && pwd`
+
+  cd "$saveddir"
+  # echo Using m2 at $M2_HOME
+fi
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched
+if $cygwin ; then
+  [ -n "$M2_HOME" ] &&
+    M2_HOME=`cygpath --unix "$M2_HOME"`
+  [ -n "$JAVA_HOME" ] &&
+    JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+  [ -n "$CLASSPATH" ] &&
+    CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
+fi
+
+# For Mingw, ensure paths are in UNIX format before anything is touched
+if $mingw ; then
+  [ -n "$M2_HOME" ] &&
+    M2_HOME="`(cd "$M2_HOME"; pwd)`"
+  [ -n "$JAVA_HOME" ] &&
+    JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
+  # TODO classpath?
+fi
+
+if [ -z "$JAVA_HOME" ]; then
+  javaExecutable="`which javac`"
+  if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
+    # readlink(1) is not available as standard on Solaris 10.
+    readLink=`which readlink`
+    if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
+      if $darwin ; then
+        javaHome="`dirname \"$javaExecutable\"`"
+        javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
+      else
+        javaExecutable="`readlink -f \"$javaExecutable\"`"
+      fi
+      javaHome="`dirname \"$javaExecutable\"`"
+      javaHome=`expr "$javaHome" : '\(.*\)/bin'`
+      JAVA_HOME="$javaHome"
+      export JAVA_HOME
+    fi
+  fi
+fi
+
+if [ -z "$JAVACMD" ] ; then
+  if [ -n "$JAVA_HOME"  ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+      # IBM's JDK on AIX uses strange locations for the executables
+      JAVACMD="$JAVA_HOME/jre/sh/java"
+    else
+      JAVACMD="$JAVA_HOME/bin/java"
+    fi
+  else
+    JAVACMD="`which java`"
+  fi
+fi
+
+if [ ! -x "$JAVACMD" ] ; then
+  echo "Error: JAVA_HOME is not defined correctly." >&2
+  echo "  We cannot execute $JAVACMD" >&2
+  exit 1
+fi
+
+if [ -z "$JAVA_HOME" ] ; then
+  echo "Warning: JAVA_HOME environment variable is not set."
+fi
+
+CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
+
+# traverses directory structure from process work directory to filesystem root
+# first directory with .mvn subdirectory is considered project base directory
+find_maven_basedir() {
+
+  if [ -z "$1" ]
+  then
+    echo "Path not specified to find_maven_basedir"
+    return 1
+  fi
+
+  basedir="$1"
+  wdir="$1"
+  while [ "$wdir" != '/' ] ; do
+    if [ -d "$wdir"/.mvn ] ; then
+      basedir=$wdir
+      break
+    fi
+    # workaround for JBEAP-8937 (on Solaris 10/Sparc)
+    if [ -d "${wdir}" ]; then
+      wdir=`cd "$wdir/.."; pwd`
+    fi
+    # end of workaround
+  done
+  echo "${basedir}"
+}
+
+# concatenates all lines of a file
+concat_lines() {
+  if [ -f "$1" ]; then
+    echo "$(tr -s '\n' ' ' < "$1")"
+  fi
+}
+
+BASE_DIR=`find_maven_basedir "$(pwd)"`
+if [ -z "$BASE_DIR" ]; then
+  exit 1;
+fi
+
+##########################################################################################
+# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
+# This allows using the maven wrapper in projects that prohibit checking in binary data.
+##########################################################################################
+if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
+    if [ "$MVNW_VERBOSE" = true ]; then
+      echo "Found .mvn/wrapper/maven-wrapper.jar"
+    fi
+else
+    if [ "$MVNW_VERBOSE" = true ]; then
+      echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
+    fi
+    jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
+    while IFS="=" read key value; do
+      case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
+      esac
+    done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
+    if [ "$MVNW_VERBOSE" = true ]; then
+      echo "Downloading from: $jarUrl"
+    fi
+    wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
+
+    if command -v wget > /dev/null; then
+        if [ "$MVNW_VERBOSE" = true ]; then
+          echo "Found wget ... using wget"
+        fi
+        wget "$jarUrl" -O "$wrapperJarPath"
+    elif command -v curl > /dev/null; then
+        if [ "$MVNW_VERBOSE" = true ]; then
+          echo "Found curl ... using curl"
+        fi
+        curl -o "$wrapperJarPath" "$jarUrl"
+    else
+        if [ "$MVNW_VERBOSE" = true ]; then
+          echo "Falling back to using Java to download"
+        fi
+        javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
+        if [ -e "$javaClass" ]; then
+            if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
+                if [ "$MVNW_VERBOSE" = true ]; then
+                  echo " - Compiling MavenWrapperDownloader.java ..."
+                fi
+                # Compiling the Java class
+                ("$JAVA_HOME/bin/javac" "$javaClass")
+            fi
+            if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
+                # Running the downloader
+                if [ "$MVNW_VERBOSE" = true ]; then
+                  echo " - Running MavenWrapperDownloader.java ..."
+                fi
+                ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
+            fi
+        fi
+    fi
+fi
+##########################################################################################
+# End of extension
+##########################################################################################
+
+export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
+if [ "$MVNW_VERBOSE" = true ]; then
+  echo $MAVEN_PROJECTBASEDIR
+fi
+MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin; then
+  [ -n "$M2_HOME" ] &&
+    M2_HOME=`cygpath --path --windows "$M2_HOME"`
+  [ -n "$JAVA_HOME" ] &&
+    JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
+  [ -n "$CLASSPATH" ] &&
+    CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
+  [ -n "$MAVEN_PROJECTBASEDIR" ] &&
+    MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
+fi
+
+WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
+
+exec "$JAVACMD" \
+  $MAVEN_OPTS \
+  -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
+  "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
+  ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

+ 161 - 0
mvnw.cmd

@@ -0,0 +1,161 @@
+@REM ----------------------------------------------------------------------------
+@REM Licensed to the Apache Software Foundation (ASF) under one
+@REM or more contributor license agreements.  See the NOTICE file
+@REM distributed with this work for additional information
+@REM regarding copyright ownership.  The ASF licenses this file
+@REM to you under the Apache License, Version 2.0 (the
+@REM "License"); you may not use this file except in compliance
+@REM with the License.  You may obtain a copy of the License at
+@REM
+@REM    https://www.apache.org/licenses/LICENSE-2.0
+@REM
+@REM Unless required by applicable law or agreed to in writing,
+@REM software distributed under the License is distributed on an
+@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+@REM KIND, either express or implied.  See the License for the
+@REM specific language governing permissions and limitations
+@REM under the License.
+@REM ----------------------------------------------------------------------------
+
+@REM ----------------------------------------------------------------------------
+@REM Maven2 Start Up Batch script
+@REM
+@REM Required ENV vars:
+@REM JAVA_HOME - location of a JDK home dir
+@REM
+@REM Optional ENV vars
+@REM M2_HOME - location of maven2's installed home dir
+@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
+@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
+@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
+@REM     e.g. to debug Maven itself, use
+@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
+@REM ----------------------------------------------------------------------------
+
+@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
+@echo off
+@REM set title of command window
+title %0
+@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
+@if "%MAVEN_BATCH_ECHO%" == "on"  echo %MAVEN_BATCH_ECHO%
+
+@REM set %HOME% to equivalent of $HOME
+if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
+
+@REM Execute a user defined script before this one
+if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
+@REM check for pre script, once with legacy .bat ending and once with .cmd ending
+if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
+if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
+:skipRcPre
+
+@setlocal
+
+set ERROR_CODE=0
+
+@REM To isolate internal variables from possible post scripts, we use another setlocal
+@setlocal
+
+@REM ==== START VALIDATION ====
+if not "%JAVA_HOME%" == "" goto OkJHome
+
+echo.
+echo Error: JAVA_HOME not found in your environment. >&2
+echo Please set the JAVA_HOME variable in your environment to match the >&2
+echo location of your Java installation. >&2
+echo.
+goto error
+
+:OkJHome
+if exist "%JAVA_HOME%\bin\java.exe" goto init
+
+echo.
+echo Error: JAVA_HOME is set to an invalid directory. >&2
+echo JAVA_HOME = "%JAVA_HOME%" >&2
+echo Please set the JAVA_HOME variable in your environment to match the >&2
+echo location of your Java installation. >&2
+echo.
+goto error
+
+@REM ==== END VALIDATION ====
+
+:init
+
+@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
+@REM Fallback to current working directory if not found.
+
+set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
+IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
+
+set EXEC_DIR=%CD%
+set WDIR=%EXEC_DIR%
+:findBaseDir
+IF EXIST "%WDIR%"\.mvn goto baseDirFound
+cd ..
+IF "%WDIR%"=="%CD%" goto baseDirNotFound
+set WDIR=%CD%
+goto findBaseDir
+
+:baseDirFound
+set MAVEN_PROJECTBASEDIR=%WDIR%
+cd "%EXEC_DIR%"
+goto endDetectBaseDir
+
+:baseDirNotFound
+set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
+cd "%EXEC_DIR%"
+
+:endDetectBaseDir
+
+IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
+
+@setlocal EnableExtensions EnableDelayedExpansion
+for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
+@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
+
+:endReadAdditionalConfig
+
+SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
+set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
+set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
+
+set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
+FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
+	IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 
+)
+
+@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
+@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
+if exist %WRAPPER_JAR% (
+    echo Found %WRAPPER_JAR%
+) else (
+    echo Couldn't find %WRAPPER_JAR%, downloading it ...
+	echo Downloading from: %DOWNLOAD_URL%
+    powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
+    echo Finished downloading %WRAPPER_JAR%
+)
+@REM End of extension
+
+%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
+if ERRORLEVEL 1 goto error
+goto end
+
+:error
+set ERROR_CODE=1
+
+:end
+@endlocal & set ERROR_CODE=%ERROR_CODE%
+
+if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
+@REM check for post script, once with legacy .bat ending and once with .cmd ending
+if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
+if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
+:skipRcPost
+
+@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
+if "%MAVEN_BATCH_PAUSE%" == "on" pause
+
+if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
+
+exit /B %ERROR_CODE%

+ 291 - 0
pom.xml

@@ -0,0 +1,291 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>org.springframework.boot</groupId>
+        <artifactId>spring-boot-starter-parent</artifactId>
+        <version>2.3.2.RELEASE</version>
+        <relativePath/> <!-- lookup parent from repository -->
+    </parent>
+    <groupId>com.izouma</groupId>
+    <artifactId>9th</artifactId>
+    <version>0.0.1-SNAPSHOT</version>
+    <name>9th</name>
+    <description>9th</description>
+
+    <repositories>
+        <repository>
+            <id>nexus-aliyun</id>
+            <url>https://maven.aliyun.com/repository/central</url>
+        </repository>
+        <repository>
+            <id>Local repository</id>
+            <url>file://${basedir}/libs</url>
+        </repository>
+        <repository>
+            <id>jitpack.io</id>
+            <url>https://jitpack.io</url>
+        </repository>
+    </repositories>
+
+    <properties>
+        <java.version>1.8</java.version>
+        <skipTests>true</skipTests>
+        <poi.verion>3.17</poi.verion>
+        <javawx.version>3.5.0</javawx.version>
+        <aliyun.oss.version>2.8.3</aliyun.oss.version>
+        <aliyun.core.version>4.1.0</aliyun.core.version>
+    </properties>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.security</groupId>
+            <artifactId>spring-security-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-jpa</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-security</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-cache</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-aop</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>com.github.ben-manes.caffeine</groupId>
+            <artifactId>caffeine</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>javax.validation</groupId>
+            <artifactId>validation-api</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>mysql</groupId>
+            <artifactId>mysql-connector-java</artifactId>
+            <scope>runtime</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>org.hibernate</groupId>
+            <artifactId>hibernate-envers</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-configuration-processor</artifactId>
+            <optional>true</optional>
+        </dependency>
+
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <optional>true</optional>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-pool2</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>commons-beanutils</groupId>
+            <artifactId>commons-beanutils</artifactId>
+            <version>1.9.4</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-text</artifactId>
+            <version>1.3</version>
+        </dependency>
+
+        <dependency>
+            <groupId>io.jsonwebtoken</groupId>
+            <artifactId>jjwt</artifactId>
+            <version>0.9.1</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.google.code.findbugs</groupId>
+            <artifactId>annotations</artifactId>
+            <version>3.0.1</version>
+            <scope>provided</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>com.github.binarywang</groupId>
+            <artifactId>weixin-java-mp</artifactId>
+            <version>${javawx.version}</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.github.binarywang</groupId>
+            <artifactId>weixin-java-miniapp</artifactId>
+            <version>${javawx.version}</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.github.binarywang</groupId>
+            <artifactId>weixin-java-pay</artifactId>
+            <version>${javawx.version}</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.github.binarywang</groupId>
+            <artifactId>weixin-java-open</artifactId>
+            <version>${javawx.version}</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.aliyun.oss</groupId>
+            <artifactId>aliyun-sdk-oss</artifactId>
+            <version>${aliyun.oss.version}</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.aliyun</groupId>
+            <artifactId>aliyun-java-sdk-core</artifactId>
+            <version>${aliyun.core.version}</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.github.kevinsawicki</groupId>
+            <artifactId>http-request</artifactId>
+            <version>6.0</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.poi</groupId>
+            <artifactId>poi</artifactId>
+            <version>${poi.verion}</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.poi</groupId>
+            <artifactId>poi-ooxml</artifactId>
+            <version>${poi.verion}</version>
+        </dependency>
+
+        <dependency>
+            <groupId>cglib</groupId>
+            <artifactId>cglib</artifactId>
+            <version>3.1</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>easyexcel</artifactId>
+            <version>2.2.6</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.reflections</groupId>
+            <artifactId>reflections</artifactId>
+            <version>0.9.11</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.velocity</groupId>
+            <artifactId>velocity</artifactId>
+            <version>1.7</version>
+        </dependency>
+
+
+        <dependency>
+            <groupId>org.apache.velocity</groupId>
+            <artifactId>velocity-tools</artifactId>
+            <version>2.0</version>
+        </dependency>
+
+        <!-- https://mvnrepository.com/artifact/com.belerweb/pinyin4j -->
+        <dependency>
+            <groupId>com.belerweb</groupId>
+            <artifactId>pinyin4j</artifactId>
+            <version>2.5.1</version>
+        </dependency>
+        <!-- swagger -->
+        <dependency>
+            <groupId>io.springfox</groupId>
+            <artifactId>springfox-swagger2</artifactId>
+            <version>2.9.1</version>
+        </dependency>
+        <dependency>
+            <groupId>io.springfox</groupId>
+            <artifactId>springfox-swagger-ui</artifactId>
+            <version>2.9.1</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-freemarker</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>fastjson</artifactId>
+            <version>1.2.37</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.ning</groupId>
+            <artifactId>async-http-client</artifactId>
+            <version>1.9.32</version>
+        </dependency>
+        <!-- 钉钉 -->
+
+        <dependency>
+            <groupId>com.github.whvcse</groupId>
+            <artifactId>easy-captcha</artifactId>
+            <version>1.6.2</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.libjpegturbo</groupId>
+            <artifactId>mozjpeg4j</artifactId>
+            <version>1.1</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.pngquant</groupId>
+            <artifactId>pngquant4j</artifactId>
+            <version>1.0</version>
+        </dependency>
+    </dependencies>
+
+</project>

+ 21 - 0
src/main/java/com/izouma/nineth/Application.java

@@ -0,0 +1,21 @@
+package com.izouma.nineth;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.cache.annotation.EnableCaching;
+import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
+import org.springframework.scheduling.annotation.EnableScheduling;
+import springfox.documentation.swagger2.annotations.EnableSwagger2;
+
+@SpringBootApplication
+@EnableJpaAuditing
+@EnableSwagger2
+@EnableCaching
+@EnableScheduling
+public class Application {
+
+    public static void main(String[] args) {
+        SpringApplication.run(Application.class, args);
+    }
+
+}

+ 14 - 0
src/main/java/com/izouma/nineth/annotations/OperLog.java

@@ -0,0 +1,14 @@
+package com.izouma.nineth.annotations;
+
+import java.lang.annotation.*;
+
+@Target(ElementType.METHOD)
+@Retention(RetentionPolicy.RUNTIME)
+@Documented
+public @interface OperLog {
+    String value() default "";
+
+    String type() default "";
+
+    String desc() default "";
+}

+ 12 - 0
src/main/java/com/izouma/nineth/annotations/Searchable.java

@@ -0,0 +1,12 @@
+package com.izouma.nineth.annotations;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target(ElementType.FIELD)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface Searchable {
+    boolean value() default true;
+}

+ 188 - 0
src/main/java/com/izouma/nineth/aspect/OperLogAspect.java

@@ -0,0 +1,188 @@
+package com.izouma.nineth.aspect;
+
+import com.alibaba.fastjson.JSON;
+import com.izouma.nineth.annotations.OperLog;
+import com.izouma.nineth.domain.ExceptionLog;
+import com.izouma.nineth.domain.OperationLog;
+import com.izouma.nineth.domain.User;
+import com.izouma.nineth.repo.ExceptionLogRepo;
+import com.izouma.nineth.repo.OperationLogRepo;
+import com.izouma.nineth.utils.IPUtils;
+import com.izouma.nineth.utils.SecurityUtils;
+import org.aspectj.lang.JoinPoint;
+import org.aspectj.lang.annotation.AfterReturning;
+import org.aspectj.lang.annotation.AfterThrowing;
+import org.aspectj.lang.annotation.Aspect;
+import org.aspectj.lang.annotation.Pointcut;
+import org.aspectj.lang.reflect.MethodSignature;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.web.context.request.RequestAttributes;
+import org.springframework.web.context.request.RequestContextHolder;
+
+import javax.servlet.http.HttpServletRequest;
+import java.lang.reflect.Method;
+import java.time.LocalDateTime;
+import java.util.HashMap;
+import java.util.Map;
+
+@Aspect
+@Component
+public class OperLogAspect {
+
+    @Autowired
+    private OperationLogRepo operationLogRepo;
+
+    @Autowired
+    private ExceptionLogRepo exceptionLogRepo;
+
+    /**
+     * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
+     */
+    @Pointcut("@annotation(com.izouma.nineth.annotations.OperLog)")
+    public void operLogPointCut() {
+    }
+
+    /**
+     * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
+     */
+    @Pointcut("execution(* com.izouma.nineth.web..*.*(..))")
+    public void operExceptionLogPointCut() {
+    }
+
+    /**
+     * 正常返回通知,拦截用户操作日志,连接点正常执行完成后执行, 如果连接点抛出异常,则不会执行
+     *
+     * @param joinPoint 切入点
+     * @param keys      返回结果
+     */
+    @AfterReturning(value = "operLogPointCut()", returning = "keys")
+    public void saveOperLog(JoinPoint joinPoint, Object keys) {
+        // 获取RequestAttributes
+        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
+        // 从获取RequestAttributes中获取HttpServletRequest的信息
+        HttpServletRequest request = (HttpServletRequest) requestAttributes
+                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
+
+        OperationLog operationLog = new OperationLog();
+        try {
+            // 从切面织入点处通过反射机制获取织入点处的方法
+            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
+            // 获取切入点所在的方法
+            Method method = signature.getMethod();
+            // 获取操作
+            OperLog operLog = method.getAnnotation(OperLog.class);
+            if (operLog != null) {
+                operationLog.setName(operLog.value()); // 操作模块
+                operationLog.setType(operLog.type()); // 操作类型
+                operationLog.setDesc(operLog.desc()); // 操作描述
+            }
+            // 获取请求的类名
+            String className = joinPoint.getTarget().getClass().getName();
+            // 获取请求的方法名
+            String methodName = method.getName();
+            methodName = className + "." + methodName;
+
+            operationLog.setReqMethod(methodName);
+
+            // 请求的参数
+            Map<String, String> rtnMap = null;
+            String params = null;
+            if (request != null) {
+                rtnMap = convertMap(request.getParameterMap());
+                params = JSON.toJSONString(rtnMap);
+            }
+
+            operationLog.setReqParams(params);
+            operationLog.setResp(JSON.toJSONString(keys));
+
+            User user = SecurityUtils.getAuthenticatedUser();
+            if (user != null) {
+                operationLog.setUserId(String.valueOf(user.getId()));
+                operationLog.setUsername(user.getUsername());
+            }
+            operationLog.setReqIp(IPUtils.getIpAddr(request));
+            operationLog.setReqUrl(request != null ? request.getRequestURI() : null);
+            operationLog.setTime(LocalDateTime.now());
+            operationLogRepo.save(operationLog);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * 异常返回通知,用于拦截异常日志信息 连接点抛出异常后执行
+     *
+     * @param joinPoint 切入点
+     * @param e         异常信息
+     */
+    @AfterThrowing(pointcut = "operExceptionLogPointCut()", throwing = "e")
+    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
+        // 获取RequestAttributes
+        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
+        // 从获取RequestAttributes中获取HttpServletRequest的信息
+        HttpServletRequest request = (HttpServletRequest) requestAttributes
+                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
+
+        ExceptionLog exceptionLog = new ExceptionLog();
+        try {
+            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
+            Method method = signature.getMethod();
+            String className = joinPoint.getTarget().getClass().getName();
+            String methodName = method.getName();
+            methodName = className + "." + methodName;
+            exceptionLog.setReqMethod(methodName);
+
+            Map<String, String> rtnMap = convertMap(request.getParameterMap());
+            String params = JSON.toJSONString(rtnMap);
+            exceptionLog.setReqParams(params);
+
+            exceptionLog.setName(e.getClass().getName());
+            exceptionLog.setMessage(stackTraceToString(e.getClass().getName(), e.getMessage(), e
+                    .getStackTrace()));
+            User user = SecurityUtils.getAuthenticatedUser();
+            if (user != null) {
+                exceptionLog.setUserId(String.valueOf(user.getId()));
+                exceptionLog.setUsername(user.getUsername());
+            }
+
+            exceptionLog.setReqUrl(request.getRequestURI());
+            exceptionLog.setReqIp(IPUtils.getIpAddr(request));
+            exceptionLog.setTime(LocalDateTime.now());
+
+            exceptionLogRepo.save(exceptionLog);
+
+        } catch (Exception e2) {
+            e2.printStackTrace();
+        }
+
+    }
+
+    /**
+     * 转换request 请求参数
+     *
+     * @param paramMap request获取的参数数组
+     */
+    public Map<String, String> convertMap(Map<String, String[]> paramMap) {
+        Map<String, String> rtnMap = new HashMap<>();
+        for (String key : paramMap.keySet()) {
+            rtnMap.put(key, paramMap.get(key)[0]);
+        }
+        return rtnMap;
+    }
+
+    /**
+     * 转换异常信息为字符串
+     *
+     * @param exceptionName    异常名称
+     * @param exceptionMessage 异常信息
+     * @param elements         堆栈信息
+     */
+    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
+        StringBuilder strBuff = new StringBuilder();
+        for (StackTraceElement stet : elements) {
+            strBuff.append(stet).append("\n");
+        }
+        return exceptionName + ":" + exceptionMessage + "\n\t" + strBuff;
+    }
+}

+ 17 - 0
src/main/java/com/izouma/nineth/config/CacheConfig.java

@@ -0,0 +1,17 @@
+package com.izouma.nineth.config;
+
+import org.springframework.cache.CacheManager;
+import org.springframework.cache.annotation.EnableCaching;
+import org.springframework.cache.support.SimpleCacheManager;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@EnableCaching
+@Configuration
+public class CacheConfig {
+    @Bean
+    public CacheManager cacheManager() {
+        SimpleCacheManager manager = new SimpleCacheManager();
+        return manager;
+    }
+}

+ 17 - 0
src/main/java/com/izouma/nineth/config/Constants.java

@@ -0,0 +1,17 @@
+package com.izouma.nineth.config;
+
+public interface Constants {
+
+    public interface Regex {
+        String PHONE    = "^1[3-9]\\d{9}$";
+        String USERNAME = "^[_.@A-Za-z0-9-]*$";
+        String CHINESE  = "^[\\u4e00-\\u9fa5]+$";
+        String ID_NO    = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0-2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0-2]\\d)|3[0-1])\\d{3}[0-9xX]$";
+    }
+
+    String DEFAULT_AVATAR = "https://zhumj.oss-cn-hangzhou.aliyuncs.com/image/user.jpg";
+
+    String SMS_SIGN_NAME = "走马信息";
+
+    String SMS_TEMPLATE_CODE_GENERIC = "SMS_175485688";
+}

+ 148 - 0
src/main/java/com/izouma/nineth/config/DateConfig.java

@@ -0,0 +1,148 @@
+package com.izouma.nineth.config;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.*;
+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.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.convert.converter.Converter;
+
+import java.io.IOException;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Date;
+
+@Configuration
+public class DateConfig {
+
+    /**
+     * 默认日期时间格式
+     */
+    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
+    /**
+     * 默认日期格式
+     */
+    public static final String DEFAULT_DATE_FORMAT      = "yyyy-MM-dd";
+    /**
+     * 默认时间格式
+     */
+    public static final String DEFAULT_TIME_FORMAT      = "HH:mm:ss";
+
+    /**
+     * LocalDate转换器,用于转换RequestParam和PathVariable参数
+     */
+    @Bean
+    public Converter<String, LocalDate> localDateConverter() {
+        return new Converter<String, LocalDate>() {
+            @Override
+            public LocalDate convert(String source) {
+                return LocalDate.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT));
+            }
+        };
+    }
+
+    /**
+     * LocalDateTime转换器,用于转换RequestParam和PathVariable参数
+     */
+    @Bean
+    public Converter<String, LocalDateTime> localDateTimeConverter() {
+        return new Converter<String, LocalDateTime>() {
+            @Override
+            public LocalDateTime convert(String source) {
+                return LocalDateTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT));
+            }
+        };
+    }
+
+    /**
+     * LocalTime转换器,用于转换RequestParam和PathVariable参数
+     */
+    @Bean
+    public Converter<String, LocalTime> localTimeConverter() {
+        return new Converter<String, LocalTime>() {
+            @Override
+            public LocalTime convert(String source) {
+                return LocalTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT));
+            }
+        };
+    }
+
+    /**
+     * Date转换器,用于转换RequestParam和PathVariable参数
+     */
+    @Bean
+    public Converter<String, Date> dateConverter() {
+        return new Converter<String, Date>() {
+            @Override
+            public Date convert(String source) {
+                SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
+                try {
+                    return format.parse(source);
+                } catch (ParseException e) {
+                    throw new RuntimeException(e);
+                }
+            }
+        };
+    }
+
+
+    /**
+     * Json序列化和反序列化转换器,用于转换Post请求体中的json以及将我们的对象序列化为返回响应的json
+     */
+    @Bean
+    public ObjectMapper objectMapper() {
+        ObjectMapper objectMapper = new ObjectMapper();
+        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
+        objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
+
+        //LocalDateTime系列序列化和反序列化模块,继承自jsr310,我们在这里修改了日期格式
+        JavaTimeModule javaTimeModule = new JavaTimeModule();
+        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
+        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
+        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
+        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
+        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
+        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
+
+
+        //Date序列化和反序列化
+        javaTimeModule.addSerializer(Date.class, new JsonSerializer<Date>() {
+            @Override
+            public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
+                SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
+                String formattedDate = formatter.format(date);
+                jsonGenerator.writeString(formattedDate);
+            }
+        });
+        javaTimeModule.addDeserializer(Date.class, new JsonDeserializer<Date>() {
+            @Override
+            public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
+                SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
+                String date = jsonParser.getText();
+                try {
+                    return format.parse(date);
+                } catch (ParseException e) {
+                    throw new RuntimeException(e);
+                }
+            }
+        });
+
+        objectMapper.registerModule(javaTimeModule);
+        return objectMapper;
+    }
+
+
+}
+

+ 36 - 0
src/main/java/com/izouma/nineth/config/LocalDateTimeSerializerConfig.java

@@ -0,0 +1,36 @@
+package com.izouma.nineth.config;
+
+import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
+import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+
+@Configuration
+public class LocalDateTimeSerializerConfig {
+    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
+    private String pattern;
+
+    @Bean
+    public LocalDateTimeSerializer localDateTimeDeserializer() {
+        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
+    }
+
+    @Bean
+    public LocalDateSerializer localDateSerializer() {
+        return new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
+    }
+
+    @Bean
+    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
+        return builder -> {
+            builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
+            builder.serializerByType(LocalDate.class, localDateSerializer());
+        };
+    }
+}

+ 24 - 0
src/main/java/com/izouma/nineth/config/SpringSecurityAuditorAware.java

@@ -0,0 +1,24 @@
+package com.izouma.nineth.config;
+
+import com.izouma.nineth.domain.User;
+import com.izouma.nineth.utils.SecurityUtils;
+import org.springframework.data.domain.AuditorAware;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Nonnull;
+import java.util.Optional;
+
+@Component
+public class SpringSecurityAuditorAware implements AuditorAware<String> {
+
+    @Override
+    @Nonnull
+    public Optional<String> getCurrentAuditor() {
+        String auditor = "system";
+        User user = SecurityUtils.getAuthenticatedUser();
+        if (user != null) {
+            auditor = user.getNickname() + "(" + user.getId() + ")";
+        }
+        return Optional.of(auditor);
+    }
+}

+ 76 - 0
src/main/java/com/izouma/nineth/config/WebMvcConfig.java

@@ -0,0 +1,76 @@
+package com.izouma.nineth.config;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.CorsRegistry;
+import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+import springfox.documentation.builders.ApiInfoBuilder;
+import springfox.documentation.builders.PathSelectors;
+import springfox.documentation.builders.RequestHandlerSelectors;
+import springfox.documentation.spi.DocumentationType;
+import springfox.documentation.spring.web.plugins.Docket;
+
+@Configuration
+public class WebMvcConfig implements WebMvcConfigurer {
+    @Value("${storage.local_path}")
+    private String localPath;
+
+    @Override
+    public void addResourceHandlers(ResourceHandlerRegistry registry) {
+        // registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
+        // registry.addResourceHandler("webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
+        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
+        registry.addResourceHandler("/admin/**").addResourceLocations("classpath:/static/admin/");
+        registry.addResourceHandler("/files/**").addResourceLocations("file:" + localPath);
+        registry.addResourceHandler("/MP_verify*").addResourceLocations("classpath:/");
+    }
+
+    @Bean
+    public Docket createApi() {
+        return new Docket(DocumentationType.SWAGGER_2)
+                .apiInfo(new ApiInfoBuilder()
+                                 .title("接口文档")
+                                 .version("1.0.0")
+                                 .termsOfServiceUrl("#")
+                                 .description("接口文档")
+                                 .build())
+                .select()
+                .apis(RequestHandlerSelectors.basePackage("com.izouma.nineth.web"))
+                .paths(PathSelectors.any())
+                .build();
+    }
+
+    // @Bean
+    // public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
+    //     MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
+    //     //设置日期格式
+    //     ObjectMapper objectMapper = new ObjectMapper();
+    //     objectMapper.setDateFormat(CustomDateFormat.instance);
+    //     objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
+    //     mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
+    //     //设置中文编码格式
+    //     List<MediaType> list = new ArrayList<>();
+    //     list.add(MediaType.APPLICATION_JSON_UTF8);
+    //     mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list);
+    //     return mappingJackson2HttpMessageConverter;
+    // }
+
+//    @Override
+//    public void addFormatters(FormatterRegistry registry) {
+//        DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
+//        registrar.setUseIsoFormat(true);
+//        registrar.registerFormatters(registry);
+//    }
+
+    @Override
+    public void addCorsMappings(CorsRegistry registry) {
+        registry.addMapping("/**")
+                .allowedHeaders("*")
+                .allowCredentials(true)
+                .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH")
+                .exposedHeaders("Content-Disposition");
+    }
+
+}

+ 30 - 0
src/main/java/com/izouma/nineth/config/WxMaConfiguration.java

@@ -0,0 +1,30 @@
+package com.izouma.nineth.config;
+
+import cn.binarywang.wx.miniapp.api.WxMaService;
+import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
+import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
+import lombok.AllArgsConstructor;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@AllArgsConstructor
+@Configuration
+@EnableConfigurationProperties(WxMaProperties.class)
+public class WxMaConfiguration {
+    private final WxMaProperties properties;
+
+    @Bean
+    public WxMaService wxMaService() {
+        WxMaService service = new WxMaServiceImpl();
+        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
+        config.setAppid(properties.getAppId());
+        config.setSecret(properties.getAppSecret());
+        config.setToken(properties.getMsgToken());
+        config.setAesKey(properties.getMsgAesKey());
+        config.setMsgDataFormat(properties.getMsgFormat());
+        service.setWxMaConfig(config);
+        return service;
+    }
+
+}

+ 14 - 0
src/main/java/com/izouma/nineth/config/WxMaProperties.java

@@ -0,0 +1,14 @@
+package com.izouma.nineth.config;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+@Data
+@ConfigurationProperties(prefix = "wx.ma")
+public class WxMaProperties {
+    private String appId;
+    private String appSecret;
+    private String msgToken;
+    private String msgAesKey;
+    private String msgFormat;
+}

+ 74 - 0
src/main/java/com/izouma/nineth/config/WxMpConfiguration.java

@@ -0,0 +1,74 @@
+package com.izouma.nineth.config;
+
+import com.izouma.nineth.mpHandler.LogHandler;
+import lombok.AllArgsConstructor;
+import me.chanjar.weixin.mp.api.WxMpMessageRouter;
+import me.chanjar.weixin.mp.api.WxMpService;
+import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
+import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@AllArgsConstructor
+@Configuration
+@EnableConfigurationProperties(WxMpProperties.class)
+public class WxMpConfiguration {
+    private final WxMpProperties properties;
+    private final LogHandler     logHandler;
+
+    @Bean
+    public WxMpService wxMpService() {
+        WxMpDefaultConfigImpl mpConfig = new WxMpDefaultConfigImpl();
+        mpConfig.setAppId(properties.getAppId());
+        mpConfig.setSecret(properties.getAppSecret());
+        mpConfig.setAccessToken(properties.getToken());
+        mpConfig.setAesKey(properties.getAesKey());
+        WxMpService service = new WxMpServiceImpl();
+        service.setWxMpConfigStorage(mpConfig);
+        return service;
+    }
+
+    @Bean
+    public WxMpMessageRouter messageRouter(WxMpService wxMpService) {
+        final WxMpMessageRouter newRouter = new WxMpMessageRouter(wxMpService);
+
+        // 记录所有事件的日志 (异步执行)
+        newRouter.rule().handler(this.logHandler).next();
+
+        /*// 接收客服会话管理事件
+        newRouter.rule().async(false).msgType(EVENT).event(KF_CREATE_SESSION).handler(this.kfSessionHandler).end();
+        newRouter.rule().async(false).msgType(EVENT).event(KF_CLOSE_SESSION).handler(this.kfSessionHandler).end();
+        newRouter.rule().async(false).msgType(EVENT).event(KF_SWITCH_SESSION).handler(this.kfSessionHandler).end();
+
+        // 门店审核事件
+        newRouter.rule().async(false).msgType(EVENT).event(POI_CHECK_NOTIFY).handler(this.storeCheckNotifyHandler).end();
+
+        // 自定义菜单事件
+        newRouter.rule().async(false).msgType(EVENT).event(WxConsts.EventType.CLICK).handler(this.menuHandler).end();
+
+        // 点击菜单连接事件
+        newRouter.rule().async(false).msgType(EVENT).event(WxConsts.EventType.VIEW).handler(this.nullHandler).end();
+
+        // 关注事件
+        newRouter.rule().async(false).msgType(EVENT).event(SUBSCRIBE).handler(this.subscribeHandler).end();
+
+        // 取消关注事件
+        newRouter.rule().async(false).msgType(EVENT).event(UNSUBSCRIBE).handler(this.unsubscribeHandler).end();
+
+        // 上报地理位置事件
+        newRouter.rule().async(false).msgType(EVENT).event(WxConsts.EventType.LOCATION).handler(this.locationHandler).end();
+
+        // 接收地理位置消息
+        newRouter.rule().async(false).msgType(WxConsts.XmlMsgType.LOCATION).handler(this.locationHandler).end();
+
+        // 扫码事件
+        newRouter.rule().async(false).msgType(EVENT).event(WxConsts.EventType.SCAN).handler(this.scanHandler).end();
+
+        // 默认
+        newRouter.rule().async(false).handler(this.msgHandler).end();*/
+
+        return newRouter;
+    }
+
+}

+ 13 - 0
src/main/java/com/izouma/nineth/config/WxMpProperties.java

@@ -0,0 +1,13 @@
+package com.izouma.nineth.config;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+@Data
+@ConfigurationProperties(prefix = "wx.mp")
+public class WxMpProperties {
+    private String appId;
+    private String appSecret;
+    private String token;
+    private String aesKey;
+}

+ 47 - 0
src/main/java/com/izouma/nineth/config/WxPayConfiguration.java

@@ -0,0 +1,47 @@
+package com.izouma.nineth.config;
+
+import com.github.binarywang.wxpay.config.WxPayConfig;
+import com.github.binarywang.wxpay.service.WxPayService;
+import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * @author Binary Wang
+ */
+@Configuration
+@ConditionalOnClass(WxPayService.class)
+@EnableConfigurationProperties(WxPayProperties.class)
+public class WxPayConfiguration {
+    private WxPayProperties properties;
+
+    @Autowired
+    public WxPayConfiguration(WxPayProperties properties) {
+        this.properties = properties;
+    }
+
+    @Bean
+    @ConditionalOnMissingBean
+    public WxPayService wxService() {
+        WxPayConfig payConfig = new WxPayConfig();
+        payConfig.setAppId(StringUtils.trimToNull(this.properties.getAppId()));
+        payConfig.setMchId(StringUtils.trimToNull(this.properties.getMchId()));
+        payConfig.setMchKey(StringUtils.trimToNull(this.properties.getMchKey()));
+        payConfig.setSubAppId(StringUtils.trimToNull(this.properties.getSubAppId()));
+        payConfig.setSubMchId(StringUtils.trimToNull(this.properties.getSubMchId()));
+        payConfig.setKeyPath(StringUtils.trimToNull(this.properties.getKeyPath()));
+
+        // 可以指定是否使用沙箱环境
+        payConfig.setUseSandboxEnv(false);
+
+        WxPayService wxPayService = new WxPayServiceImpl();
+        wxPayService.setConfig(payConfig);
+        return wxPayService;
+    }
+
+}

+ 97 - 0
src/main/java/com/izouma/nineth/config/WxPayProperties.java

@@ -0,0 +1,97 @@
+package com.izouma.nineth.config;
+
+import org.apache.commons.lang3.builder.ToStringBuilder;
+import org.apache.commons.lang3.builder.ToStringStyle;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+/**
+ * wxpay pay properties
+ *
+ * @author Binary Wang
+ */
+@ConfigurationProperties(prefix = "wx.pay")
+public class WxPayProperties {
+  /**
+   * 设置微信公众号或者小程序等的appid
+   */
+  private String appId;
+
+  /**
+   * 微信支付商户号
+   */
+  private String mchId;
+
+  /**
+   * 微信支付商户密钥
+   */
+  private String mchKey;
+
+  /**
+   * 服务商模式下的子商户公众账号ID,普通模式请不要配置,请在配置文件中将对应项删除
+   */
+  private String subAppId;
+
+  /**
+   * 服务商模式下的子商户号,普通模式请不要配置,最好是请在配置文件中将对应项删除
+   */
+  private String subMchId;
+
+  /**
+   * apiclient_cert.p12文件的绝对路径,或者如果放在项目中,请以classpath:开头指定
+   */
+  private String keyPath;
+
+  public String getAppId() {
+    return this.appId;
+  }
+
+  public void setAppId(String appId) {
+    this.appId = appId;
+  }
+
+  public String getMchId() {
+    return mchId;
+  }
+
+  public void setMchId(String mchId) {
+    this.mchId = mchId;
+  }
+
+  public String getMchKey() {
+    return mchKey;
+  }
+
+  public void setMchKey(String mchKey) {
+    this.mchKey = mchKey;
+  }
+
+  public String getSubAppId() {
+    return subAppId;
+  }
+
+  public void setSubAppId(String subAppId) {
+    this.subAppId = subAppId;
+  }
+
+  public String getSubMchId() {
+    return subMchId;
+  }
+
+  public void setSubMchId(String subMchId) {
+    this.subMchId = subMchId;
+  }
+
+  public String getKeyPath() {
+    return this.keyPath;
+  }
+
+  public void setKeyPath(String keyPath) {
+    this.keyPath = keyPath;
+  }
+
+  @Override
+  public String toString() {
+    return ToStringBuilder.reflectionToString(this,
+        ToStringStyle.MULTI_LINE_STYLE);
+  }
+}

+ 24 - 0
src/main/java/com/izouma/nineth/converter/FileObjectConverter.java

@@ -0,0 +1,24 @@
+package com.izouma.nineth.converter;
+
+import com.alibaba.fastjson.JSON;
+import com.izouma.nineth.domain.FileObject;
+import org.apache.commons.lang3.StringUtils;
+
+import javax.persistence.AttributeConverter;
+
+public class FileObjectConverter implements AttributeConverter<FileObject, String> {
+    @Override
+    public String convertToDatabaseColumn(FileObject fileObject) {
+        if (fileObject != null  )
+            return JSON.toJSONString(fileObject);
+        return null;
+    }
+
+    @Override
+    public FileObject convertToEntityAttribute(String s) {
+        if (StringUtils.isNotEmpty(s)) {
+            return JSON.parseObject(s, FileObject.class);
+        }
+        return null;
+    }
+}

+ 25 - 0
src/main/java/com/izouma/nineth/converter/FileObjectListConverter.java

@@ -0,0 +1,25 @@
+package com.izouma.nineth.converter;
+
+import com.alibaba.fastjson.JSON;
+import com.izouma.nineth.domain.FileObject;
+import org.apache.commons.lang3.StringUtils;
+
+import javax.persistence.AttributeConverter;
+import java.util.List;
+
+public class FileObjectListConverter implements AttributeConverter<List<FileObject>, String> {
+    @Override
+    public String convertToDatabaseColumn(List<FileObject> list) {
+        if (list != null)
+            return JSON.toJSONString(list);
+        return null;
+    }
+
+    @Override
+    public List<FileObject> convertToEntityAttribute(String s) {
+        if (StringUtils.isNotEmpty(s)) {
+            return JSON.parseArray(s, FileObject.class);
+        }
+        return null;
+    }
+}

+ 28 - 0
src/main/java/com/izouma/nineth/converter/JSONObjectConverter.java

@@ -0,0 +1,28 @@
+package com.izouma.nineth.converter;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import lombok.extern.slf4j.Slf4j;
+
+import javax.persistence.AttributeConverter;
+
+@Slf4j
+public class JSONObjectConverter implements AttributeConverter<JSONObject, String> {
+    @Override
+    public String convertToDatabaseColumn(JSONObject jsonObject) {
+        if (jsonObject != null) {
+            return jsonObject.toJSONString();
+        }
+        return null;
+    }
+
+    @Override
+    public JSONObject convertToEntityAttribute(String s) {
+        try {
+            return JSON.parseObject(s);
+        } catch (Exception e) {
+            log.error("parse json error", e);
+        }
+        return null;
+    }
+}

+ 26 - 0
src/main/java/com/izouma/nineth/converter/LongArrayConverter.java

@@ -0,0 +1,26 @@
+package com.izouma.nineth.converter;
+
+import org.apache.commons.lang3.StringUtils;
+
+import javax.persistence.AttributeConverter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class LongArrayConverter implements AttributeConverter<List<Long>, String> {
+    @Override
+    public String convertToDatabaseColumn(List<Long> longs) {
+        if (longs != null && !longs.isEmpty())
+            return StringUtils.join(longs, ",");
+        return null;
+    }
+
+    @Override
+    public List<Long> convertToEntityAttribute(String s) {
+        if (StringUtils.isNotEmpty(s)) {
+            return Arrays.stream(s.split(",")).map(Long::parseLong).collect(Collectors.toList());
+        }
+        return new ArrayList<>();
+    }
+}

+ 25 - 0
src/main/java/com/izouma/nineth/converter/StringArrayConverter.java

@@ -0,0 +1,25 @@
+package com.izouma.nineth.converter;
+
+import org.apache.commons.lang3.StringUtils;
+
+import javax.persistence.AttributeConverter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class StringArrayConverter implements AttributeConverter<List<String>, String> {
+    @Override
+    public String convertToDatabaseColumn(List<String> strings) {
+        if (strings != null && !strings.isEmpty())
+            return StringUtils.join(strings, ",");
+        return null;
+    }
+
+    @Override
+    public List<String> convertToEntityAttribute(String s) {
+        if (StringUtils.isNotEmpty(s)) {
+            return Arrays.asList(s.split(","));
+        }
+        return new ArrayList<>();
+    }
+}

+ 24 - 0
src/main/java/com/izouma/nineth/converter/StringToMapConverter.java

@@ -0,0 +1,24 @@
+package com.izouma.nineth.converter;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.springframework.core.convert.converter.Converter;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.util.Map;
+
+@Component
+public class StringToMapConverter implements Converter<String, Map<String, Object>> {
+
+    @Override
+    public Map<String, Object> convert(@Nullable String source) {
+        try {
+            return new ObjectMapper().readValue(source, new TypeReference<Map<String, Object>>() {
+            });
+        } catch (IOException e) {
+            throw new RuntimeException(e.getMessage());
+        }
+    }
+}

+ 83 - 0
src/main/java/com/izouma/nineth/domain/AuditedEntity.java

@@ -0,0 +1,83 @@
+package com.izouma.nineth.domain;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.hibernate.envers.Audited;
+import org.springframework.data.annotation.CreatedBy;
+import org.springframework.data.annotation.CreatedDate;
+import org.springframework.data.annotation.LastModifiedBy;
+import org.springframework.data.annotation.LastModifiedDate;
+import org.springframework.data.jpa.domain.support.AuditingEntityListener;
+
+import javax.persistence.EntityListeners;
+import javax.persistence.MappedSuperclass;
+import java.time.LocalDateTime;
+
+@MappedSuperclass
+@Audited
+@EntityListeners(AuditingEntityListener.class)
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonIgnoreProperties(ignoreUnknown = true)
+public abstract class AuditedEntity {
+
+    @JsonIgnore
+    @CreatedBy
+    private String createdBy;
+
+    @JsonIgnore
+    @CreatedDate
+    private LocalDateTime createdAt;
+
+    @JsonIgnore
+    @LastModifiedBy
+    private String modifiedBy;
+
+    @JsonIgnore
+    @LastModifiedDate
+    private LocalDateTime modifiedAt;
+
+    private boolean del;
+
+    public String getCreatedBy() {
+        return createdBy;
+    }
+
+    public void setCreatedBy(String createdBy) {
+        this.createdBy = createdBy;
+    }
+
+    @JsonProperty("createdAt")
+    public LocalDateTime getCreatedAt() {
+        return createdAt;
+    }
+
+    public void setCreatedAt(LocalDateTime createdAt) {
+        this.createdAt = createdAt;
+    }
+
+    public String getModifiedBy() {
+        return modifiedBy;
+    }
+
+    public void setModifiedBy(String modifiedBy) {
+        this.modifiedBy = modifiedBy;
+    }
+
+    public LocalDateTime getModifiedAt() {
+        return modifiedAt;
+    }
+
+    public void setModifiedAt(LocalDateTime modifiedAt) {
+        this.modifiedAt = modifiedAt;
+    }
+
+    public boolean isDel() {
+        return del;
+    }
+
+    public void setDel(boolean del) {
+        this.del = del;
+    }
+}

+ 93 - 0
src/main/java/com/izouma/nineth/domain/BaseEntity.java

@@ -0,0 +1,93 @@
+package com.izouma.nineth.domain;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.hibernate.envers.Audited;
+import org.springframework.data.annotation.CreatedBy;
+import org.springframework.data.annotation.CreatedDate;
+import org.springframework.data.annotation.LastModifiedBy;
+import org.springframework.data.annotation.LastModifiedDate;
+import org.springframework.data.jpa.domain.support.AuditingEntityListener;
+
+import javax.persistence.*;
+import java.time.LocalDateTime;
+
+@MappedSuperclass
+@Audited
+@EntityListeners(AuditingEntityListener.class)
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonIgnoreProperties(value = {"hibernateLazyInitializer"}, ignoreUnknown = true)
+public abstract class BaseEntity {
+    @Id
+    @GeneratedValue(strategy = GenerationType.AUTO)
+    private Long id;
+
+    @JsonIgnore
+    @CreatedBy
+    private String createdBy;
+
+    @JsonIgnore
+    @CreatedDate
+    private LocalDateTime createdAt;
+
+    @JsonIgnore
+    @LastModifiedBy
+    private String modifiedBy;
+
+    @JsonIgnore
+    @LastModifiedDate
+    private LocalDateTime modifiedAt;
+
+    private boolean del;
+
+    public Long getId() {
+        return id;
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    public String getCreatedBy() {
+        return createdBy;
+    }
+
+    public void setCreatedBy(String createdBy) {
+        this.createdBy = createdBy;
+    }
+
+    @JsonProperty("createdAt")
+    public LocalDateTime getCreatedAt() {
+        return createdAt;
+    }
+
+    public void setCreatedAt(LocalDateTime createdAt) {
+        this.createdAt = createdAt;
+    }
+
+    public String getModifiedBy() {
+        return modifiedBy;
+    }
+
+    public void setModifiedBy(String modifiedBy) {
+        this.modifiedBy = modifiedBy;
+    }
+
+    public LocalDateTime getModifiedAt() {
+        return modifiedAt;
+    }
+
+    public void setModifiedAt(LocalDateTime modifiedAt) {
+        this.modifiedAt = modifiedAt;
+    }
+
+    public boolean isDel() {
+        return del;
+    }
+
+    public void setDel(boolean del) {
+        this.del = del;
+    }
+}

+ 49 - 0
src/main/java/com/izouma/nineth/domain/District.java

@@ -0,0 +1,49 @@
+package com.izouma.nineth.domain;
+
+import com.izouma.nineth.annotations.Searchable;
+import com.izouma.nineth.enums.DistrictLevel;
+import io.swagger.annotations.ApiModel;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import javax.persistence.*;
+
+@Data
+@Entity
+@AllArgsConstructor
+@NoArgsConstructor
+@Builder
+@ApiModel("行政区域")
+public class District extends AuditedEntity {
+    @Id
+    private Long id;
+
+    @Column(length = 10)
+    private String cityCode;
+
+    @Searchable
+    private String name;
+
+    private double lat;
+
+    private double lng;
+
+    @Column(length = 20)
+    @Enumerated(EnumType.STRING)
+    private DistrictLevel level;
+
+    private Long parent;
+
+    private int childCount;
+
+    private int cityCount;
+
+    private int districtCount;
+
+    private int streetCount;
+
+    @Transient
+    private Boolean leaf;
+}

+ 71 - 0
src/main/java/com/izouma/nineth/domain/ExceptionLog.java

@@ -0,0 +1,71 @@
+package com.izouma.nineth.domain;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import javax.persistence.*;
+import java.time.LocalDateTime;
+
+@Data
+@Entity
+@AllArgsConstructor
+@NoArgsConstructor
+@Builder
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonIgnoreProperties(value = {"hibernateLazyInitializer"}, ignoreUnknown = true)
+@ApiModel("异常日志")
+public class ExceptionLog {
+    @Id
+    @GeneratedValue(strategy = GenerationType.AUTO)
+    private Long id;
+
+    @ApiModelProperty("异常名称")
+    private String name;
+
+    @ApiModelProperty("操作类型")
+    private String type;
+
+    @ApiModelProperty("用户ID")
+    private String userId;
+
+    @ApiModelProperty("用户名")
+    private String username;
+
+    @ApiModelProperty("描述")
+    @Column(name = "description")
+    private String desc;
+
+    @ApiModelProperty("调用方法")
+    private String reqMethod;
+
+    @ApiModelProperty("请求地址")
+    private String reqUrl;
+
+    @ApiModelProperty("请求参数")
+    @Lob
+    private String reqParams;
+
+    @ApiModelProperty("请求ip")
+    private String reqIp;
+
+    @ApiModelProperty("返回结果")
+    @Lob
+    private String resp;
+
+    @ApiModelProperty("操作时间")
+    private LocalDateTime time;
+
+    @ApiModelProperty("异常消息")
+    @Lob
+    private String message;
+
+    @ApiModelProperty("错误追踪")
+    @Lob
+    private String stackTrace;
+}

+ 10 - 0
src/main/java/com/izouma/nineth/domain/FileObject.java

@@ -0,0 +1,10 @@
+package com.izouma.nineth.domain;
+
+import lombok.Data;
+
+@Data
+public class FileObject {
+    String name;
+
+    String url;
+}

+ 71 - 0
src/main/java/com/izouma/nineth/domain/Menu.java

@@ -0,0 +1,71 @@
+package com.izouma.nineth.domain;
+
+import com.alibaba.excel.annotation.ExcelIgnore;
+import com.izouma.nineth.dto.MenuDTO;
+import com.izouma.nineth.security.Authority;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.hibernate.annotations.Where;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+@Data
+@Entity
+@NoArgsConstructor
+@AllArgsConstructor
+@Builder
+@Where(clause = "active = 1")
+public class Menu extends BaseEntity implements Serializable {
+    private String name;
+
+    private String path;
+
+    private String icon;
+
+    private Integer sort;
+
+    private Long parent;
+
+    private Boolean root;
+
+    private Boolean enabled;
+
+    private Boolean active;
+
+    private String category;
+
+    @OneToMany
+    @JoinColumn(name = "parent", insertable = false, updatable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
+    List<Menu> children;
+
+    @ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.DETACH})
+    @JoinTable(
+            name = "menu_authority",
+            joinColumns = {@JoinColumn(name = "menu_id", referencedColumnName = "id")},
+            inverseJoinColumns = {@JoinColumn(name = "authority", referencedColumnName = "name")})
+    @ExcelIgnore
+    private Set<Authority> authorities = new HashSet<>();
+
+    public static Menu from(MenuDTO menuDTO) {
+        Menu menu = Menu.builder()
+                .name(menuDTO.getName())
+                .path(menuDTO.getPath())
+                .icon(menuDTO.getIcon())
+                .sort(menuDTO.getSort())
+                .parent(menuDTO.getParent())
+                .root(menuDTO.getRoot())
+                .enabled(menuDTO.getEnabled())
+                .active(menuDTO.getActive())
+                .category(menuDTO.getCategory())
+                .children(null)
+                .build();
+        menu.setId(menuDTO.getId());
+        return menu;
+    }
+}

+ 63 - 0
src/main/java/com/izouma/nineth/domain/OperationLog.java

@@ -0,0 +1,63 @@
+package com.izouma.nineth.domain;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import javax.persistence.*;
+import java.time.LocalDateTime;
+
+@Data
+@Entity
+@AllArgsConstructor
+@NoArgsConstructor
+@Builder
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonIgnoreProperties(value = {"hibernateLazyInitializer"}, ignoreUnknown = true)
+@ApiModel("操作日志")
+public class OperationLog {
+    @Id
+    @GeneratedValue(strategy = GenerationType.AUTO)
+    private Long id;
+
+    @ApiModelProperty("操作名称")
+    private String name;
+
+    @ApiModelProperty("操作类型")
+    private String type;
+
+    @ApiModelProperty("用户ID")
+    private String userId;
+
+    @ApiModelProperty("用户名")
+    private String username;
+
+    @ApiModelProperty("描述")
+    @Column(name = "description")
+    private String desc;
+
+    @ApiModelProperty("调用方法")
+    private String reqMethod;
+
+    @ApiModelProperty("请求地址")
+    private String reqUrl;
+
+    @ApiModelProperty("请求参数")
+    @Lob
+    private String reqParams;
+
+    @ApiModelProperty("请求ip")
+    private String reqIp;
+
+    @ApiModelProperty("返回结果")
+    @Lob
+    private String resp;
+
+    @ApiModelProperty("操作时间")
+    private LocalDateTime time;
+}

+ 32 - 0
src/main/java/com/izouma/nineth/domain/SmsRecord.java

@@ -0,0 +1,32 @@
+package com.izouma.nineth.domain;
+
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import javax.persistence.Entity;
+import java.time.LocalDateTime;
+
+@Data
+@Entity
+@AllArgsConstructor
+@NoArgsConstructor
+@Builder
+@ApiModel(value = "短信验证码记录", description = "短信验证码记录")
+public class SmsRecord extends BaseEntity {
+    @ApiModelProperty(value = "会话ID", name = "sessionId")
+    private String        sessionId;
+    @ApiModelProperty(value = "手机号", name = "phone;")
+    private String        phone;
+    @ApiModelProperty(value = "验证码", name = "code")
+    private String        code;
+    @ApiModelProperty(value = "过期时间", name = "expiresAt")
+    private LocalDateTime expiresAt;
+    @ApiModelProperty(value = "是否过期", name = "expired")
+    private Boolean       expired;
+    @ApiModelProperty(value = "验证码用途", name = "scope")
+    private String        scope;
+}

+ 57 - 0
src/main/java/com/izouma/nineth/domain/SuperUser.java

@@ -0,0 +1,57 @@
+package com.izouma.nineth.domain;
+
+import com.alibaba.excel.annotation.ExcelIgnore;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.izouma.nineth.annotations.Searchable;
+import com.izouma.nineth.config.Constants;
+import com.izouma.nineth.security.Authority;
+import io.swagger.annotations.ApiModel;
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.hibernate.annotations.BatchSize;
+import org.hibernate.annotations.Where;
+
+import javax.persistence.*;
+import javax.validation.constraints.Pattern;
+import javax.validation.constraints.Size;
+import java.util.HashSet;
+import java.util.Set;
+
+@Data
+@Entity
+@AllArgsConstructor
+@NoArgsConstructor
+@Where(clause = "enabled = 1")
+@ApiModel(value = "超级用户", description = "超级用户")
+public class SuperUser extends BaseEntity {
+
+    @Pattern(regexp = Constants.Regex.USERNAME)
+    @Size(min = 1, max = 50)
+    @Column(nullable = false, unique = true)
+    @Searchable
+    private String username;
+
+    @Searchable
+    private String nickname;
+
+    private String avatar;
+
+    @JsonIgnore
+    private String password;
+
+    @Searchable
+    private String phone;
+
+    @Column(nullable = false)
+    private Boolean enabled = true;
+
+    @ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.ALL})
+    @JoinTable(
+            name = "super_user_authority",
+            joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
+            inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")})
+    @BatchSize(size = 20)
+    @ExcelIgnore
+    private Set<Authority> authorities = new HashSet<>();
+}

+ 40 - 0
src/main/java/com/izouma/nineth/domain/SysConfig.java

@@ -0,0 +1,40 @@
+package com.izouma.nineth.domain;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import javax.persistence.*;
+
+@Data
+@Entity
+@AllArgsConstructor
+@NoArgsConstructor
+@Builder
+public class SysConfig extends AuditedEntity {
+    @Id
+    @Column(length = 25, unique = true)
+    @ApiModelProperty(value = "名称", name = "name")
+    private String name;
+
+    @Column(name = "description")
+    @ApiModelProperty(value = "描述", name = "desc")
+    private String desc;
+
+    @ApiModelProperty(value = "值", name = "value")
+    private String value;
+
+    @Enumerated(EnumType.STRING)
+    private ValueType type;
+
+    public enum ValueType {
+        STRING,
+        TIME,
+        DATE,
+        DATETIME,
+        BOOLEAN,
+        NUMBER
+    }
+}

+ 17 - 0
src/main/java/com/izouma/nineth/domain/TestClass.java

@@ -0,0 +1,17 @@
+package com.izouma.nineth.domain;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import javax.persistence.Entity;
+
+@Data
+@Entity
+@AllArgsConstructor
+@NoArgsConstructor
+@Builder
+public class TestClass extends BaseEntity {
+    private String name;
+}

+ 71 - 0
src/main/java/com/izouma/nineth/domain/User.java

@@ -0,0 +1,71 @@
+package com.izouma.nineth.domain;
+
+import com.alibaba.excel.annotation.ExcelIgnore;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.izouma.nineth.annotations.Searchable;
+import com.izouma.nineth.config.Constants;
+import com.izouma.nineth.security.Authority;
+import io.swagger.annotations.ApiModel;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.hibernate.annotations.BatchSize;
+
+import javax.persistence.*;
+import javax.validation.constraints.Pattern;
+import javax.validation.constraints.Size;
+import java.io.Serializable;
+import java.util.HashSet;
+import java.util.Set;
+
+@Data
+@Entity
+@AllArgsConstructor
+@NoArgsConstructor
+@Builder
+@ApiModel(value = "用户", description = "用户")
+public class User extends BaseEntity implements Serializable {
+
+    @Pattern(regexp = Constants.Regex.USERNAME)
+    @Size(min = 1, max = 50)
+    @Column(nullable = false, unique = true)
+    @Searchable
+    private String username;
+
+    @Searchable
+    private String nickname;
+
+    private String avatar;
+
+    @JsonIgnore
+    private String password;
+
+    private boolean del = false;
+
+    @ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.DETACH})
+    @JoinTable(
+            name = "user_authority",
+            joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id", foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))},
+            inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name", foreignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT))})
+    @BatchSize(size = 20)
+    @ExcelIgnore
+    private Set<Authority> authorities = new HashSet<>();
+
+    private String openId;
+
+    private String sex;
+
+    private String language;
+
+    private String city;
+
+    private String province;
+
+    private String country;
+
+    @Searchable
+    private String phone;
+
+    private String email;
+}

+ 11 - 0
src/main/java/com/izouma/nineth/dto/Captcha.java

@@ -0,0 +1,11 @@
+package com.izouma.nineth.dto;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+
+@Data
+@AllArgsConstructor
+public class Captcha {
+    private String key;
+    private String image;
+}

+ 23 - 0
src/main/java/com/izouma/nineth/dto/MenuDTO.java

@@ -0,0 +1,23 @@
+package com.izouma.nineth.dto;
+
+public interface MenuDTO {
+    Long getId();
+
+    String getName();
+
+    String getPath();
+
+    String getIcon();
+
+    Integer getSort();
+
+    Long getParent();
+
+    Boolean getRoot();
+
+    Boolean getEnabled();
+
+    Boolean getActive();
+
+    String getCategory();
+}

+ 15 - 0
src/main/java/com/izouma/nineth/dto/PageQuery.java

@@ -0,0 +1,15 @@
+package com.izouma.nineth.dto;
+
+import lombok.Data;
+
+import java.util.HashMap;
+import java.util.Map;
+
+@Data
+public class PageQuery {
+    private int                 page  = 0;
+    private int                 size  = 20;
+    private String              sort;
+    private String              search;
+    private Map<String, Object> query = new HashMap<>();
+}

+ 37 - 0
src/main/java/com/izouma/nineth/dto/UserRegister.java

@@ -0,0 +1,37 @@
+package com.izouma.nineth.dto;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.izouma.nineth.security.Authority;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import java.util.HashSet;
+import java.util.Set;
+
+@Data
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonIgnoreProperties(value = {"hibernateLazyInitializer"}, ignoreUnknown = true)
+public class UserRegister {
+
+    private String username;
+
+    private String nickname;
+
+    private String avatar;
+
+    private String password;
+
+    private Set<Authority> authorities = new HashSet<>();
+
+    private String sex;
+
+    private String phone;
+
+    private String email;
+}

+ 354 - 0
src/main/java/com/izouma/nineth/dto/gen/GenCode.java

@@ -0,0 +1,354 @@
+package com.izouma.nineth.dto.gen;
+
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
+
+import java.util.List;
+
+/**
+ * gen_code_model 实体类
+ * Fri May 04 15:57:06 CST 2018  Suo Chen Cheng
+ */
+@JsonAutoDetect
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class GenCode {
+
+    /**
+     * id
+     */
+    private Integer id;
+
+    /**
+     * 表名
+     */
+    private String tableName;
+
+    /**
+     * 类名
+     */
+    private String className;
+
+    /**
+     * 备注
+     */
+    private String remark;
+
+    /**
+     * 是否生成表
+     */
+    private Boolean genTable;
+
+    /**
+     * 是否生成类
+     */
+    private Boolean genClass;
+
+    /**
+     * 是否生成列表页面
+     */
+    private Boolean genList;
+
+    /**
+     * 是否生成表单页面
+     */
+    private Boolean genForm;
+
+    /**
+     * 是否生成路由
+     */
+    private Boolean genRouter;
+
+    /**
+     * 字段表id
+     */
+    private String fieldId;
+
+    /**
+     * java生成路径
+     */
+    private String javaPath;
+
+    /**
+     * vue生成路径
+     */
+    private String viewPath;
+
+    /**
+     * 路由生成路径
+     */
+    private String routerPath;
+
+    /**
+     * resources生成路径
+     */
+    private String resourcesPath;
+
+    /**
+     * 数据库类型:Mysql/SqlServer
+     */
+    private String dataBaseType;
+
+    private List<TableField> fields;    // 表字段
+    private TableField primaryField; //主键字段
+
+    private Boolean readTable;
+
+    /**
+     * 数据库CODE,使用什么数据源S
+     */
+    private String dataSourceCode;
+
+    /**
+     * 生成代码的JSON Str
+     */
+    private String genJson;
+
+    private String searchKey;
+
+    private String delFlag;
+
+    private String typeFlag;
+
+    private List<Subtable> subtables;
+
+    private boolean update;
+
+    private String basePackage;//基础包路径
+
+    private String tablePackage;//对象的包名
+
+    private String genPackage;//子包名
+
+
+    public List<TableField> getFields() {
+        return fields;
+    }
+
+    public void setFields(List<TableField> fields) {
+        this.fields = fields;
+    }
+
+    public TableField getPrimaryField() {
+        return primaryField;
+    }
+
+    public void setPrimaryField(TableField primaryField) {
+        this.primaryField = primaryField;
+    }
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setTableName(String tableName) {
+        this.tableName = tableName;
+    }
+
+    public String getTableName() {
+        return tableName;
+    }
+
+    public void setClassName(String className) {
+        this.className = className;
+    }
+
+    public String getClassName() {
+        return className;
+    }
+
+    public void setRemark(String remark) {
+        this.remark = remark;
+    }
+
+    public String getRemark() {
+        return remark;
+    }
+
+    public void setGenTable(Boolean genTable) {
+        this.genTable = genTable;
+    }
+
+    public Boolean getGenTable() {
+        return genTable;
+    }
+
+    public void setGenClass(Boolean genClass) {
+        this.genClass = genClass;
+    }
+
+    public Boolean getGenClass() {
+        return genClass;
+    }
+
+    public void setGenList(Boolean genList) {
+        this.genList = genList;
+    }
+
+    public Boolean getGenList() {
+        return genList;
+    }
+
+    public void setGenForm(Boolean genForm) {
+        this.genForm = genForm;
+    }
+
+    public Boolean getGenForm() {
+        return genForm;
+    }
+
+    public void setFieldId(String fieldId) {
+        this.fieldId = fieldId;
+    }
+
+    public String getFieldId() {
+        return fieldId;
+    }
+
+    public String getJavaPath() {
+        return javaPath;
+    }
+
+    public void setJavaPath(String javaPath) {
+        this.javaPath = javaPath;
+    }
+
+    public String getViewPath() {
+        return viewPath;
+    }
+
+    public void setViewPath(String viewPath) {
+        this.viewPath = viewPath;
+    }
+
+    public String getDataBaseType() {
+        return dataBaseType;
+    }
+
+    public void setDataBaseType(String dataBaseType) {
+        this.dataBaseType = dataBaseType;
+    }
+
+    public Boolean getReadTable() {
+        return readTable;
+    }
+
+    public void setReadTable(Boolean readTable) {
+        this.readTable = readTable;
+    }
+
+    public String getRouterPath() {
+        return routerPath;
+    }
+
+    public void setRouterPath(String routerPath) {
+        this.routerPath = routerPath;
+    }
+
+    public Boolean getGenRouter() {
+        return genRouter;
+    }
+
+    public void setGenRouter(Boolean genRouter) {
+        this.genRouter = genRouter;
+    }
+
+    public String getDataSourceCode() {
+        return dataSourceCode;
+    }
+
+    public void setDataSourceCode(String dataSourceCode) {
+        this.dataSourceCode = dataSourceCode;
+    }
+
+    public String getGenJson() {
+        return genJson;
+    }
+
+    public void setGenJson(String genJson) {
+        this.genJson = genJson;
+    }
+
+    public String getSearchKey() {
+        return searchKey;
+    }
+
+    public void setSearchKey(String searchKey) {
+        this.searchKey = searchKey;
+    }
+
+    public String getDelFlag() {
+        return delFlag;
+    }
+
+    public void setDelFlag(String delFlag) {
+        this.delFlag = delFlag;
+    }
+
+    public String getTypeFlag() {
+        return typeFlag;
+    }
+
+    public void setTypeFlag(String typeFlag) {
+        this.typeFlag = typeFlag;
+    }
+
+    public List<Subtable> getSubtables() {
+        return subtables;
+    }
+
+    public void setSubtables(List<Subtable> subtables) {
+        this.subtables = subtables;
+    }
+
+    public boolean getUpdate() {
+        return update;
+    }
+
+    public void setUpdate(boolean update) {
+        this.update = update;
+    }
+
+    public String getResourcesPath() {
+        return resourcesPath;
+    }
+
+    public void setResourcesPath(String resourcesPath) {
+        this.resourcesPath = resourcesPath;
+    }
+
+    public boolean isUpdate() {
+        return update;
+    }
+
+    public String getBasePackage() {
+        return basePackage;
+    }
+
+    public void setBasePackage(String basePackage) {
+        this.basePackage = basePackage;
+    }
+
+    public String getTablePackage() {
+        return tablePackage;
+    }
+
+    public void setTablePackage(String tablePackage) {
+        this.tablePackage = tablePackage;
+    }
+
+    public String getGenPackage() {
+        return genPackage;
+    }
+
+    public void setGenPackage(String genPackage) {
+        this.genPackage = genPackage;
+    }
+}
+

+ 55 - 0
src/main/java/com/izouma/nineth/dto/gen/Subtable.java

@@ -0,0 +1,55 @@
+package com.izouma.nineth.dto.gen;
+
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.JsonInclude;
+
+/**
+ * table_field 实体类
+ * Fri May 04 13:38:24 CST 2018  Suo Chen Cheng
+ */
+@JsonAutoDetect
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class Subtable {
+
+    private String name;
+
+    private String column;
+
+    private String subColumn;
+
+    private String subCode;
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getColumn() {
+        return column;
+    }
+
+    public void setColumn(String column) {
+        this.column = column;
+    }
+
+    public String getSubColumn() {
+        return subColumn;
+    }
+
+    public void setSubColumn(String subColumn) {
+        this.subColumn = subColumn;
+    }
+
+    public String getSubCode() {
+        return subCode;
+    }
+
+    public void setSubCode(String subCode) {
+        this.subCode = subCode;
+    }
+}
+

+ 163 - 0
src/main/java/com/izouma/nineth/dto/gen/TableField.java

@@ -0,0 +1,163 @@
+package com.izouma.nineth.dto.gen;
+
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import lombok.Data;
+
+@Data
+@JsonAutoDetect
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class TableField {
+
+    /**
+     * id
+     */
+    private Integer id;
+
+    /**
+     * 字段名
+     */
+    private String name;
+
+    /**
+     * 驼峰式名字
+     */
+    private String modelName;
+
+    /**
+     * 备注
+     */
+    private String remark;
+
+    /**
+     * 数据类型(数据库)
+     */
+    private String jdbcType;
+
+    /**
+     * java类型
+     */
+    private String javaType;
+
+    /**
+     * 长度
+     */
+    private Integer length;
+
+    /**
+     * 小数长度
+     */
+    private Integer decimalPlaces;
+
+    /**
+     * 默认值
+     */
+    private String defaultValue;
+
+    /**
+     * 非空
+     */
+    private Boolean notNull;
+
+    /**
+     * 主键
+     */
+    private Boolean primaryKey;
+
+    /**
+     * 自增
+     */
+    private Boolean autoIncrease;
+
+    /**
+     * 在列表中显示
+     */
+    private Boolean showInList;
+
+    /**
+     * 在表单中显示
+     */
+    private Boolean showInForm;
+
+    /**
+     * 可以排序
+     */
+    private Boolean sortable;
+
+    /**
+     * 表单类型
+     */
+    private String formType;
+
+    /**
+     * 搜索方式
+     */
+    private String searchMethod;
+
+    /**
+     * 表单必填
+     */
+    private Boolean required;
+
+    /**
+     * 表单验证
+     */
+    private Boolean validate;
+
+    /**
+     * 最短长度
+     */
+    private Integer minLength;
+
+    /**
+     * 最大长度
+     */
+    private Integer maxLength;
+
+    /**
+     * 最小值
+     */
+    private String min;
+
+    /**
+     * 最大值
+     */
+    private String max;
+
+    /**
+     * 验证类型
+     */
+    private String validatorType;
+
+    /**
+     * xml里jdbcType
+     */
+    private String sqlType;
+
+    /**
+     * 下拉框类型 1 枚举, 2 接口, 3 读表
+     */
+    private String apiFlag;
+
+    /**
+     * 接口方法/表名
+     */
+    private String optionsMethod;
+
+    /**
+     * 选项值,在枚举是用该值解析
+     */
+    private String optionsValue;
+
+
+    /**
+     * 显示值
+     */
+    private String optionsLabel;
+
+
+}
+

+ 16 - 0
src/main/java/com/izouma/nineth/enums/AuthorityName.java

@@ -0,0 +1,16 @@
+package com.izouma.nineth.enums;
+
+public enum AuthorityName {
+    ROLE_USER("普通用户"),
+    ROLE_DEV("开发者"),
+    ROLE_ADMIN("管理员");
+    private final String description;
+
+    AuthorityName(String description) {
+        this.description = description;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+}

+ 18 - 0
src/main/java/com/izouma/nineth/enums/DistrictLevel.java

@@ -0,0 +1,18 @@
+package com.izouma.nineth.enums;
+
+public enum DistrictLevel {
+    PROVINCE(1),
+    CITY(2),
+    DISTRICT(3),
+    STREET(4),
+    NONE(5);
+    private final int value;
+
+    DistrictLevel(int value) {
+        this.value = value;
+    }
+
+    public int getValue() {
+        return value;
+    }
+}

+ 7 - 0
src/main/java/com/izouma/nineth/exception/AuthenticationException.java

@@ -0,0 +1,7 @@
+package com.izouma.nineth.exception;
+
+public class AuthenticationException extends RuntimeException {
+    public AuthenticationException(String message, Throwable cause) {
+        super(message, cause);
+    }
+}

+ 45 - 0
src/main/java/com/izouma/nineth/exception/BusinessException.java

@@ -0,0 +1,45 @@
+package com.izouma.nineth.exception;
+
+import java.util.function.Supplier;
+
+public class BusinessException extends RuntimeException implements Supplier<BusinessException> {
+    private static final long serialVersionUID = 3779880207424189309L;
+
+    private Integer code = -1;
+    private String  error;
+
+    public BusinessException(String error) {
+        super();
+        this.error = error;
+    }
+
+    public BusinessException(String error, String message) {
+        super(message);
+        this.error = error;
+    }
+
+    public BusinessException(String error, String message, Integer code) {
+        super(message);
+        this.code = code;
+        this.error = error;
+    }
+
+    public BusinessException(String error, int code) {
+        super();
+        this.error = error;
+        this.code = code;
+    }
+
+    @Override
+    public BusinessException get() {
+        return this;
+    }
+
+    public Integer getCode() {
+        return code;
+    }
+
+    public String getError() {
+        return error;
+    }
+}

+ 149 - 0
src/main/java/com/izouma/nineth/exception/GlobalExceptionHandler.java

@@ -0,0 +1,149 @@
+package com.izouma.nineth.exception;
+
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpStatus;
+import org.springframework.transaction.TransactionSystemException;
+import org.springframework.validation.BindException;
+import org.springframework.validation.FieldError;
+import org.springframework.validation.ObjectError;
+import org.springframework.web.bind.MethodArgumentNotValidException;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.ResponseStatus;
+import org.springframework.web.servlet.ModelAndView;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.validation.ConstraintViolation;
+import javax.validation.ConstraintViolationException;
+import javax.validation.Path;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+@ControllerAdvice
+@Slf4j
+public class GlobalExceptionHandler {
+
+    @ExceptionHandler(value = BusinessException.class)
+    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
+    @ResponseBody
+    public Map<String, Object> serviceExceptionHandler(BusinessException e) {
+        Map<String, Object> map = new HashMap<>();
+        map.put("error", e.getError());
+        map.put("message", e.getMessage());
+        map.put("code", -1);
+        return map;
+    }
+
+    @ExceptionHandler({AuthenticationException.class})
+    @ResponseStatus(HttpStatus.UNAUTHORIZED)
+    @ResponseBody
+    public Map<String, Object> handleAuthenticationException(AuthenticationException e) {
+        Map<String, Object> map = new HashMap<>();
+        map.put("error", e.getMessage());
+        map.put("code", -1);
+        return map;
+    }
+
+    @ExceptionHandler(value = TransactionSystemException.class)
+    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
+    @ResponseBody
+    public Map<String, Object> serviceExceptionHandler(TransactionSystemException e) {
+        String message = e.getMessage();
+        try {
+            if (e.getCause().getCause() instanceof ConstraintViolationException) {
+                ConstraintViolationException violationException = (ConstraintViolationException) e.getCause()
+                        .getCause();
+                message = violationException.getConstraintViolations().stream()
+                        .map(constraintViolation -> constraintViolation.getPropertyPath() + constraintViolation.getMessage())
+                        .collect(Collectors.joining(","));
+                log.error(message);
+            }
+        } catch (Exception ignore) {
+        }
+        Map<String, Object> map = new HashMap<>();
+        map.put("error", message);
+        map.put("code", -1);
+        return map;
+    }
+
+    @ExceptionHandler(value = Exception.class)
+    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
+    @ResponseBody
+    public Object serviceExceptionHandler(Exception e, HttpServletRequest request) {
+        log.error(e.getMessage(), e);
+        if (request.getHeader("Accept").contains("text/html")) {
+            ModelAndView modelAndView = new ModelAndView("commons/500");
+            StringWriter out = new StringWriter();
+            PrintWriter writer = new PrintWriter(out);
+            e.printStackTrace(writer);
+            String trace = out.toString();
+            trace = trace.replaceAll("\n", "<br>");
+            modelAndView.addObject("trace", trace);
+            return modelAndView;
+        } else {
+            Map<String, Object> map = new HashMap<>();
+            map.put("error", e.getMessage());
+            map.put("code", -1);
+            return map;
+        }
+    }
+
+    @ExceptionHandler({BindException.class, ConstraintViolationException.class, MethodArgumentNotValidException.class})
+    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
+    @ResponseBody
+    public Map<String, Object> validateExceptionHandler(Exception e, HttpServletRequest request) {
+        log.error("请求:{}发生异常:{}", request.getRequestURI(), e);
+
+        // 错误信息
+        StringBuilder sb = new StringBuilder("参数校验失败:");
+        // 错误信息map
+        Map<String, String> error = new HashMap<>();
+
+        String msg = "";
+        if (!(e instanceof BindException) && !(e instanceof MethodArgumentNotValidException)) {
+            for (ConstraintViolation cv : ((ConstraintViolationException) e).getConstraintViolations()) {
+                msg = cv.getMessage();
+                sb.append(msg).append(";");
+
+                Iterator<Path.Node> it = cv.getPropertyPath().iterator();
+                Path.Node last = null;
+                while (it.hasNext()) {
+                    last = (Path.Node) it.next();
+                }
+                /*for(last = null; it.hasNext(); last = (Path.Node)it.next()) {
+                }*/
+                error.put(last != null ? last.getName() : "", msg);
+            }
+        } else {
+            List<ObjectError> allErrors = null;
+            if (e instanceof BindException) {
+                allErrors = ((BindException) e).getAllErrors();
+            } else {
+                allErrors = ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors();
+            }
+            // 拼接错误信息
+            for (ObjectError oe : allErrors) {
+                msg = oe.getDefaultMessage();
+                sb.append(msg).append(";");
+                if (oe instanceof FieldError) {
+                    error.put(((FieldError) oe).getField(), msg);
+                } else {
+                    error.put(oe.getObjectName(), msg);
+                }
+            }
+        }
+
+        Map<String, Object> map = new HashMap<>();
+        map.put("error", "参数校验失败");
+        map.put("message", sb);
+        map.put("code", -1);
+        log.error(e.getMessage());
+        return map;
+    }
+}

+ 23 - 0
src/main/java/com/izouma/nineth/mpHandler/LogHandler.java

@@ -0,0 +1,23 @@
+package com.izouma.nineth.mpHandler;
+
+import lombok.extern.slf4j.Slf4j;
+import me.chanjar.weixin.common.session.WxSessionManager;
+import me.chanjar.weixin.mp.api.WxMpMessageHandler;
+import me.chanjar.weixin.mp.api.WxMpService;
+import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
+import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
+import org.springframework.stereotype.Component;
+
+import java.util.Map;
+
+@Component
+@Slf4j
+public class LogHandler implements WxMpMessageHandler {
+    @Override
+    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
+                                    Map<String, Object> context, WxMpService wxMpService,
+                                    WxSessionManager sessionManager) {
+        log.info("\n接收到请求消息,内容:{}", wxMessage);
+        return null;
+    }
+}

+ 7 - 0
src/main/java/com/izouma/nineth/repo/AuthorityRepo.java

@@ -0,0 +1,7 @@
+package com.izouma.nineth.repo;
+
+import com.izouma.nineth.security.Authority;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface AuthorityRepo extends JpaRepository<Authority, String> {
+}

+ 8 - 0
src/main/java/com/izouma/nineth/repo/DistrictRepo.java

@@ -0,0 +1,8 @@
+package com.izouma.nineth.repo;
+
+import com.izouma.nineth.domain.District;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+public interface DistrictRepo extends JpaRepository<District, Long>, JpaSpecificationExecutor<District> {
+}

+ 8 - 0
src/main/java/com/izouma/nineth/repo/ExceptionLogRepo.java

@@ -0,0 +1,8 @@
+package com.izouma.nineth.repo;
+
+import com.izouma.nineth.domain.ExceptionLog;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+public interface ExceptionLogRepo extends JpaRepository<ExceptionLog, Long>, JpaSpecificationExecutor<ExceptionLog> {
+}

+ 35 - 0
src/main/java/com/izouma/nineth/repo/MenuRepo.java

@@ -0,0 +1,35 @@
+package com.izouma.nineth.repo;
+
+import com.izouma.nineth.domain.Menu;
+import com.izouma.nineth.dto.MenuDTO;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.jpa.repository.Modifying;
+import org.springframework.data.jpa.repository.Query;
+
+import javax.transaction.Transactional;
+import java.util.List;
+
+public interface MenuRepo extends JpaRepository<Menu, Long>, JpaSpecificationExecutor<Menu> {
+    @Query(nativeQuery = true, value = "SELECT ifnull(max(sort + 1),1) FROM menu")
+    int nextSort();
+
+    @Query("select m.category from Menu m group by m.category")
+    List<String> categories();
+
+    @Transactional
+    @Modifying
+    @Query(value = "delete from menu_authority where authority = ?1", nativeQuery = true)
+    int clearAuthority(String name);
+
+    @Transactional
+    @Modifying
+    @Query(value = "insert into menu_authority value (?2, ?1)", nativeQuery = true)
+    int saveAuthority(String name, Long id);
+
+    @Query(value = "select * " +
+            "from menu " +
+            "    join menu_authority on menu.id = menu_authority.menu_id " +
+            "where authority in ?1 and active = 1 group by id", nativeQuery = true)
+    List<MenuDTO> authorityMenus(Iterable<String> authority);
+}

+ 8 - 0
src/main/java/com/izouma/nineth/repo/OperationLogRepo.java

@@ -0,0 +1,8 @@
+package com.izouma.nineth.repo;
+
+import com.izouma.nineth.domain.OperationLog;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+public interface OperationLogRepo extends JpaRepository<OperationLog, Long>, JpaSpecificationExecutor<OperationLog> {
+}

+ 24 - 0
src/main/java/com/izouma/nineth/repo/SmsRecordRepo.java

@@ -0,0 +1,24 @@
+package com.izouma.nineth.repo;
+
+import com.izouma.nineth.domain.SmsRecord;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Modifying;
+import org.springframework.data.jpa.repository.Query;
+
+import javax.transaction.Transactional;
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.Optional;
+
+public interface SmsRecordRepo extends JpaRepository<SmsRecord, Long> {
+    Optional<SmsRecord> findLastBySessionIdAndExpiresAtAfterAndExpiredFalse(String sessionId, LocalDateTime time);
+
+    Optional<SmsRecord> findLastByPhoneAndExpiresAtAfterAndExpiredFalse(String phone, LocalDateTime time);
+
+    List<SmsRecord> findAllByPhoneAndExpiresAtAfterAndExpiredFalse(String phone, LocalDateTime time);
+
+    @Query("update SmsRecord s set s.expired = true where s.phone = ?1")
+    @Modifying
+    @Transactional
+    void expire(String phone);
+}

+ 11 - 0
src/main/java/com/izouma/nineth/repo/SysConfigRepo.java

@@ -0,0 +1,11 @@
+package com.izouma.nineth.repo;
+
+import com.izouma.nineth.domain.SysConfig;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+import java.util.Optional;
+
+public interface SysConfigRepo extends JpaRepository<SysConfig, String>, JpaSpecificationExecutor<SysConfig> {
+    Optional<SysConfig> findByName(String name);
+}

+ 16 - 0
src/main/java/com/izouma/nineth/repo/TestClassRepo.java

@@ -0,0 +1,16 @@
+package com.izouma.nineth.repo;
+
+import com.izouma.nineth.domain.TestClass;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.jpa.repository.Modifying;
+import org.springframework.data.jpa.repository.Query;
+
+import javax.transaction.Transactional;
+
+public interface TestClassRepo extends JpaRepository<TestClass, Long>, JpaSpecificationExecutor<TestClass> {
+    @Query("update TestClass t set t.del = true where t.id = ?1")
+    @Modifying
+    @Transactional
+    void softDelete(Long id);
+}

+ 26 - 0
src/main/java/com/izouma/nineth/repo/UserRepo.java

@@ -0,0 +1,26 @@
+package com.izouma.nineth.repo;
+
+import com.izouma.nineth.domain.User;
+import com.izouma.nineth.security.Authority;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.jpa.repository.Modifying;
+import org.springframework.data.jpa.repository.Query;
+
+import javax.transaction.Transactional;
+import java.util.List;
+
+public interface UserRepo extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
+    @Transactional
+    @Modifying
+    @Query("update User u set u.del = true where u.id = ?1")
+    void softDelete(Long id);
+
+    User findByUsernameAndDelFalse(String username);
+
+    List<User> findAllByAuthoritiesContainsAndDelFalse(Authority authority);
+
+    User findByOpenIdAndDelFalse(String openId);
+
+    User findByPhoneAndDelFalse(String phone);
+}

+ 64 - 0
src/main/java/com/izouma/nineth/security/Authority.java

@@ -0,0 +1,64 @@
+package com.izouma.nineth.security;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.izouma.nineth.enums.AuthorityName;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import javax.persistence.*;
+import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Size;
+import java.io.Serializable;
+import java.util.Objects;
+
+@Entity
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+@Builder
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class Authority implements Serializable {
+
+    public static Authority get(AuthorityName name) {
+        return new Authority(name.name(), name.getDescription());
+    }
+
+    @Id
+    @Size(max = 50)
+    @NotNull
+    @Column(length = 50)
+    private String name;
+
+    @Column(length = 50)
+    @Size(max = 50)
+    @NotNull
+    private String description;
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+
+        Authority authority = (Authority) o;
+
+        return Objects.equals(name, authority.name);
+    }
+
+    @Override
+    public int hashCode() {
+        return name != null ? name.hashCode() : 0;
+    }
+
+    @Override
+    public String toString() {
+        return "Authority{" +
+                "name='" + name + '\'' +
+                "}";
+    }
+}

+ 25 - 0
src/main/java/com/izouma/nineth/security/JwtAuthenticationEntryPoint.java

@@ -0,0 +1,25 @@
+package com.izouma.nineth.security;
+
+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.Serializable;
+
+@Component
+public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
+
+    private static final long serialVersionUID = -8970718410437077606L;
+
+    @Override
+    public void commence(HttpServletRequest request,
+                         HttpServletResponse response,
+                         AuthenticationException authException) throws IOException {
+        // This is invoked when user tries to access a secured REST resource without supplying any credentials
+        // We should just send a 401 Unauthorized response because there is no 'login page' to redirect to
+        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "授权失败");
+    }
+}

+ 87 - 0
src/main/java/com/izouma/nineth/security/JwtAuthorizationTokenFilter.java

@@ -0,0 +1,87 @@
+package com.izouma.nineth.security;
+
+import io.jsonwebtoken.ExpiredJwtException;
+import io.jsonwebtoken.SignatureException;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
+import org.springframework.stereotype.Component;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+@Component
+@Slf4j
+public class JwtAuthorizationTokenFilter extends OncePerRequestFilter {
+
+    private final UserDetailsService userDetailsService;
+    private final JwtTokenUtil       jwtTokenUtil;
+    private final String             tokenHeader;
+
+    public JwtAuthorizationTokenFilter(@Qualifier("jwtUserDetailsService") UserDetailsService userDetailsService, JwtTokenUtil jwtTokenUtil, @Value("${jwt.header}") String tokenHeader) {
+        this.userDetailsService = userDetailsService;
+        this.jwtTokenUtil = jwtTokenUtil;
+        this.tokenHeader = tokenHeader;
+    }
+
+    @Override
+    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
+        log.debug("processing authentication for '{}'", request.getRequestURL());
+
+        final String requestHeader = request.getHeader(this.tokenHeader);
+
+        String username = null;
+        String authToken = null;
+        if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
+            authToken = requestHeader.substring(7);
+            try {
+                username = jwtTokenUtil.getUsernameFromToken(authToken);
+            } catch (IllegalArgumentException e) {
+                log.error("an error occurred during getting username from token", e);
+            } catch (ExpiredJwtException e) {
+                log.warn("the token is expired and not valid anymore", e);
+            } catch (SignatureException e) {
+                log.error(e.getMessage());
+            }
+        } else {
+            log.warn("couldn't find bearer string, will ignore the header");
+        }
+
+        log.debug("checking authentication for user '{}'", username);
+        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
+            log.debug("security context was null, so authorizing user");
+
+            // It is not compelling necessary to load the use details from the database. You could also store the information
+            // in the token and read it from it. It's up to you ;)            
+            UserDetails userDetails;
+            try {
+                userDetails = userDetailsService.loadUserByUsername(username);
+            } catch (Exception e) {
+                //response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
+                chain.doFilter(request, response);
+                return;
+            }
+
+
+            // For simple validation it is completely sufficient to just check the token integrity. You don't have to call
+            // the database compellingly. Again it's up to you ;)
+            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
+                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
+                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
+                log.info("authorized user '{}', setting security context", username);
+                SecurityContextHolder.getContext().setAuthentication(authentication);
+            }
+        }
+
+        chain.doFilter(request, response);
+    }
+}

+ 12 - 0
src/main/java/com/izouma/nineth/security/JwtConfig.java

@@ -0,0 +1,12 @@
+package com.izouma.nineth.security;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+@Data
+@ConfigurationProperties(prefix = "jwt")
+public class JwtConfig {
+    private String secret;
+    private String header;
+    private Long   expiration;
+}

+ 125 - 0
src/main/java/com/izouma/nineth/security/JwtTokenUtil.java

@@ -0,0 +1,125 @@
+package com.izouma.nineth.security;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import io.jsonwebtoken.Claims;
+import io.jsonwebtoken.Clock;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.SignatureAlgorithm;
+import io.jsonwebtoken.impl.DefaultClock;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.stereotype.Component;
+
+import java.io.Serializable;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.function.Function;
+
+@Component
+public class JwtTokenUtil implements Serializable {
+
+    private static final long serialVersionUID = -3301605591108950415L;
+
+    static final String CLAIM_KEY_USERNAME = "sub";
+    static final String CLAIM_KEY_CREATED  = "iat";
+
+    @SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "It's okay here")
+    private Clock     clock = DefaultClock.INSTANCE;
+    private JwtConfig jwtConfig;
+
+    public JwtTokenUtil(JwtConfig jwtConfig) {
+        this.jwtConfig = jwtConfig;
+    }
+
+    public String getUsernameFromToken(String token) {
+        return getClaimFromToken(token, Claims::getSubject);
+    }
+
+    public Date getIssuedAtDateFromToken(String token) {
+        return getClaimFromToken(token, Claims::getIssuedAt);
+    }
+
+    public Date getExpirationDateFromToken(String token) {
+        return getClaimFromToken(token, Claims::getExpiration);
+    }
+
+    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
+        final Claims claims = getAllClaimsFromToken(token);
+        return claimsResolver.apply(claims);
+    }
+
+    private Claims getAllClaimsFromToken(String token) {
+        return Jwts.parser()
+                .setSigningKey(jwtConfig.getSecret())
+                .parseClaimsJws(token)
+                .getBody();
+    }
+
+    private Boolean isTokenExpired(String token) {
+        final Date expiration = getExpirationDateFromToken(token);
+        return expiration.before(clock.now());
+    }
+
+    private Boolean isCreatedBeforeLastPasswordReset(Date created, Date lastPasswordReset) {
+        return (lastPasswordReset != null && created.before(lastPasswordReset));
+    }
+
+    private Boolean ignoreTokenExpiration(String token) {
+        // here you specify tokens, for that the expiration is ignored
+        return false;
+    }
+
+    public String generateToken(UserDetails userDetails) {
+        Map<String, Object> claims = new HashMap<>();
+        return doGenerateToken(claims, userDetails.getUsername());
+    }
+
+    private String doGenerateToken(Map<String, Object> claims, String subject) {
+        final Date createdDate = clock.now();
+        final Date expirationDate = calculateExpirationDate(createdDate);
+
+        return Jwts.builder()
+                .setClaims(claims)
+                .setSubject(subject)
+                .setIssuedAt(createdDate)
+                .setExpiration(expirationDate)
+                .signWith(SignatureAlgorithm.HS512, jwtConfig.getSecret())
+                .compact();
+    }
+
+    public Boolean canTokenBeRefreshed(String token, Date lastPasswordReset) {
+        final Date created = getIssuedAtDateFromToken(token);
+        return !isCreatedBeforeLastPasswordReset(created, lastPasswordReset)
+                && (!isTokenExpired(token) || ignoreTokenExpiration(token));
+    }
+
+    public String refreshToken(String token) {
+        final Date createdDate = clock.now();
+        final Date expirationDate = calculateExpirationDate(createdDate);
+
+        final Claims claims = getAllClaimsFromToken(token);
+        claims.setIssuedAt(createdDate);
+        claims.setExpiration(expirationDate);
+
+        return Jwts.builder()
+                .setClaims(claims)
+                .signWith(SignatureAlgorithm.HS512, jwtConfig.getSecret())
+                .compact();
+    }
+
+    public Boolean validateToken(String token, UserDetails userDetails) {
+        JwtUser user = (JwtUser) userDetails;
+        final String username = getUsernameFromToken(token);
+        final Date created = getIssuedAtDateFromToken(token);
+        //final Date expiration = getExpirationDateFromToken(token);
+        return (
+                username.equals(user.getUsername())
+                        && !isTokenExpired(token)
+                        && !isCreatedBeforeLastPasswordReset(created, user.getLastPasswordResetDate())
+        );
+    }
+
+    private Date calculateExpirationDate(Date createdDate) {
+        return new Date(createdDate.getTime() + jwtConfig.getExpiration() * 1000);
+    }
+}

+ 81 - 0
src/main/java/com/izouma/nineth/security/JwtUser.java

@@ -0,0 +1,81 @@
+package com.izouma.nineth.security;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.izouma.nineth.domain.User;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.userdetails.UserDetails;
+
+import java.time.ZoneId;
+import java.util.Collection;
+import java.util.Date;
+
+/**
+ * Created by stephan on 20.03.16.
+ */
+public class JwtUser implements UserDetails {
+
+    private static final long serialVersionUID = 5803985158027956021L;
+
+    private final Collection<? extends GrantedAuthority> authorities;
+    private final Date                                   lastPasswordResetDate;
+    private       User                                   user;
+
+    public JwtUser(User user, Collection<? extends GrantedAuthority> authorities) {
+        this.authorities = authorities;
+        this.lastPasswordResetDate = Date.from(user.getCreatedAt().atZone(ZoneId.systemDefault()).toInstant());
+        this.user = user;
+    }
+
+    @JsonIgnore
+    public Long getId() {
+        return user.getId();
+    }
+
+    @Override
+    public String getUsername() {
+        return user.getUsername();
+    }
+
+    @JsonIgnore
+    @Override
+    public boolean isAccountNonExpired() {
+        return true;
+    }
+
+    @JsonIgnore
+    @Override
+    public boolean isAccountNonLocked() {
+        return true;
+    }
+
+    @JsonIgnore
+    @Override
+    public boolean isCredentialsNonExpired() {
+        return true;
+    }
+
+    @JsonIgnore
+    @Override
+    public String getPassword() {
+        return user.getPassword();
+    }
+
+    @Override
+    public Collection<? extends GrantedAuthority> getAuthorities() {
+        return authorities;
+    }
+
+    @Override
+    public boolean isEnabled() {
+        return !user.isDel();
+    }
+
+    @JsonIgnore
+    public Date getLastPasswordResetDate() {
+        return lastPasswordResetDate;
+    }
+
+    public User getUser() {
+        return user;
+    }
+}

+ 26 - 0
src/main/java/com/izouma/nineth/security/JwtUserDetailsService.java

@@ -0,0 +1,26 @@
+package com.izouma.nineth.security;
+
+import com.izouma.nineth.domain.User;
+import com.izouma.nineth.repo.UserRepo;
+import lombok.AllArgsConstructor;
+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;
+
+@AllArgsConstructor
+@Service("jwtUserDetailsService")
+public class JwtUserDetailsService implements UserDetailsService {
+    private UserRepo userRepo;
+
+    @Override
+    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
+        User user = userRepo.findByUsernameAndDelFalse(username);
+
+        if (user == null) {
+            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
+        } else {
+            return JwtUserFactory.create(user);
+        }
+    }
+}

+ 28 - 0
src/main/java/com/izouma/nineth/security/JwtUserFactory.java

@@ -0,0 +1,28 @@
+package com.izouma.nineth.security;
+
+import com.izouma.nineth.domain.User;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public final class JwtUserFactory {
+
+    private JwtUserFactory() {
+    }
+
+    public static JwtUser create(User user) {
+        return new JwtUser(user, mapToGrantedAuthorities(user.getAuthorities()));
+    }
+
+    private static List<GrantedAuthority> mapToGrantedAuthorities(Set<Authority> authorities) {
+        if (authorities != null) {
+            return authorities.stream()
+                              .map(authority -> new SimpleGrantedAuthority(authority.getName()))
+                              .collect(Collectors.toList());
+        }
+        return null;
+    }
+}

+ 110 - 0
src/main/java/com/izouma/nineth/security/WebSecurityConfig.java

@@ -0,0 +1,110 @@
+package com.izouma.nineth.security;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.http.HttpMethod;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
+import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.builders.WebSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.config.http.SessionCreationPolicy;
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
+
+@EnableWebSecurity
+@EnableGlobalMethodSecurity(prePostEnabled = true)
+@EnableConfigurationProperties({JwtConfig.class})
+public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
+
+    @Autowired
+    private JwtAuthenticationEntryPoint unauthorizedHandler;
+
+    @Autowired
+    private JwtUserDetailsService jwtUserDetailsService;
+
+    // Custom JWT based security filter
+    @Autowired
+    JwtAuthorizationTokenFilter authenticationTokenFilter;
+
+    @Value("${jwt.header}")
+    private String tokenHeader;
+
+    @Autowired
+    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
+        auth.userDetailsService(jwtUserDetailsService)
+                .passwordEncoder(passwordEncoderBean());
+    }
+
+    @Bean
+    public PasswordEncoder passwordEncoderBean() {
+        return new BCryptPasswordEncoder();
+    }
+
+    @Bean
+    @Override
+    public AuthenticationManager authenticationManagerBean() throws Exception {
+        return super.authenticationManagerBean();
+    }
+
+    @Override
+    protected void configure(HttpSecurity httpSecurity) throws Exception {
+        // We don't need CSRF for this example
+        httpSecurity.csrf().disable()
+                .cors().and()
+                // dont authenticate this particular request
+                .authorizeRequests()
+                //swagger-ui放行路径
+                .antMatchers("/v2/api-docs", "/swagger-ui.html", "/swagger-resources/**", "/webjars/**").permitAll()
+                .antMatchers("/user/register").permitAll()
+                .antMatchers("/upload/**").permitAll()
+                .antMatchers("/files/**").permitAll()
+                .antMatchers("/static/**").permitAll()
+                .antMatchers("/auth/**").permitAll()
+                .antMatchers("/captcha/**").permitAll()
+                .antMatchers("/admin/**").permitAll()
+                .antMatchers("/systemVariable/all").permitAll()
+                .antMatchers("/**/excel").permitAll()
+                .antMatchers("/wx/**").permitAll()
+                .antMatchers("/sms/sendVerify").permitAll()
+                .antMatchers("/error").permitAll()
+                .antMatchers("/401").permitAll()
+                .antMatchers("/404").permitAll()
+                .antMatchers("/500").permitAll()
+                .antMatchers("/MP_verify*").permitAll()
+                // all other requests need to be authenticated
+                .anyRequest().authenticated().and()
+                // make sure we use stateless session; session won't be used to
+                // store user's state.
+                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
+                .and().sessionManagement()
+                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
+        // Add a filter to validate the tokens with every request
+        httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
+    }
+
+    @Override
+    public void configure(WebSecurity web) throws Exception {
+        // AuthenticationTokenFilter will ignore the below paths
+        web.ignoring()
+                .antMatchers("/auth/**")
+
+                // allow anonymous resource requests
+                .and()
+                .ignoring()
+                .antMatchers(
+                        HttpMethod.GET,
+                        "/",
+                        "/*.html",
+                        "/**/favicon.ico",
+                        "/**/*.html",
+                        "/**/*.css",
+                        "/**/*.js"
+                );
+    }
+}

+ 47 - 0
src/main/java/com/izouma/nineth/service/CaptchaService.java

@@ -0,0 +1,47 @@
+package com.izouma.nineth.service;
+
+import com.izouma.nineth.dto.Captcha;
+import com.wf.captcha.SpecCaptcha;
+import lombok.AllArgsConstructor;
+import org.apache.commons.lang3.StringUtils;
+import org.ehcache.UserManagedCache;
+import org.ehcache.config.builders.ExpiryPolicyBuilder;
+import org.ehcache.config.builders.UserManagedCacheBuilder;
+import org.springframework.stereotype.Service;
+
+import java.awt.*;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.UUID;
+
+@Service
+@AllArgsConstructor
+public class CaptchaService {
+    private final UserManagedCache<String, String> captchaCache =
+            UserManagedCacheBuilder.newUserManagedCacheBuilder(String.class, String.class)
+                    .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMinutes(10)))
+                    .build(true);
+
+    public Captcha gen() throws IOException, FontFormatException {
+        String key = UUID.randomUUID().toString();
+        SpecCaptcha specCaptcha = new SpecCaptcha(90 * 2, 32 * 2, 5);
+        specCaptcha.setFont(com.wf.captcha.base.Captcha.FONT_7, 24 * 2);
+        String code = specCaptcha.text().toLowerCase();
+        String image = specCaptcha.toBase64();
+        captchaCache.put(key, code);
+        return new Captcha(key, image);
+    }
+
+    public boolean verify(String key, String code) {
+        if (StringUtils.isBlank(key) || StringUtils.isBlank(code)) {
+            return false;
+        }
+        code = code.toLowerCase();
+        boolean verify = false;
+        String trueCode = captchaCache.get(key);
+        if (StringUtils.isNotBlank(trueCode) && trueCode.equals(code)) {
+            verify = true;
+        }
+        return verify;
+    }
+}

+ 121 - 0
src/main/java/com/izouma/nineth/service/DistrictService.java

@@ -0,0 +1,121 @@
+package com.izouma.nineth.service;
+
+import com.alibaba.fastjson.JSON;
+import com.github.kevinsawicki.http.HttpRequest;
+import com.izouma.nineth.domain.District;
+import com.izouma.nineth.enums.DistrictLevel;
+import com.izouma.nineth.repo.DistrictRepo;
+import com.izouma.nineth.utils.amap.DistrictsItem;
+import com.izouma.nineth.utils.amap.QueryDistrictResponse;
+import lombok.AllArgsConstructor;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.data.jpa.domain.Specification;
+import org.springframework.stereotype.Service;
+
+import javax.persistence.criteria.Predicate;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+@Service
+@AllArgsConstructor
+public class DistrictService {
+
+    private final DistrictRepo districtRepo;
+
+    public List<District> get(DistrictLevel level, DistrictLevel maxLevel, Long parent) {
+        return districtRepo.findAll((Specification<District>) (root, criteriaQuery, criteriaBuilder) -> {
+            List<Predicate> predicates = new ArrayList<>();
+            if (level != null) {
+                predicates.add(criteriaBuilder.equal(root.get("level"), level));
+            }
+            if (parent != null) {
+                predicates.add(criteriaBuilder.equal(root.get("parent"), parent));
+            }
+            if (maxLevel != null) {
+                List<DistrictLevel> list = Arrays.stream(DistrictLevel.values())
+                        .filter(l -> l.getValue() <= maxLevel.getValue())
+                        .collect(Collectors.toList());
+                if (list.isEmpty()) {
+                    predicates.add(criteriaBuilder.equal(root.get("level"), DistrictLevel.NONE));
+                } else {
+                    predicates.add(root.get("level").in(list));
+                }
+            }
+            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
+        }).stream().peek(district -> {
+            if (maxLevel != null) {
+                int childCount = 0;
+                switch (maxLevel) {
+                    case PROVINCE:
+                        break;
+                    case CITY:
+                        childCount = district.getCityCount();
+                        break;
+                    case DISTRICT:
+                        childCount = district.getCityCount() + district.getDistrictCount();
+                        break;
+                    case STREET:
+                        childCount = district.getCityCount() + district.getDistrictCount() + district.getStreetCount();
+                        break;
+                }
+                district.setLeaf(childCount == 0);
+            } else {
+                district.setLeaf(district.getChildCount() == 0);
+            }
+        }).collect(Collectors.toList());
+    }
+
+    public void sync() {
+        QueryDistrictResponse response = JSON.parseObject(HttpRequest.get("https://restapi.amap.com/v3/config/district?key=3d59fb422c5c13af59bf82a8b6f3ad54&subdistrict=4")
+                .body(), QueryDistrictResponse.class);
+        response.getDistricts().get(0).getDistricts().stream().parallel().forEach(item -> saveDistrict(item, null));
+    }
+
+    private void saveDistrict(DistrictsItem item, Long parentId) {
+        District district = District.builder()
+                .id(Long.parseLong(item.getAdcode()))
+                .name(item.getName())
+                .parent(parentId)
+                .level(DistrictLevel.valueOf(item.getLevel().toUpperCase()))
+                .build();
+        if (district.getLevel() == DistrictLevel.STREET) {
+            district.setId(Long.parseLong(district.getId() + String.format("%02d", item.getIdx())));
+        }
+        if (StringUtils.isNotBlank(item.getCenter())) {
+            String[] arr = item.getCenter().split(",");
+            district.setLng(Double.parseDouble(arr[0]));
+            district.setLat(Double.parseDouble(arr[1]));
+        }
+        if (item.getCitycode() != null && item.getCitycode() instanceof String) {
+            district.setCityCode((String) item.getCitycode());
+        }
+        if (item.getDistricts() != null) {
+            district.setChildCount(item.getDistricts().size());
+            district.setCityCount((int) item.getDistricts()
+                    .stream()
+                    .filter(d -> DistrictLevel.valueOf(d.getLevel().toUpperCase()) == DistrictLevel.CITY)
+                    .count());
+            district.setDistrictCount((int) item.getDistricts()
+                    .stream()
+                    .filter(d -> DistrictLevel.valueOf(d.getLevel().toUpperCase()) == DistrictLevel.DISTRICT)
+                    .count());
+            district.setStreetCount((int) item.getDistricts()
+                    .stream()
+                    .filter(d -> DistrictLevel.valueOf(d.getLevel().toUpperCase()) == DistrictLevel.STREET)
+                    .count());
+        } else {
+            district.setChildCount(0);
+        }
+        districtRepo.save(district);
+        if (item.getDistricts() != null) {
+            int[] idx = {1};
+            item.getDistricts().stream().parallel().forEach(child -> {
+                child.setIdx(idx[0]++);
+                saveDistrict(child, district.getId());
+            });
+        }
+    }
+
+}

+ 13 - 0
src/main/java/com/izouma/nineth/service/ExceptionLogService.java

@@ -0,0 +1,13 @@
+package com.izouma.nineth.service;
+
+import com.izouma.nineth.repo.ExceptionLogRepo;
+import lombok.AllArgsConstructor;
+import org.springframework.stereotype.Service;
+
+@Service
+@AllArgsConstructor
+public class ExceptionLogService {
+
+    private ExceptionLogRepo exceptionLogRepo;
+
+}

+ 173 - 0
src/main/java/com/izouma/nineth/service/GenCodeService.java

@@ -0,0 +1,173 @@
+package com.izouma.nineth.service;
+
+import com.izouma.nineth.dto.gen.GenCode;
+import com.izouma.nineth.dto.gen.TableField;
+import freemarker.template.Configuration;
+import freemarker.template.Template;
+import freemarker.template.TemplateException;
+import jodd.util.StringUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.awt.*;
+import java.awt.font.FontRenderContext;
+import java.awt.geom.AffineTransform;
+import java.io.*;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Service
+@Slf4j
+public class GenCodeService {
+    @Autowired
+    private Configuration cfg;
+
+    public void genController(GenCode model) throws IOException, TemplateException {
+
+        Path targetFile = StringUtils.isNotBlank(model.getGenPackage()) ?
+                Paths.get(model.getJavaPath(), "web", model.getGenPackage(), model.getClassName() + "Controller.java")
+                        .toAbsolutePath() :
+                Paths.get(model.getJavaPath(), "web", model.getClassName() + "Controller.java").toAbsolutePath();
+        Map<String, Object> extra = new HashMap<>();
+        if (StringUtil.isNotEmpty(model.getGenPackage())) {
+            List<String> imports = new ArrayList<>();
+            imports.add("import " + model.getBasePackage() + ".web.BaseController;");
+            extra.put("imports", imports);
+        }
+        extra.put("subPackage", StringUtil.isNotEmpty(model.getGenPackage()));
+        extra.put("softDelete", canSoftDelete(model));
+        genFile("ControllerTemplate.ftl", model, extra, targetFile);
+        log.info("成功生成Controller:{}", targetFile.toString());
+    }
+
+    public void genService(GenCode model) throws IOException, TemplateException {
+        Path targetFile = StringUtils.isNotBlank(model.getGenPackage()) ?
+                Paths.get(model.getJavaPath(), "service", model.getGenPackage(), model.getClassName() + "Service.java")
+                        .toAbsolutePath() :
+                Paths.get(model.getJavaPath(), "service", model.getClassName() + "Service.java").toAbsolutePath();
+        Map<String, Object> extra = new HashMap<>();
+        extra.put("softDelete", canSoftDelete(model));
+        genFile("ServiceTemplate.ftl", model, extra, targetFile);
+        log.info("成功生成Service:{}", targetFile.toString());
+    }
+
+    public void genRepo(GenCode model) throws IOException, TemplateException, ClassNotFoundException {
+        Path targetFile = StringUtils.isNotBlank(model.getGenPackage()) ?
+                Paths.get(model.getJavaPath(), "repo", model.getGenPackage(), model.getClassName() + "Repo.java")
+                        .toAbsolutePath() :
+                Paths.get(model.getJavaPath(), "repo", model.getClassName() + "Repo.java").toAbsolutePath();
+        Map<String, Object> extra = new HashMap<>();
+        extra.put("softDelete", canSoftDelete(model));
+        genFile("RepoTemplate.ftl", model, extra, targetFile);
+        log.info("成功生成Repo:{}", targetFile.toString());
+    }
+
+    public void genListView(GenCode model) throws IOException, TemplateException {
+        Path targetFile = Paths.get(model.getViewPath(), model.getClassName() + "List.vue").toAbsolutePath();
+        Map<String, Object> extra = new HashMap<>();
+        extra.put("softDelete", canSoftDelete(model));
+        genFile("ListViewTemplate.ftl", model, extra, targetFile);
+        log.info("成功生成ListView:{}", targetFile.toString());
+    }
+
+    public void genEditView(GenCode model) throws IOException, TemplateException, FontFormatException {
+        Path targetFile = Paths.get(model.getViewPath(), model.getClassName() + "Edit.vue").toAbsolutePath();
+        Map<String, Object> map = new HashMap<>();
+        int maxLabelWidth = 0;
+        for (TableField field : model.getFields()) {
+            String label = StringUtils.isEmpty(field.getRemark()) ? field.getModelName() : field.getRemark();
+            int labelWidth = measureText(label, 14);
+            if (labelWidth > maxLabelWidth) {
+                maxLabelWidth = labelWidth;
+            }
+        }
+        map.put("labelWidth", maxLabelWidth + 25 + "px");
+        map.put("softDelete", canSoftDelete(model));
+        genFile("EditViewTemplate.ftl", model, map, targetFile);
+        log.info("成功生成EditView:{}", targetFile.toString());
+    }
+
+    private void genFile(String template, GenCode model, Map<String, Object> extraData, Path path) throws IOException, TemplateException {
+        Map<String, Object> data = new HashMap<>();
+        data.put("model", model);
+        if (extraData != null) {
+            data.putAll(extraData);
+        }
+
+        Files.createDirectories(path.getParent());
+
+        Template temp = cfg.getTemplate(template);
+        Writer out = new FileWriter(path.toString());
+        temp.process(data, out);
+        out.flush();
+        out.close();
+    }
+
+    private int measureText(String text, float fontSize) throws IOException, FontFormatException {
+        AffineTransform affinetransform = new AffineTransform();
+        FontRenderContext frc = new FontRenderContext(affinetransform, true, true);
+        Font font = Font.createFont(Font.TRUETYPE_FONT, this.getClass()
+                .getResourceAsStream("/font/SourceHanSansCN-Normal.ttf"));
+        return (int) (font.deriveFont(fontSize).getStringBounds(text, frc).getWidth());
+    }
+
+    public void genRouter(GenCode model) {
+        try {
+            File file = new File(model.getRouterPath(), "router.js");
+            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
+            StringBuilder routerJs = new StringBuilder();
+            String line = null;
+            while ((line = reader.readLine()) != null) {
+                routerJs.append(line).append("\n");
+            }
+            reader.close();
+
+            int insertLocation = routerJs.indexOf("/**INSERT_LOCATION**/");
+            if (insertLocation > -1) {
+                String remark = model.getRemark();
+                String routeName = StringUtils.capitalize(model.getClassName());
+                String routePath = StringUtils.uncapitalize(model.getClassName());
+                String route = "{\n                    path: '/"
+                        + routePath
+                        + "Edit',\n                    name: '"
+                        + routeName
+                        + "Edit',\n                    component: () => import(/* webpackChunkName: \"" + routePath + "Edit\" */ '@/views/"
+                        + routeName
+                        + "Edit.vue'),\n                    meta: {\n                       title: '" + remark + "编辑',\n"
+                        + "                    },\n                },\n                {\n                    path: '/"
+                        + routePath
+                        + "List',\n                    name: '"
+                        + routeName
+                        + "List',\n                    component: () => import(/* webpackChunkName: \"" + routePath + "List\" */ '@/views/"
+                        + routeName
+                        + "List.vue'),\n                    meta: {\n                       title: '" + remark + "',\n"
+                        + "                    },\n               }\n                ";
+                boolean needComma = !routerJs.toString().substring(0, insertLocation).trim().endsWith(",");
+                if (needComma) {
+                    routerJs.insert(routerJs.toString().substring(0, insertLocation).lastIndexOf("}") + 1, ",");
+                    insertLocation++;
+                }
+                routerJs.insert(insertLocation, route);
+            }
+
+            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
+            bufferedOutputStream.write(routerJs.toString().trim().getBytes());
+            bufferedOutputStream.close();
+
+            System.out.println("成功生成路由:" + file.getAbsolutePath());
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    private boolean canSoftDelete(GenCode model) {
+        return true;
+    }
+}

+ 13 - 0
src/main/java/com/izouma/nineth/service/OperationLogService.java

@@ -0,0 +1,13 @@
+package com.izouma.nineth.service;
+
+import com.izouma.nineth.repo.OperationLogRepo;
+import lombok.AllArgsConstructor;
+import org.springframework.stereotype.Service;
+
+@Service
+@AllArgsConstructor
+public class OperationLogService {
+
+    private OperationLogRepo operationLogRepo;
+
+}

+ 53 - 0
src/main/java/com/izouma/nineth/service/SysConfigService.java

@@ -0,0 +1,53 @@
+package com.izouma.nineth.service;
+
+import com.izouma.nineth.domain.SysConfig;
+import com.izouma.nineth.dto.PageQuery;
+import com.izouma.nineth.exception.BusinessException;
+import com.izouma.nineth.repo.SysConfigRepo;
+import com.izouma.nineth.utils.JpaUtils;
+import lombok.AllArgsConstructor;
+import org.springframework.data.domain.Page;
+import org.springframework.stereotype.Service;
+import springfox.documentation.annotations.Cacheable;
+
+import java.math.BigDecimal;
+import java.time.LocalTime;
+import java.time.format.DateTimeFormatter;
+
+@Service
+@AllArgsConstructor
+public class SysConfigService {
+    private SysConfigRepo sysConfigRepo;
+
+    public Page<SysConfig> all(PageQuery pageQuery) {
+        return sysConfigRepo.findAll(JpaUtils.toSpecification(pageQuery, SysConfig.class), JpaUtils.toPageRequest(pageQuery));
+    }
+
+    @Cacheable("SysConfigServiceGetBigDecimal")
+    public BigDecimal getBigDecimal(String name) {
+        return sysConfigRepo.findByName(name).map(sysConfig -> new BigDecimal(sysConfig.getValue()))
+                .orElse(BigDecimal.ZERO);
+    }
+
+    @Cacheable("SysConfigServiceGetTime")
+    public LocalTime getTime(String name) {
+        String str = sysConfigRepo.findByName(name).map(SysConfig::getValue)
+                .orElseThrow(new BusinessException("配置不存在"));
+        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm");
+        return LocalTime.from(dateTimeFormatter.parse(str));
+    }
+
+    @Cacheable("SysConfigServiceGetBoolean")
+    public boolean getBoolean(String name) {
+        String str = sysConfigRepo.findByName(name).map(SysConfig::getValue)
+                .orElseThrow(new BusinessException("配置不存在"));
+        return str.equals("1");
+    }
+
+    @Cacheable("SysConfigServiceGetInt")
+    public int getInt(String name) {
+        String str = sysConfigRepo.findByName(name).map(SysConfig::getValue)
+                .orElseThrow(new BusinessException("配置不存在"));
+        return Integer.parseInt(str);
+    }
+}

+ 20 - 0
src/main/java/com/izouma/nineth/service/TestClassService.java

@@ -0,0 +1,20 @@
+package com.izouma.nineth.service;
+
+import com.izouma.nineth.domain.TestClass;
+import com.izouma.nineth.dto.PageQuery;
+import com.izouma.nineth.repo.TestClassRepo;
+import com.izouma.nineth.utils.JpaUtils;
+import lombok.AllArgsConstructor;
+import org.springframework.data.domain.Page;
+import org.springframework.stereotype.Service;
+
+@Service
+@AllArgsConstructor
+public class TestClassService {
+
+    private TestClassRepo testClassRepo;
+
+    public Page<TestClass> all(PageQuery pageQuery) {
+        return testClassRepo.findAll(JpaUtils.toSpecification(pageQuery, TestClass.class), JpaUtils.toPageRequest(pageQuery));
+    }
+}

+ 184 - 0
src/main/java/com/izouma/nineth/service/UserService.java

@@ -0,0 +1,184 @@
+package com.izouma.nineth.service;
+
+import cn.binarywang.wx.miniapp.api.WxMaService;
+import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
+import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
+import com.izouma.nineth.config.Constants;
+import com.izouma.nineth.domain.User;
+import com.izouma.nineth.dto.PageQuery;
+import com.izouma.nineth.dto.UserRegister;
+import com.izouma.nineth.exception.BusinessException;
+import com.izouma.nineth.repo.UserRepo;
+import com.izouma.nineth.security.Authority;
+import com.izouma.nineth.security.JwtTokenUtil;
+import com.izouma.nineth.security.JwtUserFactory;
+import com.izouma.nineth.service.sms.SmsService;
+import com.izouma.nineth.service.storage.StorageService;
+import com.izouma.nineth.utils.JpaUtils;
+import lombok.AllArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import me.chanjar.weixin.common.error.WxErrorException;
+import me.chanjar.weixin.mp.api.WxMpService;
+import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
+import me.chanjar.weixin.mp.bean.result.WxMpUser;
+import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.BeanUtils;
+import org.springframework.data.domain.Page;
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+import org.springframework.stereotype.Service;
+
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+@Service
+@Slf4j
+@AllArgsConstructor
+public class UserService {
+    private UserRepo       userRepo;
+    private WxMaService    wxMaService;
+    private WxMpService    wxMpService;
+    private SmsService     smsService;
+    private StorageService storageService;
+    private JwtTokenUtil   jwtTokenUtil;
+    private CaptchaService captchaService;
+
+    public Page<User> all(PageQuery pageQuery) {
+        return userRepo.findAll(JpaUtils.toSpecification(pageQuery, User.class), JpaUtils.toPageRequest(pageQuery));
+    }
+
+    public User create(UserRegister userRegister) {
+        User user = new User();
+        BeanUtils.copyProperties(userRegister, user);
+        if (StringUtils.isNotBlank(userRegister.getPassword())) {
+            user.setPassword(new BCryptPasswordEncoder().encode(userRegister.getPassword()));
+        }
+        return userRepo.save(user);
+    }
+
+    public void del(Long id) {
+        User user = userRepo.findById(id).orElseThrow(new BusinessException("用户不存在"));
+        user.setDel(true);
+        if (StringUtils.isNoneEmpty(user.getOpenId())) {
+            user.setOpenId(user.getOpenId() + "###" + RandomStringUtils.randomAlphabetic(8));
+        }
+        if (StringUtils.isNoneEmpty(user.getPhone())) {
+            user.setPhone(user.getPhone() + "###" + RandomStringUtils.randomAlphabetic(8));
+        }
+        userRepo.save(user);
+    }
+
+    public User loginByPhone(String phone) {
+        return userRepo.findByPhoneAndDelFalse(phone);
+    }
+
+    public User loginMp(String code) throws WxErrorException {
+        WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
+        WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(accessToken, null);
+        User user = userRepo.findByOpenIdAndDelFalse(wxMpUser.getOpenId());
+        if (user == null) {
+            user = User.builder()
+                    .username(UUID.randomUUID().toString())
+                    .nickname(wxMpUser.getNickname())
+                    .avatar(wxMpUser.getHeadImgUrl())
+                    .sex(wxMpUser.getSexDesc())
+                    .country(wxMpUser.getCountry())
+                    .province(wxMpUser.getProvince())
+                    .city(wxMpUser.getCity())
+                    .openId(wxMpUser.getOpenId())
+                    .language(wxMpUser.getLanguage())
+                    .authorities(Collections.singleton(Authority.builder().name("ROLE_USER").build()))
+                    .build();
+            userRepo.save(user);
+        }
+        return user;
+    }
+
+    public User loginMa(String code) {
+        try {
+            WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
+            String openId = result.getOpenid();
+            String sessionKey = result.getSessionKey();
+            User userInfo = userRepo.findByOpenIdAndDelFalse(openId);
+            if (userInfo != null) {
+                return userInfo;
+            }
+            userInfo = User.builder()
+                    .username(UUID.randomUUID().toString())
+                    .nickname("用户" + RandomStringUtils.randomAlphabetic(6))
+                    .openId(openId)
+                    .avatar(Constants.DEFAULT_AVATAR)
+                    .authorities(Collections.singleton(Authority.builder().name("ROLE_USER").build()))
+                    .build();
+            userInfo = userRepo.save(userInfo);
+            return userInfo;
+        } catch (WxErrorException e) {
+            e.printStackTrace();
+        }
+        throw new BusinessException("登录失败");
+    }
+
+    public User getMaUserInfo(String sessionKey, String rawData, String signature,
+                              String encryptedData, String iv) {
+        // 用户信息校验
+        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
+            throw new BusinessException("获取用户信息失败");
+        }
+
+        // 解密用户信息
+        WxMaUserInfo wxUserInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
+        User user = userRepo.findByOpenIdAndDelFalse(wxUserInfo.getOpenId());
+
+        String avatarUrl = Constants.DEFAULT_AVATAR;
+        try {
+            String path = "image/avatar/" +
+                    new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) +
+                    RandomStringUtils.randomAlphabetic(8) +
+                    ".jpg";
+            avatarUrl = storageService.uploadFromUrl(wxUserInfo.getAvatarUrl(), path);
+        } catch (Exception e) {
+            log.error("获取头像失败", e);
+        }
+
+        if (user == null) {
+
+            user = User.builder()
+                    .username(UUID.randomUUID().toString())
+                    .nickname(wxUserInfo.getNickName())
+                    .openId(wxUserInfo.getOpenId())
+                    .avatar(avatarUrl)
+                    .sex(wxUserInfo.getGender())
+                    .country(wxUserInfo.getCountry())
+                    .province(wxUserInfo.getProvince())
+                    .city(wxUserInfo.getCity())
+                    .authorities(Collections.singleton(Authority.builder().name("ROLE_USER").build()))
+                    .build();
+            user = userRepo.save(user);
+
+        } else {
+            user.setAvatar(avatarUrl);
+            user.setNickname(wxUserInfo.getNickName());
+            user.setSex(wxUserInfo.getGender());
+            user.setCountry(wxUserInfo.getCountry());
+            user.setProvince(wxUserInfo.getProvince());
+            user.setCity(wxUserInfo.getCity());
+            user = userRepo.save(user);
+        }
+
+        return user;
+    }
+
+    public String setPassword(Long userId, String password) {
+        User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
+        user.setPassword(new BCryptPasswordEncoder().encode(password));
+        user = userRepo.save(user);
+        return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
+    }
+
+    public String setPassword(Long userId, String key, String code, String password) {
+        if (!captchaService.verify(key, code)) {
+            throw new BusinessException("验证码错误");
+        }
+        return setPassword(userId, password);
+    }
+}

+ 94 - 0
src/main/java/com/izouma/nineth/service/sms/AliSmsService.java

@@ -0,0 +1,94 @@
+package com.izouma.nineth.service.sms;
+
+import com.aliyuncs.CommonRequest;
+import com.aliyuncs.CommonResponse;
+import com.aliyuncs.DefaultAcsClient;
+import com.aliyuncs.IAcsClient;
+import com.aliyuncs.exceptions.ClientException;
+import com.aliyuncs.http.MethodType;
+import com.aliyuncs.profile.DefaultProfile;
+import com.izouma.nineth.config.Constants;
+import com.izouma.nineth.domain.SmsRecord;
+import com.izouma.nineth.exception.BusinessException;
+import com.izouma.nineth.repo.SmsRecordRepo;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.RandomStringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.configurationprocessor.json.JSONException;
+import org.springframework.boot.configurationprocessor.json.JSONObject;
+import org.springframework.stereotype.Service;
+
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
+
+@Service
+@Slf4j
+public class AliSmsService implements SmsService {
+    @Value("${aliyun.access-key-id}")
+    private String        accessKeyId;
+    @Value("${aliyun.access-key-secret}")
+    private String        accessKeySecret;
+    @Autowired
+    private SmsRecordRepo smsRecordRepo;
+
+    @Override
+    public String sendVerify(String phone) {
+        smsRecordRepo.findLastByPhoneAndExpiresAtAfterAndExpiredFalse(phone, LocalDateTime.now()).ifPresent(record -> {
+            if (record.getCreatedAt().plusMinutes(1L).isAfter(LocalDateTime.now())) {
+                long sec = record.getCreatedAt().plusMinutes(1L).toInstant(ZoneOffset.UTC).getEpochSecond() - LocalDateTime.now().toInstant(ZoneOffset.UTC).getEpochSecond() + 1;
+                throw new BusinessException("请" + sec + "秒后再试");
+            }
+        });
+
+        String code = RandomStringUtils.randomNumeric(4);
+        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
+        IAcsClient client = new DefaultAcsClient(profile);
+
+        CommonRequest request = new CommonRequest();
+        request.setMethod(MethodType.POST);
+        request.setDomain("dysmsapi.aliyuncs.com");
+        request.setVersion("2017-05-25");
+        request.setAction("SendSms");
+        request.putQueryParameter("PhoneNumbers", phone);
+        request.putQueryParameter("SignName", Constants.SMS_SIGN_NAME);
+        request.putQueryParameter("TemplateCode", Constants.SMS_TEMPLATE_CODE_GENERIC);
+        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
+        try {
+            CommonResponse response = client.getCommonResponse(request);
+            if (response.getHttpStatus() != 200) {
+                throw new BusinessException("发送失败,请稍后再试", response.getHttpStatus() + "," + response.getData());
+            }
+            log.info("send sms response {}", response.getData());
+            JSONObject jsonObject = new JSONObject(response.getData());
+            if (!"ok".equalsIgnoreCase(jsonObject.getString("Code"))) {
+                throw new BusinessException("发送失败,请稍后再试", jsonObject.getString("Message"));
+            }
+            smsRecordRepo.expire(phone);
+            String sessionId = RandomStringUtils.randomAlphabetic(10);
+            smsRecordRepo.save(SmsRecord.builder()
+                                        .sessionId(sessionId)
+                                        .phone(phone)
+                                        .code(code)
+                                        .expiresAt(LocalDateTime.now().plusMinutes(5))
+                                        .expired(false)
+                                        .build());
+            return sessionId;
+        } catch (ClientException | JSONException e) {
+            e.printStackTrace();
+            throw new BusinessException("发送失败,请稍后再试", e.getMessage());
+        }
+    }
+
+    @Override
+    public void verify(String phone, String code) throws SmsVerifyException {
+        SmsRecord smsRecord = smsRecordRepo.findLastByPhoneAndExpiresAtAfterAndExpiredFalse(phone, LocalDateTime.now()).orElseThrow(new SmsVerifyException("验证码错误"));
+        if (!smsRecord.getCode().equalsIgnoreCase(code)) {
+            throw new BusinessException("验证码错误");
+        }
+        smsRecord.setExpired(true);
+        smsRecordRepo.save(smsRecord);
+    }
+
+
+}

+ 20 - 0
src/main/java/com/izouma/nineth/service/sms/SmsService.java

@@ -0,0 +1,20 @@
+package com.izouma.nineth.service.sms;
+
+import java.util.function.Supplier;
+
+public interface SmsService {
+    String sendVerify(String phone);
+
+    void verify(String phone, String code) throws SmsVerifyException;
+
+    class SmsVerifyException extends Exception implements Supplier<SmsVerifyException> {
+        public SmsVerifyException(String msg) {
+            super(msg);
+        }
+
+        @Override
+        public SmsVerifyException get() {
+            return this;
+        }
+    }
+}

+ 70 - 0
src/main/java/com/izouma/nineth/service/storage/AliStorageService.java

@@ -0,0 +1,70 @@
+package com.izouma.nineth.service.storage;
+
+import com.aliyun.oss.OSSClient;
+import com.aliyun.oss.model.ObjectMetadata;
+import com.izouma.nineth.exception.BusinessException;
+import lombok.Data;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.stereotype.Service;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+
+@Data
+@Service
+@Slf4j
+@EnableConfigurationProperties
+@ConfigurationProperties(prefix = "aliyun")
+@ConditionalOnProperty(name = "storage.provider", havingValue = "aliyun")
+public class AliStorageService implements StorageService {
+    private String accessKeyId;
+    private String accessKeySecret;
+    private String ossBucketName;
+    private String ossEndPoint;
+    private String ossDomain;
+
+    @Override
+    public String uploadFromInputStream(InputStream inputStream, String path) {
+        log.info("阿里云OSS上传: inputStream -> {}", path);
+        try {
+            String result = upload(inputStream, path);
+            log.info("上传成功 {}", result);
+            return result;
+        } catch (Exception e) {
+            log.error("阿里云OSS上传失败", e);
+            throw new BusinessException("上传失败", e.getMessage());
+        }
+    }
+
+    @Override
+    public String uploadFromUrl(String url, String path) {
+        log.info("阿里云OSS上传: {} -> {}", url, path);
+        try {
+            InputStream inputStream = new URL(url).openStream();
+            String result = upload(inputStream, path);
+            log.info("上传成功 {}", result);
+            return result;
+        } catch (Exception e) {
+            log.error("阿里云OSS上传失败", e);
+            throw new BusinessException("上传失败", e.getMessage());
+        }
+    }
+
+    private String upload(InputStream inputStream, String path) {
+        OSSClient client = new OSSClient(ossEndPoint, accessKeyId, accessKeySecret);
+        ObjectMetadata metadata = new ObjectMetadata();
+        client.putObject(ossBucketName, path, inputStream, metadata);
+        client.shutdown();
+        try {
+            inputStream.close();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return ossDomain + "/" + path;
+    }
+
+}

+ 63 - 0
src/main/java/com/izouma/nineth/service/storage/LocalStorageService.java

@@ -0,0 +1,63 @@
+package com.izouma.nineth.service.storage;
+
+import com.izouma.nineth.exception.BusinessException;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.io.FileUtils;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.stereotype.Service;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+@Service
+@Slf4j
+@ConditionalOnProperty(name = "storage.provider", havingValue = "local")
+public class LocalStorageService implements StorageService {
+
+    @Value("${storage.local_path}")
+    private String localPath;
+
+    @Override
+    public String uploadFromInputStream(InputStream fin, String path) {
+        log.info("本地上传: inputStream -> {}", path);
+        try {
+            return upload(fin, path);
+        } catch (IOException e) {
+            log.error("本地上传失败", e);
+            throw new BusinessException("上传失败", e.getMessage());
+        }
+    }
+
+    @Override
+    public String uploadFromUrl(String url, String path) {
+        log.info("本地上传: {} -> {}", url, path);
+        try {
+            InputStream inputStream = new URL(url).openStream();
+            return upload(inputStream, path);
+        } catch (Exception e) {
+            log.error("本地上传失败", e);
+            throw new BusinessException("上传失败", e.getMessage());
+        }
+    }
+
+    private String upload(InputStream inputStream, String path) throws IOException {
+        Path uploadPath = Paths.get(localPath, path).getParent();
+        if (Files.notExists(uploadPath, LinkOption.values())) {
+            Files.createDirectories(uploadPath);
+        }
+        FileUtils.copyToFile(inputStream, new File(Paths.get(localPath, path).toString()));
+        try {
+            inputStream.close();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return "files" + "/" + path;
+    }
+}

+ 9 - 0
src/main/java/com/izouma/nineth/service/storage/StorageService.java

@@ -0,0 +1,9 @@
+package com.izouma.nineth.service.storage;
+
+import java.io.InputStream;
+
+public interface StorageService {
+    String uploadFromInputStream(InputStream fin, String path);
+
+    String uploadFromUrl(String url, String path);
+}

+ 45 - 0
src/main/java/com/izouma/nineth/utils/DateTimeUtils.java

@@ -0,0 +1,45 @@
+package com.izouma.nineth.utils;
+
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.time.temporal.TemporalAccessor;
+
+public class DateTimeUtils {
+    public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm";
+    public static final String T_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
+    public static final String DATE_FORMAT      = "yyyy-MM-dd";
+
+    public static LocalDate toLocalDate(long ts) {
+        if (String.valueOf(ts).length() > 10) {
+            return LocalDate.from(Instant.ofEpochMilli(ts));
+        } else {
+            return LocalDate.from(Instant.ofEpochSecond(ts));
+        }
+    }
+
+    public static LocalDateTime toLocalDateTime(long ts) {
+        if (String.valueOf(ts).length() > 10) {
+            return LocalDateTime.from(Instant.ofEpochMilli(ts));
+        } else {
+            return LocalDateTime.from(Instant.ofEpochSecond(ts));
+        }
+    }
+
+    public static LocalDate toLocalDate(String str, String fmt) {
+        return LocalDate.from(DateTimeFormatter.ofPattern(fmt).parse(str));
+    }
+
+    public static LocalDateTime toLocalDateTime(String str, String fmt) {
+        return LocalDateTime.from(DateTimeFormatter.ofPattern(fmt).parse(str));
+    }
+
+    public static String format(TemporalAccessor temporal, String fmt) {
+        return DateTimeFormatter.ofPattern(fmt).format(temporal);
+    }
+
+    public static long toTimestamp(TemporalAccessor temporal) {
+        return Instant.from(temporal).toEpochMilli();
+    }
+}

+ 204 - 0
src/main/java/com/izouma/nineth/utils/FileUtils.java

@@ -0,0 +1,204 @@
+package com.izouma.nineth.utils;
+
+import org.apache.commons.lang3.StringUtils;
+
+import java.io.*;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.PosixFileAttributeView;
+import java.nio.file.attribute.PosixFileAttributes;
+import java.nio.file.attribute.PosixFilePermission;
+import java.nio.file.attribute.PosixFilePermissions;
+import java.util.Set;
+
+public class FileUtils {
+
+    public static String getExtension(String fileName) {
+        if (StringUtils.INDEX_NOT_FOUND == StringUtils.indexOf(fileName, "."))
+            return StringUtils.EMPTY;
+        String ext = StringUtils.substring(fileName, StringUtils.lastIndexOf(fileName, "."));
+        return StringUtils.trimToEmpty(ext);
+    }
+
+    public static String getFileName(String header) {
+        String[] tempArr1 = header.split(";");
+        String[] tempArr2 = tempArr1[2].split("=");
+        // 获取文件名,兼容各种浏览器的写法
+        return tempArr2[1].substring(tempArr2[1].lastIndexOf("\\") + 1).replaceAll("\"", "");
+
+    }
+
+    /**
+     * 获取文件权限
+     *
+     * <pre>
+     * 当前仅支持posix系统,需要修改为windows格式
+     * </pre>
+     *
+     * @param path
+     * @return
+     * @throws IOException
+     */
+    public static String getPermissions(Path path) throws IOException {
+        PosixFileAttributeView fileAttributeView = Files.getFileAttributeView(path, PosixFileAttributeView.class);
+        PosixFileAttributes readAttributes = fileAttributeView.readAttributes();
+        Set<PosixFilePermission> permissions = readAttributes.permissions();
+        return PosixFilePermissions.toString(permissions);
+    }
+
+    /**
+     * 修改文件权限
+     *
+     * @param file
+     * @param permsCode
+     * @param recursive
+     * @return
+     * @throws IOException
+     */
+    public static String setPermissions(File file, String permsCode, boolean recursive) throws IOException {
+        PosixFileAttributeView fileAttributeView = Files.getFileAttributeView(file.toPath(),
+                PosixFileAttributeView.class);
+        fileAttributeView.setPermissions(PosixFilePermissions.fromString(permsCode));
+        if (file.isDirectory() && recursive && file.listFiles() != null) {
+            for (File f : file.listFiles()) {
+                setPermissions(f, permsCode, true);
+            }
+        }
+        return permsCode;
+    }
+
+    public static boolean write(InputStream inputStream, File f) {
+        boolean ret = false;
+
+        try (OutputStream outputStream = new FileOutputStream(f)) {
+
+            int read;
+            byte[] bytes = new byte[1024];
+
+            while ((read = inputStream.read(bytes)) != -1) {
+                outputStream.write(bytes, 0, read);
+            }
+            ret = true;
+
+        } catch (IOException e) {
+            e.printStackTrace();
+
+        } finally {
+            if (inputStream != null) {
+                try {
+                    inputStream.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+        }
+        return ret;
+    }
+
+    public static void mkFolder(String fileName) {
+        File f = new File(fileName);
+        if (!f.exists()) {
+            f.mkdir();
+        }
+    }
+
+    public static File mkFile(String fileName) {
+        File f = new File(fileName);
+        try {
+            f.createNewFile();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return f;
+    }
+
+    public static void fileProber(File dirFile) {
+
+        File parentFile = dirFile.getParentFile();
+        if (!parentFile.exists()) {
+
+            // 递归寻找上级目录
+            fileProber(parentFile);
+
+            parentFile.mkdir();
+        }
+
+    }
+
+    /**
+     * 将文本文件中的内容读入到buffer中
+     *
+     * @param buffer   buffer
+     * @param filePath 文件路径
+     * @throws IOException 异常
+     * @date 2013-1-7
+     */
+    public static void readToBuffer(StringBuffer buffer, String filePath) throws IOException {
+        InputStream is = new FileInputStream(filePath);
+        String line; // 用来保存每行读取的内容
+        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
+        line = reader.readLine(); // 读取第一行
+        while (line != null) { // 如果 line 为空说明读完了
+            buffer.append(line); // 将读到的内容添加到 buffer 中
+            buffer.append("\n"); // 添加换行符
+            line = reader.readLine(); // 读取下一行
+        }
+        reader.close();
+        is.close();
+    }
+
+    /**
+     * 读取文本文件内容
+     *
+     * @param filePath 文件所在路径
+     * @return 文本内容
+     * @throws IOException 异常
+     * @date 2013-1-7
+     */
+    public static String readFile(String filePath) throws IOException {
+        StringBuffer sb = new StringBuffer();
+        FileUtils.readToBuffer(sb, filePath);
+        return sb.toString();
+    }
+
+
+    /**
+     * 功能:Java读取txt文件的内容
+     * 步骤:1:先获得文件句柄
+     * 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
+     * 3:读取到输入流后,需要读取生成字节流
+     * 4:一行一行的输出。readline()。
+     * 备注:需要考虑的是异常情况
+     */
+    public static String readFileToString(File file) {
+        try {
+            if (file.isFile() && file.exists()) { //判断文件是否存在
+                Long filelength = file.length(); // 获取文件长度
+                byte[] filecontent = new byte[filelength.intValue()];
+                try {
+                    FileInputStream in = new FileInputStream(file);
+                    in.read(filecontent);
+                    in.close();
+                } catch (FileNotFoundException e) {
+                    e.printStackTrace();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+
+                String fileContentArr = new String(filecontent);
+
+                return fileContentArr;// 返回文件内容,默认编码
+            } else {
+                System.out.println("找不到指定的文件");
+            }
+        } catch (Exception e) {
+            System.out.println("读取文件内容出错");
+            e.printStackTrace();
+        }
+
+        return null;
+
+    }
+
+
+}

+ 71 - 0
src/main/java/com/izouma/nineth/utils/IPUtils.java

@@ -0,0 +1,71 @@
+package com.izouma.nineth.utils;
+
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.util.StringUtils;
+
+import javax.servlet.http.HttpServletRequest;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+
+@Slf4j
+public class IPUtils {
+    private static final String IP_UTILS_FLAG = ",";
+    private static final String UNKNOWN       = "unknown";
+    private static final String LOCALHOST_IP  = "0:0:0:0:0:0:0:1";
+    private static final String LOCALHOST_IP1 = "127.0.0.1";
+
+    /**
+     * 获取IP地址
+     * <p>
+     * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
+     * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
+     */
+    public static String getIpAddr(HttpServletRequest request) {
+        String ip = null;
+        try {
+            //以下两个获取在k8s中,将真实的客户端IP,放到了x-Original-Forwarded-For。而将WAF的回源地址放到了 x-Forwarded-For了。
+            ip = request.getHeader("X-Original-Forwarded-For");
+            if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
+                ip = request.getHeader("X-Forwarded-For");
+            }
+            //获取nginx等代理的ip
+            if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
+                ip = request.getHeader("x-forwarded-for");
+            }
+            if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
+                ip = request.getHeader("Proxy-Client-IP");
+            }
+            if (StringUtils.isEmpty(ip) || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
+                ip = request.getHeader("WL-Proxy-Client-IP");
+            }
+            if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
+                ip = request.getHeader("HTTP_CLIENT_IP");
+            }
+            if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
+                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
+            }
+            //兼容k8s集群获取ip
+            if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
+                ip = request.getRemoteAddr();
+                if (LOCALHOST_IP1.equalsIgnoreCase(ip) || LOCALHOST_IP.equalsIgnoreCase(ip)) {
+                    //根据网卡取本机配置的IP
+                    InetAddress iNet = null;
+                    try {
+                        iNet = InetAddress.getLocalHost();
+                        ip = iNet.getHostAddress();
+                    } catch (UnknownHostException e) {
+                        log.error("getClientIp error", e);
+                    }
+                }
+            }
+        } catch (Exception e) {
+            log.error("IPUtils ERROR ", e);
+        }
+        //使用代理,则获取第一个IP地址
+        if (!StringUtils.isEmpty(ip) && ip.indexOf(IP_UTILS_FLAG) > 0) {
+            ip = ip.substring(0, ip.indexOf(IP_UTILS_FLAG));
+        }
+
+        return ip;
+    }
+}

+ 8 - 0
src/main/java/com/izouma/nineth/utils/ImageUtils.java

@@ -0,0 +1,8 @@
+package com.izouma.nineth.utils;
+
+public class ImageUtils {
+
+    public static void compressJpg() {
+
+    }
+}

Энэ ялгаанд хэт олон файл өөрчлөгдсөн тул зарим файлыг харуулаагүй болно