Browse Source

首次提交

贾艺驰 1 year ago
commit
0a79977bdf
100 changed files with 7564 additions and 0 deletions
  1. 26 0
      .gitignore
  2. 58 0
      base/pom.xml
  3. 70 0
      base/sql.sql
  4. 64 0
      base/src/main/java/com/api/base/config/DateConverterConfig.java
  5. 41 0
      base/src/main/java/com/api/base/config/ExceptionHandler.java
  6. 101 0
      base/src/main/java/com/api/base/config/InitRunner.java
  7. 89 0
      base/src/main/java/com/api/base/config/MvcConfigurer.java
  8. 69 0
      base/src/main/java/com/api/base/config/MybatisConfigurer.java
  9. 18 0
      base/src/main/java/com/api/base/config/ProjectConstant.java
  10. 58 0
      base/src/main/java/com/api/base/config/auth/AccessManager.java
  11. 80 0
      base/src/main/java/com/api/base/config/auth/JwtAuthenticationTokenFilter.java
  12. 132 0
      base/src/main/java/com/api/base/config/auth/JwtTokenUtil.java
  13. 91 0
      base/src/main/java/com/api/base/config/auth/PowerSource.java
  14. 132 0
      base/src/main/java/com/api/base/config/auth/SecurityConfig.java
  15. 24 0
      base/src/main/java/com/api/base/config/auth/handler/GoAccessDeniedHandler.java
  16. 34 0
      base/src/main/java/com/api/base/config/auth/handler/GoAuthenticationEntryPoint.java
  17. 32 0
      base/src/main/java/com/api/base/config/auth/handler/GoAuthenticationFailureHandler.java
  18. 53 0
      base/src/main/java/com/api/base/config/auth/handler/GoAuthenticationSuccessHandler.java
  19. 27 0
      base/src/main/java/com/api/base/config/auth/handler/GoLogoutSuccessHandler.java
  20. 60 0
      base/src/main/java/com/api/base/config/auth/service/DetailsService.java
  21. 34 0
      base/src/main/java/com/api/base/config/cache/RedisConfig.java
  22. 69 0
      base/src/main/java/com/api/base/config/cache/SerializeUtils.java
  23. 67 0
      base/src/main/java/com/api/base/controll/PowerController.java
  24. 93 0
      base/src/main/java/com/api/base/controll/RoleController.java
  25. 71 0
      base/src/main/java/com/api/base/controll/SysWhitelistController.java
  26. 142 0
      base/src/main/java/com/api/base/controll/Upload.java
  27. 184 0
      base/src/main/java/com/api/base/controll/UserController.java
  28. 18 0
      base/src/main/java/com/api/base/dao/PowerMapper.java
  29. 14 0
      base/src/main/java/com/api/base/dao/RoleMapper.java
  30. 7 0
      base/src/main/java/com/api/base/dao/RolePowerMapper.java
  31. 10 0
      base/src/main/java/com/api/base/dao/SysWhitelistMapper.java
  32. 9 0
      base/src/main/java/com/api/base/dao/UserMapper.java
  33. 9 0
      base/src/main/java/com/api/base/dao/UserRoleMapper.java
  34. 29 0
      base/src/main/java/com/api/base/dao/mapper/PowerMapper.xml
  35. 24 0
      base/src/main/java/com/api/base/dao/mapper/RoleMapper.xml
  36. 8 0
      base/src/main/java/com/api/base/dao/mapper/RolePowerMapper.xml
  37. 14 0
      base/src/main/java/com/api/base/dao/mapper/SysWhitelistMapper.xml
  38. 26 0
      base/src/main/java/com/api/base/dao/mapper/UserMapper.xml
  39. 11 0
      base/src/main/java/com/api/base/dao/mapper/UserRoleMapper.xml
  40. 36 0
      base/src/main/java/com/api/base/dto/ElTree.java
  41. 54 0
      base/src/main/java/com/api/base/model/Power.java
  42. 65 0
      base/src/main/java/com/api/base/model/Role.java
  43. 32 0
      base/src/main/java/com/api/base/model/RolePower.java
  44. 26 0
      base/src/main/java/com/api/base/model/SysWhitelist.java
  45. 277 0
      base/src/main/java/com/api/base/model/User.java
  46. 32 0
      base/src/main/java/com/api/base/model/UserRole.java
  47. 22 0
      base/src/main/java/com/api/base/service/PowerService.java
  48. 11 0
      base/src/main/java/com/api/base/service/RolePowerService.java
  49. 13 0
      base/src/main/java/com/api/base/service/RoleService.java
  50. 17 0
      base/src/main/java/com/api/base/service/SysWhitelistService.java
  51. 11 0
      base/src/main/java/com/api/base/service/UserRoleService.java
  52. 24 0
      base/src/main/java/com/api/base/service/UserService.java
  53. 41 0
      base/src/main/java/com/api/base/service/impl/PowerServiceImpl.java
  54. 22 0
      base/src/main/java/com/api/base/service/impl/RolePowerServiceImpl.java
  55. 45 0
      base/src/main/java/com/api/base/service/impl/RoleServiceImpl.java
  56. 37 0
      base/src/main/java/com/api/base/service/impl/SysWhitelistServiceImpl.java
  57. 22 0
      base/src/main/java/com/api/base/service/impl/UserRoleServiceImpl.java
  58. 97 0
      base/src/main/java/com/api/base/service/impl/UserServiceImpl.java
  59. 76 0
      code-generator/pom.xml
  60. 15 0
      code-generator/src/main/java/com/api/code/generator/config/ProjectConstant.java
  61. 94 0
      code-generator/src/main/java/com/api/code/generator/controller/CodeGeneratorController.java
  62. 254 0
      code-generator/src/main/java/com/api/code/generator/service/GeneratorService.java
  63. 54 0
      code-generator/src/main/java/com/api/code/generator/template/controller-restful.ftl
  64. 83 0
      code-generator/src/main/java/com/api/code/generator/template/controller.ftl
  65. 22 0
      code-generator/src/main/java/com/api/code/generator/template/service-impl.ftl
  66. 11 0
      code-generator/src/main/java/com/api/code/generator/template/service.ftl
  67. 81 0
      code-generator/src/main/resources/static/generator.html
  68. 73 0
      common/pom.xml
  69. 124 0
      common/src/main/java/com/api/common/GeneratorSnowflakeId.java
  70. 166 0
      common/src/main/java/com/api/common/IDCardUtils.java
  71. 31 0
      common/src/main/java/com/api/common/IPUtil.java
  72. 90 0
      common/src/main/java/com/api/common/ImageUploadUtil.java
  73. 117 0
      common/src/main/java/com/api/common/JSONUtils.java
  74. 143 0
      common/src/main/java/com/api/common/UtilFun.java
  75. 39 0
      common/src/main/java/com/api/common/config/UploadConfig.java
  76. 90 0
      common/src/main/java/com/api/common/execl/ExcelUtil.java
  77. 47 0
      common/src/main/java/com/api/common/jpush/JPush.java
  78. 373 0
      common/src/main/java/com/api/common/jpush/JpushService.java
  79. 344 0
      common/src/main/java/com/api/common/mybatis/MapperRefresh.java
  80. 22 0
      common/src/main/java/com/api/common/mybatis/NameSpace.java
  81. 29 0
      common/src/main/java/com/api/common/mybatis/ResultMap.java
  82. 35 0
      common/src/main/java/com/api/common/mybatis/RootConfiguration.java
  83. 86 0
      common/src/main/java/com/api/common/wx/Notify.java
  84. 27 0
      common/src/main/java/com/api/common/wx/ReturnCode.java
  85. 60 0
      common/src/main/java/com/api/common/wx/WxCommon.java
  86. 74 0
      common/src/main/java/com/api/common/wx/WxRequest.java
  87. 42 0
      common/src/main/java/com/api/common/wx/pay/IWXPayDomain.java
  88. 107 0
      common/src/main/java/com/api/common/wx/pay/WXConfig.java
  89. 660 0
      common/src/main/java/com/api/common/wx/pay/WXPay.java
  90. 103 0
      common/src/main/java/com/api/common/wx/pay/WXPayConfig.java
  91. 63 0
      common/src/main/java/com/api/common/wx/pay/WXPayConstants.java
  92. 265 0
      common/src/main/java/com/api/common/wx/pay/WXPayReport.java
  93. 257 0
      common/src/main/java/com/api/common/wx/pay/WXPayRequest.java
  94. 295 0
      common/src/main/java/com/api/common/wx/pay/WXPayUtil.java
  95. 30 0
      common/src/main/java/com/api/common/wx/pay/WXPayXmlUtil.java
  96. 49 0
      core/pom.xml
  97. 19 0
      core/src/main/java/com/api/core/Mapper.java
  98. 17 0
      core/src/main/java/com/api/core/ServiceException.java
  99. 15 0
      core/src/main/java/com/api/core/annotation/PowerEnable.java
  100. 0 0
      core/src/main/java/com/api/core/annotation/condition/HttpsCondition.java

+ 26 - 0
.gitignore

@@ -0,0 +1,26 @@
+# Compiled class file
+*.class
+
+# Log file
+*.log
+
+# BlueJ files
+*.ctxt
+
+# Mobile Tools for Java (J2ME)
+.mtj.tmp/
+
+# Package Files #
+*.jar
+*.war
+*.nar
+*.ear
+*.zip
+*.tar.gz
+*.rar
+*.iml
+.idea/
+target
+# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
+hs_err_pid*
+games.iml

+ 58 - 0
base/pom.xml

@@ -0,0 +1,58 @@
+<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <parent>
+        <artifactId>parent</artifactId>
+        <groupId>com.api</groupId>
+        <version>1.0-SNAPSHOT</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+
+    <artifactId>base</artifactId>
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-redis</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>io.jsonwebtoken</groupId>
+            <artifactId>jjwt</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.api</groupId>
+            <artifactId>core</artifactId>
+            <version>1.0-SNAPSHOT</version>
+        </dependency>
+        <dependency>
+            <groupId>com.api</groupId>
+            <artifactId>common</artifactId>
+            <version>1.0-SNAPSHOT</version>
+        </dependency>
+        <!-- swagger2 -->
+        <dependency>
+            <groupId>io.springfox</groupId>
+            <artifactId>springfox-swagger2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>io.springfox</groupId>
+            <artifactId>springfox-swagger-ui</artifactId>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <resources>
+            <resource>
+                <directory>src/main/java</directory>
+                <includes>
+                    <include>**/*.xml</include>
+                </includes>
+            </resource>
+        </resources>
+    </build>
+
+</project>

+ 70 - 0
base/sql.sql

@@ -0,0 +1,70 @@
+create table sys_user
+(
+    id                bigint auto_increment primary key,
+    username          varchar(255)           null,
+    password          varchar(255)           not null,
+    mobile_number     varchar(15)            null comment '手机',
+    gender            tinyint    default '0' not null comment '性别',
+    email             varchar(50)            null comment '邮箱',
+    latest_login_time timestamp              null comment '最后登录的时间',
+    create_time       datetime comment '创建时间',
+    nickname          varchar(100) comment '创建时间',
+    avatar            varchar(300) comment '创建时间',
+    enable            tinyint    default 0   not null,
+    type              tinyint(2) default 2   null,
+    openid            varchar(200)           null,
+    constraint user_openId_uindex unique (openid)
+)
+    comment '用户表' charset = utf8mb4;
+
+
+create table sys_role
+(
+    id          mediumint(8) auto_increment
+        primary key,
+    name        varchar(255) not null,
+    description varchar(100) null,
+    constraint role_name_uindex
+        unique (name)
+)
+    comment '角色表' charset = utf8mb4;
+
+create table sys_power
+(
+    id   mediumint(8) auto_increment
+        primary key,
+    name varchar(255) not null,
+    url  varchar(255) not null,
+    pid  mediumint(8) null,
+    constraint power_name_url_pk
+        unique (name, url)
+)
+    charset = utf8mb4;
+
+create table sys_user_role
+(
+    role_id bigint not null,
+    user_id bigint not null,
+    primary key (role_id, user_id)
+)
+    charset = utf8mb4;
+
+create index user_role_user_id_fk
+    on sys_user_role (user_id);
+
+create table sys_role_power
+(
+    role_id  mediumint(8) not null,
+    power_id mediumint(8) not null,
+    primary key (role_id, power_id),
+    constraint role_power_power_id_fk
+        foreign key (power_id) references sys_power (id),
+    constraint role_power_role_id_fk
+        foreign key (role_id) references sys_role (id)
+)
+    charset = utf8mb4;
+create table sys_whitelist
+(
+    url varchar(100) not null
+        primary key
+);

+ 64 - 0
base/src/main/java/com/api/base/config/DateConverterConfig.java

@@ -0,0 +1,64 @@
+package com.api.base.config;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.core.convert.converter.Converter;
+import org.springframework.lang.Nullable;
+import org.springframework.stereotype.Component;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+@Component
+public class DateConverterConfig implements Converter<String, Date> {
+
+    private Logger logger = LoggerFactory.getLogger(this.getClass());
+
+    private static final List<String> formarts = new ArrayList<>(4);
+    static{
+        formarts.add("yyyy-MM");
+        formarts.add("yyyy-MM-dd");
+        formarts.add("yyyy-MM-dd hh:mm");
+        formarts.add("yyyy-MM-dd hh:mm:ss");
+    }
+    @Nullable
+    @Override
+    public Date convert(String source) {
+        String value = source.trim();
+        if ("".equals(value)) {
+            return null;
+        }
+        if(source.matches("^\\d{4}-\\d{1,2}$")){
+            return parseDate(source, formarts.get(0));
+        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")){
+            return parseDate(source, formarts.get(1));
+        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")){
+            return parseDate(source, formarts.get(2));
+        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")){
+            return parseDate(source, formarts.get(3));
+        }else {
+            throw new IllegalArgumentException("Invalid boolean value '" + source + "'");
+        }
+    }
+
+    /**
+     * 格式化日期
+     * @param dateStr String 字符型日期
+     * @param format String 格式
+     * @return Date 日期
+     */
+    private Date parseDate(String dateStr, String format) {
+        Date date=null;
+        try {
+            DateFormat dateFormat = new SimpleDateFormat(format);
+            date = dateFormat.parse(dateStr);
+        } catch (Exception e) {
+            logger.error("日期转换出错",e);
+        }
+        return date;
+    }
+
+}

+ 41 - 0
base/src/main/java/com/api/base/config/ExceptionHandler.java

@@ -0,0 +1,41 @@
+package com.api.base.config;
+
+import com.api.core.ServiceException;
+import com.api.core.response.Result;
+import com.api.core.response.ResultEnum;
+import com.api.core.response.ResultGenerator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.dao.DuplicateKeyException;
+import org.springframework.security.web.firewall.RequestRejectedException;
+import org.springframework.web.HttpRequestMethodNotSupportedException;
+import org.springframework.web.bind.MissingServletRequestParameterException;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.multipart.MaxUploadSizeExceededException;
+
+import javax.servlet.http.HttpServletRequest;
+import java.net.ConnectException;
+
+@ControllerAdvice
+public class ExceptionHandler {
+    private Logger logger = LoggerFactory.getLogger(this.getClass());
+
+    @org.springframework.web.bind.annotation.ExceptionHandler()
+    public @ResponseBody
+    Result defaultErrorHandler(HttpServletRequest req, Exception e) {
+        logger.error(req.getRequestURI(), e);
+        if (e instanceof MaxUploadSizeExceededException) return ResultGenerator.genResult(ResultEnum.UPLOADED_MAX);
+        if (e instanceof IllegalArgumentException) return ResultGenerator.genResult(ResultEnum.DATE_ENTRY_ERROR);
+        if (e instanceof MissingServletRequestParameterException)
+            return ResultGenerator.genResult(ResultEnum.PARAMS_LACK);
+        if (e instanceof ConnectException) return ResultGenerator.genResult(ResultEnum.CONNECT_EXCEPTION);
+        if (e instanceof HttpRequestMethodNotSupportedException)
+            return ResultGenerator.genExceptionResult(e);
+        if (e instanceof DuplicateKeyException)
+            return ResultGenerator.genResult(ResultEnum.DUPLICATE_KEY);
+        if (e instanceof RequestRejectedException) return ResultGenerator.genResult(ResultEnum.INTERNAL_SERVER_ERROR);
+        if (e instanceof ServiceException) return ResultGenerator.genExceptionResult(e);
+        return ResultGenerator.genExceptionResult();
+    }
+}

+ 101 - 0
base/src/main/java/com/api/base/config/InitRunner.java

@@ -0,0 +1,101 @@
+package com.api.base.config;
+
+import com.api.base.model.Power;
+import com.api.base.model.Role;
+import com.api.base.service.PowerService;
+import com.api.base.service.RoleService;
+import com.api.core.annotation.PowerEnable;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.CommandLineRunner;
+import org.springframework.stereotype.Component;
+import org.springframework.web.context.WebApplicationContext;
+import org.springframework.web.method.HandlerMethod;
+import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
+import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
+import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+/**
+ * Created by wanghuiwen on 17-2-12.
+ * 服务启动执行
+ */
+@Component
+public class InitRunner implements CommandLineRunner {
+    Logger logger = LoggerFactory.getLogger(this.getClass());
+    @Resource
+    private PowerService powerService;
+    @Resource
+    private RoleService roleService;
+
+    @Autowired
+    WebApplicationContext applicationContext;
+    @Autowired
+    private RequestMappingHandlerMapping requestMappingHandlerMapping;
+
+
+    public void run(String... strings) {
+        initPower();
+        initRole();
+    }
+
+    private void initRole() {
+        for (Role r : ProjectConstant.initRole) {
+            if (roleService.findBy("description", r.getDescription()) == null)
+                roleService.save(r);
+        }
+    }
+
+    private void initPower() {
+        Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
+
+        for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
+            Power power = new Power();
+            Power parent ;
+
+            String parentName = "";
+            String parentUrl = "";
+            if (m.getValue().getMethod().getDeclaringClass().isAnnotationPresent(PowerEnable.class)) {
+                parentName = m.getValue().getMethod().getDeclaringClass().getAnnotation(PowerEnable.class).name(); // 类名
+                parentUrl = m.getValue().getMethod().getDeclaringClass().getAnnotation(PowerEnable.class).url(); // 类名
+
+            }
+            if (!StringUtils.isEmpty(parentName)) {
+                parent = powerService.findBy("url", parentUrl);
+                if (parent == null) {
+                    parent = new Power();
+                    parent.setName(parentName);
+                    parent.setUrl(parentUrl);
+                    parent.setPid(0);
+                    powerService.save(parent);
+                }
+            }else {
+                parent=null;
+            }
+
+
+            PatternsRequestCondition p = m.getKey().getPatternsCondition();
+            for (String url : p.getPatterns()) {
+                if (StringUtils.isEmpty(url)) continue;
+                power.setUrl(url);
+            }
+
+            Power old = powerService.findBy("url", power.getUrl());
+            power.setName(m.getKey().getName() == null ? power.getUrl() : m.getKey().getName());
+            power.setPid(parent==null? -1 :parent.getId());
+            if (old == null) {
+                powerService.save(power);
+            } else {
+                old.setPid(parent==null? -1 :parent.getId());
+                old.setName(m.getKey().getName());
+                powerService.update(old);
+            }
+        }
+    }
+
+
+}

+ 89 - 0
base/src/main/java/com/api/base/config/MvcConfigurer.java

@@ -0,0 +1,89 @@
+package com.api.base.config;
+
+import com.api.common.config.UploadConfig;
+import com.api.core.annotation.condition.HttpsCondition;
+import org.apache.catalina.Context;
+import org.apache.tomcat.util.descriptor.web.SecurityCollection;
+import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
+import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.converter.HttpMessageConverter;
+import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
+import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
+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 javax.annotation.Resource;
+import java.util.List;
+
+/**
+ * Spring MVC 配置
+ */
+@Configuration
+public class MvcConfigurer implements WebMvcConfigurer {
+
+    private final Logger logger = LoggerFactory.getLogger(MvcConfigurer.class);
+
+    @Resource
+    private UploadConfig uploadConfig;
+
+
+    @Override
+    public void addResourceHandlers(ResourceHandlerRegistry registry) {
+
+        registry.addResourceHandler("/"+uploadConfig.getPrefix()+"**")
+                .addResourceLocations("file:" + uploadConfig.getFilePath());
+
+        registry.addResourceHandler("swagger-ui.html")
+                .addResourceLocations("classpath:/META-INF/resources/");
+
+        registry.addResourceHandler("/webjars/**")
+                .addResourceLocations("classpath:/META-INF/resources/webjars/");
+
+        registry.addResourceHandler("/**")
+                .addResourceLocations("classpath:/META-INF/resources/")
+                .addResourceLocations("classpath:/resources/")
+                .addResourceLocations("classpath:/static/");
+
+        WebMvcConfigurer.super.addResourceHandlers(registry);
+    }
+
+    //解决跨域问题
+    @Override
+    public void addCorsMappings(CorsRegistry registry) {
+        registry.addMapping("/**")
+                .allowedHeaders("*")
+                .allowedMethods("*")
+                .allowedOrigins("*");
+    }
+
+    @Override
+    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
+        Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.xml();
+        builder.indentOutput(true);
+        converters.add(new MappingJackson2XmlHttpMessageConverter(builder.build()));
+    }
+
+    @Conditional(HttpsCondition.class)
+    @Bean
+    public ServletWebServerFactory servletContainer() {
+        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
+            @Override
+            protected void postProcessContext(Context context) {
+                SecurityConstraint constraint = new SecurityConstraint();
+                constraint.setUserConstraint("CONFIDENTIAL");
+                SecurityCollection collection = new SecurityCollection();
+                collection.addPattern("/*");
+                constraint.addCollection(collection);
+                context.addConstraint(constraint);
+            }
+        };
+        return tomcat;
+    }
+}

+ 69 - 0
base/src/main/java/com/api/base/config/MybatisConfigurer.java

@@ -0,0 +1,69 @@
+package com.api.base.config;
+
+import com.github.pagehelper.PageInterceptor;
+import org.apache.ibatis.plugin.Interceptor;
+import org.apache.ibatis.session.SqlSessionFactory;
+import org.mybatis.spring.SqlSessionFactoryBean;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
+import org.springframework.core.io.support.ResourcePatternResolver;
+import tk.mybatis.spring.mapper.MapperScannerConfigurer;
+
+import javax.sql.DataSource;
+import java.util.Properties;
+
+import static com.api.base.config.ProjectConstant.*;
+
+
+/**
+ * Mybatis & Mapper & PageHelper 配置
+ */
+@Configuration
+public class MybatisConfigurer {
+
+    Logger logger = LoggerFactory.getLogger(this.getClass());
+
+    @Bean
+    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
+        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
+        org.apache.ibatis.session.Configuration configuration =new org.apache.ibatis.session.Configuration();
+        configuration.setCallSettersOnNulls(true);
+
+        factory.setDataSource(dataSource);
+        factory.setConfiguration(configuration);
+        factory.setTypeAliasesPackage(MODEL_PACKAGE);
+
+        //配置分页插件,详情请查阅官方文档
+        PageInterceptor pageInterceptor = new PageInterceptor();
+        Properties properties = new Properties();
+        pageInterceptor.setProperties(properties);
+
+
+        //添加插件
+        factory.setPlugins(new Interceptor[]{pageInterceptor});
+
+        //添加XML目录
+        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
+        factory.setMapperLocations(resolver.getResources("classpath*:com/api/**/mapper/*.xml"));
+        return factory.getObject();
+    }
+
+    @Bean
+    public MapperScannerConfigurer mapperScannerConfigurer() {
+        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
+        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
+        mapperScannerConfigurer.setBasePackage(MAPPER_PACKAGE);
+        //配置通用Mapper,详情请查阅官方文档
+        Properties properties = new Properties();
+        properties.setProperty("mappers", MAPPER_INTERFACE_REFERENCE);
+        properties.setProperty("notEmpty", "false");//insert、update是否判断字符串类型!='' 即 test="str != null"表达式内是否追加 and str != ''
+        properties.setProperty("IDENTITY", "MYSQL");
+        mapperScannerConfigurer.setProperties(properties);
+        return mapperScannerConfigurer;
+    }
+
+}
+

+ 18 - 0
base/src/main/java/com/api/base/config/ProjectConstant.java

@@ -0,0 +1,18 @@
+package com.api.base.config;
+
+
+import com.api.base.model.Role;
+
+/**
+ * 项目常量
+ */
+public final class ProjectConstant {
+    private static final String BASE_PACKAGE = "com.api";//项目基础包名称,根据自己公司的项目修改
+
+    static final String MODEL_PACKAGE = BASE_PACKAGE + ".model";//Model所在包
+    static final String MAPPER_PACKAGE = BASE_PACKAGE + ".dao";//Mapper所在包
+    static final String MAPPER_INTERFACE_REFERENCE = "com.api.core.Mapper";//Mapper插件基础接口的完全限定名
+    public static final String ROLE_ADMIN="admin";
+    public static final String ROLE_USER="user";
+    static final Role[] initRole={new Role("管理员",ROLE_ADMIN),new Role("普通用户",ROLE_USER)};
+}

+ 58 - 0
base/src/main/java/com/api/base/config/auth/AccessManager.java

@@ -0,0 +1,58 @@
+package com.api.base.config.auth;
+
+import com.api.base.config.ProjectConstant;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.access.AccessDecisionManager;
+import org.springframework.security.access.AccessDeniedException;
+import org.springframework.security.access.ConfigAttribute;
+import org.springframework.security.authentication.InsufficientAuthenticationException;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.GrantedAuthority;
+
+import java.util.Collection;
+import java.util.Iterator;
+
+public class AccessManager  implements AccessDecisionManager {
+    private Logger logger = LoggerFactory.getLogger(this.getClass());
+    /**
+     * 方法是判定是否拥有权限的决策方法,
+     * (1)authentication 是释CustomUserService中循环添加到 GrantedAuthority 对象中的权限信息集合.
+     * (2)object 包含客户端发起的请求的requset信息,可转换为 HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
+     * (3)configAttributes 为MyFilterInvocationSecurityMetadataSource的getAttributes(Object object)这个方法返回的结果,此方法是为了判定用户请求的url 是否在权限表中,如果在权限表中,则返回给 decide 方法
+     */
+    @Override
+    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
+            throws AccessDeniedException, InsufficientAuthenticationException {
+
+        if(configAttributes == null  || configAttributes.size()==0) {
+            throw new AccessDeniedException("permission denied");
+        }
+        ConfigAttribute cfa;
+        String needRole;
+        //遍历基于URL获取的权限信息和用户自身的角色信息进行对比.
+        for(Iterator<ConfigAttribute> it = configAttributes.iterator(); it.hasNext();) {
+            cfa = it.next();
+            needRole = cfa.getAttribute();
+            //authentication 为CustomUserDetailService中添加的权限信息.
+            for(GrantedAuthority grantedAuthority:authentication.getAuthorities()) {
+                if(needRole.equals(grantedAuthority.getAuthority())||grantedAuthority.getAuthority().equals(ProjectConstant.ROLE_ADMIN)) {
+                    logger.info(authentication.getName()+":"+needRole);
+                    return;
+                }
+            }
+        }
+        logger.error(authentication.getName()+":访问非法权限:"+configAttributes);
+        throw new AccessDeniedException("permission denied");
+    }
+    @Override
+    public boolean supports(ConfigAttribute attribute) {
+        return true;
+    }
+
+    @Override
+    public boolean supports(Class<?> clazz) {
+        return true;
+    }
+
+}

+ 80 - 0
base/src/main/java/com/api/base/config/auth/JwtAuthenticationTokenFilter.java

@@ -0,0 +1,80 @@
+package com.api.base.config.auth;
+
+import com.api.base.config.auth.service.DetailsService;
+import com.api.common.JSONUtils;
+import com.api.core.response.Result;
+import com.api.core.response.ResultEnum;
+import com.api.core.response.ResultGenerator;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.data.redis.RedisConnectionFailureException;
+import org.springframework.http.HttpStatus;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.core.userdetails.UserDetails;
+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
+public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
+    @Value("${jwt.header}")
+    private String tokenHeader;
+    @Value("${jwt.tokenHead}")
+    private String tokenHead;
+
+    private DetailsService userDetailsService;
+    private JwtTokenUtil jwtTokenUtil;
+
+    @Autowired
+    public JwtAuthenticationTokenFilter(DetailsService userDetailsService, JwtTokenUtil jwtTokenUtil) {
+        this.userDetailsService = userDetailsService;
+        this.jwtTokenUtil = jwtTokenUtil;
+
+    }
+
+    @Override
+    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
+        try {
+
+        String authHeader = request.getHeader(tokenHeader);
+        if (authHeader != null && authHeader.startsWith(tokenHead)) {
+            String authToken = authHeader.substring(tokenHead.length());
+
+                    String username = jwtTokenUtil.getUsernameFromToken(authToken);
+                    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
+                        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
+                        if (jwtTokenUtil.validateToken(authToken, username)) {
+                            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
+                            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
+                            SecurityContextHolder.getContext().setAuthentication(authentication);
+                        }
+                    }
+
+        }
+        filterChain.doFilter(request, response);
+        }catch (Exception e){
+            logger.error("TokenFilterException",e);
+            response.setHeader("Content-Type", "application/json;charset=utf-8");
+            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
+            Result result = ResultGenerator.genExceptionResult();
+            if(e instanceof RedisConnectionFailureException){
+                result = ResultGenerator.genResult(ResultEnum.REDIS_CONNECTION_FAILUR);
+            }
+            response.getWriter().write(JSONUtils.obj2json(result));
+            response.getWriter().flush();
+        }
+    }
+
+
+
+
+
+
+}

+ 132 - 0
base/src/main/java/com/api/base/config/auth/JwtTokenUtil.java

@@ -0,0 +1,132 @@
+package com.api.base.config.auth;
+
+import io.jsonwebtoken.Claims;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.SignatureAlgorithm;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+import java.io.Serializable;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+@Component
+public class JwtTokenUtil  implements Serializable {
+    private static final String CLAIM_KEY_USERNAME = "sub";
+    private static final String CLAIM_KEY_TYPE = "type";
+    private static final String CLAIM_KEY_CREATED = "created";
+    private static final long serialVersionUID = -8305152446124853696L;
+
+    /**
+     * 密钥
+     */
+    @Value("${jwt.secret}")
+    private String secret;
+    /**
+     * //有效期
+     */
+    @Value("${jwt.expiration}")
+    private Long expiration;
+
+    @Value("${jwt.tokenHead}")
+    private String tokenHead;
+
+    /**
+     * 从数据声明生成令牌
+     *
+     * @param claims 数据声明
+     * @return 令牌
+     */
+    private String generateToken(Map<String, Object> claims) {
+        Date expirationDate = new Date(System.currentTimeMillis() + expiration * 1000);
+        return Jwts.builder().setClaims(claims).setExpiration(expirationDate).signWith(SignatureAlgorithm.HS512, secret).compact();
+    }
+
+    /**
+     * 从令牌中获取数据声明
+     *
+     * @param token 令牌
+     * @return 数据声明
+     */
+    private Claims getClaimsFromToken(String token) {
+        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
+
+    }
+
+    /**
+     * 生成令牌
+     *
+     * @return 令牌
+     */
+    public String generateToken(String username) {
+        Map<String, Object> claims = new HashMap<>();
+        claims.put(CLAIM_KEY_USERNAME, username);
+        claims.put(CLAIM_KEY_CREATED, new Date());
+        return generateToken(claims);
+    }
+
+    /**
+     * 从令牌中获取用户名
+     *
+     * @param token 令牌
+     * @return 用户名
+     */
+    String getUsernameFromToken(String token) {
+        Claims claims = getClaimsFromToken(token);
+        return claims.getSubject();
+    }
+
+    /**
+     * 从令牌中获取用户类型
+     *
+     * @param token 令牌
+     * @return 用户名
+     */
+    public String getTypeFromToken(String token) {
+        String type;
+        try {
+            Claims claims = getClaimsFromToken(token);
+            type = (String) claims.get(CLAIM_KEY_TYPE);
+        } catch (Exception e) {
+            type = null;
+        }
+        return type;
+    }
+
+    /**
+     * 判断令牌是否过期
+     *
+     * @param token 令牌
+     * @return 是否过期
+     */
+    private Boolean isTokenExpired(String token) {
+            Claims claims = getClaimsFromToken(token);
+            Date expiration = claims.getExpiration();
+            return expiration.before(new Date());
+    }
+
+    /**
+     * 刷新令牌
+     *
+     * @param token 原令牌
+     * @return 新令牌
+     */
+    public String refreshToken(String token) {
+            Claims claims = getClaimsFromToken(token);
+            claims.put(CLAIM_KEY_CREATED, new Date());
+        return generateToken(claims);
+    }
+
+    /**
+     * 验证令牌
+     *
+     * @param token       令牌
+     * @return 是否有效
+     */
+    Boolean validateToken(String token, String userName) {
+        String username = getUsernameFromToken(token);
+        return (username.equals(userName) && !isTokenExpired(token));
+    }
+
+}

+ 91 - 0
base/src/main/java/com/api/base/config/auth/PowerSource.java

@@ -0,0 +1,91 @@
+package com.api.base.config.auth;
+
+import com.api.base.model.Power;
+import com.api.base.model.SysWhitelist;
+import com.api.base.service.PowerService;
+import com.api.base.service.SysWhitelistService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.access.ConfigAttribute;
+import org.springframework.security.web.FilterInvocation;
+import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
+import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.Collection;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class PowerSource implements FilterInvocationSecurityMetadataSource {
+    Logger logger =  LoggerFactory.getLogger(this.getClass());
+
+    private PowerService powerService;
+
+    private SysWhitelistService sysWhitelistService;
+
+    public PowerSource(PowerService powerService,SysWhitelistService sysWhitelistService) {
+        this.powerService = powerService;
+        this.sysWhitelistService=sysWhitelistService;
+    }
+
+    /**
+     * 此方法是为了判定用户请求的url 是否在权限表中,如果在权限表中,则返回给 decide 方法。
+     * object-->FilterInvocation
+     */
+    @Override
+    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
+        List<Power> powers =powerService.findAll();
+        FilterInvocation filterInvocation = (FilterInvocation) object;
+
+        if (isMatcherAllowedRequest(filterInvocation)) return null ; //return null 表示允许访问,不做拦截
+        HttpServletRequest request = filterInvocation.getHttpRequest();
+        String resUrl;
+        //URL规则匹配.
+        AntPathRequestMatcher matcher;
+        for(Power p : powers) {
+            resUrl=p.getUrl();
+            matcher = new AntPathRequestMatcher(resUrl);
+            if(matcher.matches(request)) {
+                return org.springframework.security.access.SecurityConfig.createList(p.getUrl());
+            }
+        }
+        //没有有匹配到,需要指定相应的角色:
+        return org.springframework.security.access.SecurityConfig.createList(filterInvocation.getRequestUrl());
+    }
+
+
+
+
+    /**
+     * 判断当前请求是否在允许请求的范围内
+     * @param fi 当前请求
+     * @return 是否在范围中
+     */
+    private boolean isMatcherAllowedRequest(FilterInvocation fi){
+        return allowedRequest().stream().map(AntPathRequestMatcher::new)
+                .filter(requestMatcher -> requestMatcher.matches(fi.getHttpRequest()))
+                .toArray().length > 0;
+    }
+
+    /**
+     *
+     * @return 定义允许请求的列表
+     */
+    private List<String> allowedRequest(){
+        List<SysWhitelist> whitelists=sysWhitelistService.selectAll();
+
+        return whitelists.stream()
+                .map(SysWhitelist::getUrl)
+                .collect(Collectors.toList());
+    }
+
+    @Override
+    public Collection<ConfigAttribute> getAllConfigAttributes() {
+        return null;
+    }
+
+    @Override
+    public boolean supports(Class<?> clazz) {
+        return true;
+    }
+}

+ 132 - 0
base/src/main/java/com/api/base/config/auth/SecurityConfig.java

@@ -0,0 +1,132 @@
+package com.api.base.config.auth;
+
+import com.api.base.config.auth.handler.*;
+import com.api.base.config.auth.service.DetailsService;
+import com.api.base.model.SysWhitelist;
+import com.api.base.service.PowerService;
+import com.api.base.service.SysWhitelistService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.HttpMethod;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.config.BeanIds;
+import org.springframework.security.config.annotation.ObjectPostProcessor;
+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.access.intercept.FilterSecurityInterceptor;
+import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
+import org.springframework.web.cors.CorsConfiguration;
+import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
+import org.springframework.web.filter.CorsFilter;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+
+@Configuration
+@EnableWebSecurity
+@EnableGlobalMethodSecurity(prePostEnabled = true)
+public class SecurityConfig extends WebSecurityConfigurerAdapter {
+    @Autowired
+    private PowerService powerService;
+    @Resource
+    private SysWhitelistService sysWhitelistService;
+
+    @Bean
+    public CorsFilter corsFilter() {
+        CorsConfiguration corsConfiguration = new CorsConfiguration();
+        corsConfiguration.setAllowCredentials(true);
+        corsConfiguration.addAllowedOrigin("*");
+        corsConfiguration.addAllowedHeader("*");
+        corsConfiguration.addAllowedMethod("*");
+        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
+        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
+        return new CorsFilter(urlBasedCorsConfigurationSource);
+    }
+    @Autowired
+    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
+
+
+    @Autowired
+    private DetailsService DetailsService;
+
+    @Autowired
+    private JwtTokenUtil jwtTokenUtil;
+
+    /**
+     * 认证
+     *
+     * @param auth
+     * @throws Exception
+     */
+    @Override
+    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+        auth.userDetailsService(this.DetailsService).passwordEncoder(passwordEncoder());
+    }
+
+
+    // 装载BCrypt密码编码器
+    @Bean
+    public PasswordEncoder passwordEncoder() {
+        return new BCryptPasswordEncoder();
+    }
+
+    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
+    @Override
+    public AuthenticationManager authenticationManagerBean() throws Exception {
+        return super.authenticationManagerBean();
+    }
+
+    @Override
+    protected void configure(HttpSecurity http) throws Exception {
+        http.headers().frameOptions().disable();
+        List<SysWhitelist> whitelists=sysWhitelistService.selectAll();
+
+        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
+                .and()
+                .authorizeRequests()
+                .antMatchers(HttpMethod.OPTIONS,
+                        whitelists.stream().map(SysWhitelist::getUrl).toArray(String[]::new)
+                        ).permitAll()
+                .withObjectPostProcessor(new MyObjectPostProcessor())
+                .anyRequest().authenticated()
+                .and().exceptionHandling()
+                .authenticationEntryPoint(new GoAuthenticationEntryPoint())
+                .accessDeniedHandler(new GoAccessDeniedHandler())
+                .and()
+                .formLogin()
+                .loginProcessingUrl("/login")
+                .usernameParameter("username")
+                .passwordParameter("password")
+                .successHandler(new GoAuthenticationSuccessHandler(jwtTokenUtil))
+                .failureHandler(new GoAuthenticationFailureHandler())
+                .and().logout().logoutUrl("/logout")
+                .logoutSuccessHandler(new GoLogoutSuccessHandler())
+                .and().cors().and().csrf().disable();
+        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
+    }
+
+    private class MyObjectPostProcessor implements ObjectPostProcessor<FilterSecurityInterceptor> {
+        @Override
+        public <O extends FilterSecurityInterceptor> O postProcess(O fsi) {
+            fsi.setSecurityMetadataSource(new PowerSource(powerService,sysWhitelistService));
+            fsi.setAccessDecisionManager(new AccessManager());
+            return fsi;
+        }
+
+    }
+
+    @Override
+    public void configure(WebSecurity web) throws Exception {
+
+        super.configure(web);
+    }
+}

+ 24 - 0
base/src/main/java/com/api/base/config/auth/handler/GoAccessDeniedHandler.java

@@ -0,0 +1,24 @@
+package com.api.base.config.auth.handler;
+
+import com.api.common.JSONUtils;
+import com.api.core.response.Result;
+import com.api.core.response.ResultGenerator;
+import org.springframework.http.HttpStatus;
+import org.springframework.security.access.AccessDeniedException;
+import org.springframework.security.web.access.AccessDeniedHandler;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+
+public class GoAccessDeniedHandler implements AccessDeniedHandler {
+    @Override
+    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException {
+        Result result = ResultGenerator.genForbiddenResult();
+        httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");
+        httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());
+        httpServletResponse.getWriter().write(JSONUtils.obj2json(result));
+        httpServletResponse.getWriter().flush();
+    }
+}

+ 34 - 0
base/src/main/java/com/api/base/config/auth/handler/GoAuthenticationEntryPoint.java

@@ -0,0 +1,34 @@
+package com.api.base.config.auth.handler;
+
+import com.api.common.JSONUtils;
+import com.api.core.response.Result;
+import com.api.core.response.ResultGenerator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.http.HttpStatus;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.AuthenticationEntryPoint;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+
+/**
+ * 它负责启动未经过身份验证的用户的身份验证过程(当他们试图访问受保护的资源
+ */
+public class GoAuthenticationEntryPoint  implements AuthenticationEntryPoint {
+
+    private Logger logger = LoggerFactory.getLogger(this.getClass());
+
+    @Override
+    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
+        Result result = ResultGenerator.genForbiddenResult();
+        logger.warn("身份验证出错",e);
+        httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");
+        httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());
+        httpServletResponse.getWriter().write(JSONUtils.obj2json(result));
+        httpServletResponse.getWriter().flush();
+    }
+
+}

+ 32 - 0
base/src/main/java/com/api/base/config/auth/handler/GoAuthenticationFailureHandler.java

@@ -0,0 +1,32 @@
+package com.api.base.config.auth.handler;
+
+import com.api.common.JSONUtils;
+import com.api.core.response.Result;
+import com.api.core.response.ResultEnum;
+import com.api.core.response.ResultGenerator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.http.HttpStatus;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.authentication.AuthenticationFailureHandler;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+public class GoAuthenticationFailureHandler implements AuthenticationFailureHandler {
+    private Logger logger = LoggerFactory.getLogger(this.getClass());
+
+    @Override
+    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
+
+        logger.warn("身份验证出错",e);
+
+        Result result = ResultGenerator.genResult(ResultEnum.LOGIN_FAIL);
+        httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");
+        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
+        httpServletResponse.getWriter().write(JSONUtils.obj2json(result));
+        httpServletResponse.getWriter().flush();
+    }
+
+}

+ 53 - 0
base/src/main/java/com/api/base/config/auth/handler/GoAuthenticationSuccessHandler.java

@@ -0,0 +1,53 @@
+package com.api.base.config.auth.handler;
+
+import com.api.core.config.AuthUser;
+import com.api.base.config.auth.JwtTokenUtil;
+import com.api.common.JSONUtils;
+import com.api.core.response.Result;
+import com.api.core.response.ResultEnum;
+import com.api.core.response.ResultGenerator;
+import org.springframework.http.HttpStatus;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
+import org.springframework.stereotype.Component;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.Console;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+@Component
+public class GoAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
+
+
+    private JwtTokenUtil jwtTokenUtil;
+
+    public GoAuthenticationSuccessHandler(JwtTokenUtil jwtTokenUtil) {
+        this.jwtTokenUtil = jwtTokenUtil;
+    }
+
+    @Override
+    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
+        httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");
+
+        AuthUser userDetails = (AuthUser) authentication.getPrincipal();
+        Map<String, Object> res = new HashMap<>();
+
+        String jwtToken = jwtTokenUtil.generateToken(userDetails.getUsername());
+        System.out.println(jwtToken);
+        userDetails.setPassword("");
+        res.put("info",userDetails);
+        res.put("token", jwtToken);
+
+        Result result = ResultGenerator.genResultAndData(ResultEnum.LOGIN_SUCCESS,res);
+
+        httpServletResponse.setStatus(HttpStatus.OK.value());
+        httpServletResponse.getWriter().write(JSONUtils.obj2json(result));
+        httpServletResponse.getWriter().flush();
+
+    }
+
+
+}

+ 27 - 0
base/src/main/java/com/api/base/config/auth/handler/GoLogoutSuccessHandler.java

@@ -0,0 +1,27 @@
+package com.api.base.config.auth.handler;
+
+import com.api.common.JSONUtils;
+import com.api.core.response.Result;
+import com.api.core.response.ResultEnum;
+import com.api.core.response.ResultGenerator;
+import org.springframework.http.HttpStatus;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+public class GoLogoutSuccessHandler implements LogoutSuccessHandler {
+    @Override
+    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
+        Result result = ResultGenerator.genResult(ResultEnum.LOGIN_OUT_SUCCESS);
+
+        httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");
+        httpServletResponse.setStatus(HttpStatus.OK.value());
+        httpServletResponse.getWriter().write(JSONUtils.obj2json(result));
+        httpServletResponse.getWriter().flush();
+
+    }
+
+}

+ 60 - 0
base/src/main/java/com/api/base/config/auth/service/DetailsService.java

@@ -0,0 +1,60 @@
+package com.api.base.config.auth.service;
+
+import com.api.core.config.AuthUser;
+import com.api.base.model.Power;
+import com.api.base.model.Role;
+import com.api.base.model.User;
+import com.api.base.service.PowerService;
+import com.api.base.service.UserService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import org.springframework.stereotype.Service;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@Service
+public class DetailsService implements UserDetailsService {
+
+    @Autowired
+    private UserService userService;
+
+    @Autowired
+    private PowerService powerService;
+
+    @Override
+    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
+        User user = userService.findBy("username",s);
+        if(user==null){
+            throw new UsernameNotFoundException("用户不存在");
+        }
+
+        List<Role> roles = userService.getRole(user.getId());
+        List<GrantedAuthority> authorities = new ArrayList<>();
+        List<String> rolestr = new ArrayList<>();
+
+
+        List<Power> powers = new ArrayList<>();
+        for (Role r : roles) {
+            rolestr.add(r.getDescription());
+            authorities.add(new SimpleGrantedAuthority(r.getDescription()));
+            List<Power> powers1 = powerService.getByRole(r.getId());
+            if (powers1 != null) {
+                powers.addAll(powers1);
+            }
+        }
+
+        if (powers.size() > 0) {
+            for (Power p : powers) {
+                authorities.add(new SimpleGrantedAuthority(p.getUrl()));
+            }
+        }
+
+        return new AuthUser(user.getUsername(), user.getPassword(), authorities, rolestr, user.getId(), user.getType(),user.getNickname(),user.getAvatar(),user.getAlias());
+
+    }
+}

+ 34 - 0
base/src/main/java/com/api/base/config/cache/RedisConfig.java

@@ -0,0 +1,34 @@
+package com.api.base.config.cache;
+
+import org.springframework.cache.annotation.CachingConfigurerSupport;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.redis.cache.RedisCacheConfiguration;
+import org.springframework.data.redis.connection.RedisConnectionFactory;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.serializer.RedisSerializationContext;
+import org.springframework.data.redis.serializer.StringRedisSerializer;
+
+@Configuration
+public class RedisConfig extends CachingConfigurerSupport {
+    @Bean
+    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
+        RedisTemplate redisTemplate=new RedisTemplate();
+        redisTemplate.setKeySerializer(new StringRedisSerializer());
+        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
+
+        redisTemplate.setHashValueSerializer(new SerializeUtils());
+        redisTemplate.setValueSerializer(new SerializeUtils());
+        redisTemplate.setConnectionFactory(factory);
+        return redisTemplate;
+    }
+    @Bean
+    public RedisCacheConfiguration redisCacheConfiguration(){
+        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
+        configuration = configuration.
+                serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new SerializeUtils()));
+        return configuration;
+    }
+
+
+}

+ 69 - 0
base/src/main/java/com/api/base/config/cache/SerializeUtils.java

@@ -0,0 +1,69 @@
+package com.api.base.config.cache;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.data.redis.serializer.RedisSerializer;
+
+import java.io.*;
+
+public class SerializeUtils implements RedisSerializer {
+
+    private static Logger logger = LoggerFactory.getLogger(SerializeUtils.class);
+
+    private static boolean isEmpty(byte[] data) {
+        return (data == null || data.length == 0);
+    }
+
+    /**
+     * 序列化
+     */
+    @Override
+    public byte[] serialize(Object object) {
+        byte[] result = null;
+
+        if (object == null) {
+            return new byte[0];
+        }
+        try (
+                ByteArrayOutputStream byteStream = new ByteArrayOutputStream(128);
+                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream)
+        ){
+
+            if (!(object instanceof Serializable)) {
+                throw new IllegalArgumentException(SerializeUtils.class.getSimpleName() + " requires a Serializable payload " +
+                        "but received an object of type [" + object.getClass().getName() + "]");
+            }
+
+            objectOutputStream.writeObject(object);
+            objectOutputStream.flush();
+            result =  byteStream.toByteArray();
+        } catch (Exception ex) {
+            logger.error("Failed to serialize",ex);
+        }
+        return result;
+    }
+
+    /**
+     * 反序列化
+     */
+    @Override
+    public Object deserialize(byte[] bytes) {
+
+        Object result = null;
+
+        if (isEmpty(bytes)) {
+            return null;
+        }
+
+        try (
+                ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
+                ObjectInputStream objectInputStream = new ObjectInputStream(byteStream)
+        ){
+            result = objectInputStream.readObject();
+        } catch (Exception e) {
+            logger.error("Failed to deserialize",e);
+        }
+        return result;
+    }
+
+}

+ 67 - 0
base/src/main/java/com/api/base/controll/PowerController.java

@@ -0,0 +1,67 @@
+package com.api.base.controll;
+
+
+import com.api.base.dto.ElTree;
+import com.api.base.model.Power;
+import com.api.base.service.PowerService;
+import com.api.core.controller.Ctrl;
+import com.api.core.annotation.PowerEnable;
+import com.api.core.response.Result;
+import com.api.core.response.ResultGenerator;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+
+/**
+ * Created by CodeGenerator on 2019/03/25.
+ */
+@PowerEnable(name = "权限管理",url = "/power")
+@Api(value = "权限管理", tags = {"权限管理"})
+@RestController
+@RequestMapping("/power")
+public class PowerController extends Ctrl {
+    @Resource
+    private PowerService powerService;
+
+    @ApiOperation(value = "权限树列表", tags = {"权限管理"}, notes = "权限树列表")
+    @PostMapping(value = "/list", name = "权限树列表")
+    public Result list() {
+        List<Power> powers = powerService.findAll();
+
+        Map<Integer, List<Power>> res = powers.stream().collect(Collectors.groupingBy(Power::getPid));
+
+        List<Power> parent = res.get(0);
+
+
+        List<ElTree<Power>> elTrees = new ArrayList<>();
+
+        for (Power p: parent) {
+            ElTree<Power> elTree = new ElTree<>();
+            elTree.setId(p.getId());
+            elTree.setName(p.getName());
+            elTree.setChildren(new ArrayList<>());
+            elTrees.add(elTree);
+        }
+
+        for (Integer key:res.keySet()) {
+            if(key!=0){
+                for (ElTree<Power> e:elTrees) {
+                    if(e.getId().equals(key)){
+                       e.getChildren().addAll(res.get(key));
+                    }
+                }
+            }
+        }
+
+        return ResultGenerator.genSuccessResult(elTrees);
+    }
+}

+ 93 - 0
base/src/main/java/com/api/base/controll/RoleController.java

@@ -0,0 +1,93 @@
+package com.api.base.controll;
+
+
+import com.api.base.model.Role;
+import com.api.base.service.PowerService;
+import com.api.base.service.RoleService;
+import com.api.core.controller.Ctrl;
+import com.api.core.annotation.PowerEnable;
+import com.api.core.response.Result;
+import com.api.core.response.ResultGenerator;
+import com.github.pagehelper.PageHelper;
+import com.github.pagehelper.PageInfo;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiImplicitParams;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.cache.annotation.CacheEvict;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import tk.mybatis.mapper.entity.Condition;
+import tk.mybatis.mapper.entity.Example;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+
+/**
+* Created by CodeGenerator on 2019/03/25.
+*/
+@PowerEnable(name = "角色管理",url = "/role")
+@Api(value = "角色管理", tags = {"角色管理"})
+@RestController
+@RequestMapping("/role")
+public class RoleController extends Ctrl {
+    @Resource
+    private RoleService roleService;
+    @Resource
+    private PowerService powerService;
+
+    @ApiOperation(value = "添加角色", tags = {"角色管理"}, notes = "添加角色")
+    @PostMapping(value = "/add",name = "添加角色")
+    public Result add(Role role) {
+        roleService.save(role);
+        return ResultGenerator.genSuccessResult();
+    }
+
+
+    @ApiOperation(value = "添加角色", tags = {"角色管理"}, notes = "添加角色")
+    @ApiImplicitParams({
+            @ApiImplicitParam(name = "where", value = "条件json", dataType = "String", paramType = "query"),
+            @ApiImplicitParam(name = "page", value = "页数", dataType = "Integer", paramType = "query"),
+            @ApiImplicitParam(name = "size", value = "条数", dataType = "Integer", paramType = "query"),
+    })
+    @PostMapping(value = "/list",name = "角色列表")
+    public Result list(@RequestParam String  where , @RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "0") Integer size) {
+        PageHelper.startPage(page, size);
+
+        Condition c= new Condition(Role.class);
+        Example.Criteria criteria = c.createCriteria();
+
+        buildWhere(where, criteria);
+
+        List<Role> list = roleService.findByCondition(c);
+        PageInfo<Role> pageInfo = new PageInfo<>(list);
+        return ResultGenerator.genSuccessResult(pageInfo);
+    }
+
+
+    @ApiOperation(value = "角色添加权限", tags = {"角色管理"}, notes = "角色添加权限")
+    @ApiImplicitParams({
+            @ApiImplicitParam(name = "powers", value = "权限json", dataType = "String", paramType = "query"),
+            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "Long", paramType = "query"),
+    })
+    @PostMapping(value = "/add/power",name = "角色添加权限")
+    @CacheEvict(value = "power",key = "#roleId")
+    public Result addPower(String powers, Long roleId){
+
+        roleService.addPower( powers,roleId);
+        return ResultGenerator.genSuccessResult();
+    }
+
+    @ApiOperation(value = "获取角色权限", tags = {"角色管理"}, notes = "获取角色权限")
+    @ApiImplicitParams({
+        @ApiImplicitParam(name = "roleId", value = "角色id", dataType = "Long", paramType = "query"),
+    })
+    @PostMapping(value = "/get/power",name = "获取角色权限")
+    public Result getPowers(Long roleId){
+        List powers =  powerService.getByRole(roleId);
+        return ResultGenerator.genSuccessResult(powers);
+    }
+}

+ 71 - 0
base/src/main/java/com/api/base/controll/SysWhitelistController.java

@@ -0,0 +1,71 @@
+package com.api.base.controll;
+import com.api.core.controller.Ctrl;
+import com.api.core.response.Result;
+import com.api.core.response.ResultGenerator;
+import com.api.base.model.SysWhitelist;
+import com.api.base.service.SysWhitelistService;
+import com.github.pagehelper.PageHelper;
+import com.github.pagehelper.PageInfo;
+import org.springframework.cache.annotation.CacheEvict;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import com.api.core.annotation.PowerEnable;
+import io.swagger.annotations.*;
+
+
+
+/**
+* Created by CodeGenerator on 2019/11/08.
+*/
+@PowerEnable(name = "白名单",url = "/sys/whitelist")
+@Api(value = "白名单", tags = {"白名单"})
+@RestController
+@RequestMapping("/sys/whitelist")
+public class SysWhitelistController extends Ctrl{
+    @Resource
+    private SysWhitelistService sysWhitelistService;
+
+    @ApiOperation(value = "白名单添加", tags = {"白名单"}, notes = "白名单添加")
+    @PostMapping(value="/add",name="白名单添加")
+    @CacheEvict(value = "whiteList",key = "'whiteList'")
+    public Result add(@ApiParam SysWhitelist sysWhitelist) {
+        sysWhitelistService.save(sysWhitelist);
+        return ResultGenerator.genSuccessResult();
+    }
+
+    @ApiOperation(value = "白名单删除", tags = {"白名单"}, notes = "白名单删除")
+    @ApiImplicitParams({
+        @ApiImplicitParam(name = "id",required=true, value = "白名单id", dataType = "Long", paramType = "query")
+    })
+    @PostMapping(value="/delete",name="白名单删除")
+    @CacheEvict(value = "whiteList",key = "'whiteList'")
+    public Result delete(@RequestParam String id) {
+        sysWhitelistService.deleteById(id);
+        return ResultGenerator.genSuccessResult();
+    }
+
+    @ApiOperation(value = "白名单修改", tags = {"白名单"}, notes = "白名单修改,对象主键必填")
+    @PostMapping(value="/update",name="白名单修改")
+    @CacheEvict(value = "whiteList",key = "'whiteList'")
+    public Result update(@ApiParam String url,
+                         @ApiParam String id) {
+
+        return sysWhitelistService.update(url,id);
+    }
+
+    @ApiOperation(value = "白名单列表信息", tags = {"白名单"}, notes = "白名单列表信息")
+    @PostMapping(value="/list",name="白名单列表信息")
+    public Result list(@RequestParam(defaultValue = "0") Integer page,
+                       @RequestParam(defaultValue = "10") Integer size) {
+        PageHelper.startPage(page, size);
+
+        List<SysWhitelist> list = sysWhitelistService.selectAll();
+        PageInfo<SysWhitelist> pageInfo = new PageInfo<>(list);
+        return ResultGenerator.genSuccessResult(pageInfo);
+    }
+}

+ 142 - 0
base/src/main/java/com/api/base/controll/Upload.java

@@ -0,0 +1,142 @@
+package com.api.base.controll;
+
+import com.api.common.config.UploadConfig;
+import com.api.common.ImageUploadUtil;
+import com.api.core.annotation.PowerEnable;
+import com.api.core.response.Result;
+import com.api.core.response.ResultEnum;
+import com.api.core.response.ResultGenerator;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.multipart.MultipartHttpServletRequest;
+import org.springframework.web.multipart.commons.CommonsMultipartResolver;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import java.io.File;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * Created by Administrator on 2017/4/6.
+ */
+@PowerEnable(name = "文件上传",url = "upload")
+@Api(value = "文件上传", tags = {"文件上传"})
+@Controller
+public class Upload {
+    Logger logger = LoggerFactory.getLogger(this.getClass());
+
+    @Resource
+    private UploadConfig uploadConfig;
+
+    /**
+     * 单图图上传 
+     *
+     * @param request
+     * @return
+     */
+    @ApiOperation(value="富文本上传",tags={"文件上传"},notes="富文本上传")
+    @RequestMapping(value = "/upload", method = RequestMethod.POST,name = "富文本上传")
+    @ResponseBody
+    public Map<String, String> uploadImages(HttpServletRequest request) {
+        String up = "image/";
+        Map<String, String> res = new HashMap<>();
+
+        try {
+            String paths = ImageUploadUtil.upload(request, uploadConfig.getFilePath() + up);
+            for (int i = 0; i < paths.split(",").length; i++) {
+                res.put("default", uploadConfig.getHost() + uploadConfig.getPrefix() + up + paths.split(",")[i]);
+            }
+            return res;
+        } catch (IOException e) {
+           logger.error("图片上传出错",e);
+        }
+        return res;
+    }
+
+
+
+    /**
+     * 身份证上传
+     */
+    @ApiOperation(value="图片上传",tags={"文件上传"},notes="图片上传")
+    @RequestMapping(value = "/img/upload", method = RequestMethod.POST,name = "图片上传")
+    @ResponseBody
+    public Result uploadIdCard(HttpServletRequest request) {
+        String up = "img/";
+        try {
+            String spath = ImageUploadUtil.upload(request, uploadConfig.getFilePath() + up);
+            return ResultGenerator.genResultAndData(ResultEnum.UPLOADED,uploadConfig.getPrefix() + up + spath.split(",")[0]);
+        } catch (IOException e) {
+            logger.error("图片上传出错",e);
+            return ResultGenerator.genResult(ResultEnum.UPLOADED_FAIL);
+        }
+    }
+    /**
+     * app安装包
+     */
+    @ApiOperation(value="apk上传",tags={"文件上传"},notes="apk上传")
+    @RequestMapping(value = "/apk/upload", method = RequestMethod.POST)
+    @ResponseBody
+    public Result uploadApk(HttpServletRequest request) {
+        // 创建一个通用的多部分解析器
+        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
+        // 图片名称
+        String fileName = "";
+        // 判断 request 是否有文件上传,即多部分请求
+        if (multipartResolver.isMultipart(request)) {
+            // 转换成多部分request
+            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
+            // 取得request中的所有文件名
+            Iterator<String> iter = multiRequest.getFileNames();
+            while (iter.hasNext()) {
+                // 记录上传过程起始时的时间,用来计算上传时间
+                // int pre = (int) System.currentTimeMillis();
+                // 取得上传文件
+                MultipartFile file = multiRequest.getFile(iter.next());
+                if (file != null) {
+                    // 取得当前上传文件的文件名称
+                    String myFileName = file.getOriginalFilename();
+                    // 如果名称不为“”,说明该文件存在,否则说明该文件不存在
+                    if (myFileName.trim() != "") {
+                        // 获得图片的原始名称
+                        String originalFilename = file.getOriginalFilename();
+                        // 获得图片后缀名称,如果后缀不为图片格式,则不上传
+                        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
+                        originalFilename = originalFilename.replace(suffix, "");
+                        if (!".apk".equals(suffix)) {
+                            throw new RuntimeException("不支持文件格式" + suffix);
+                        }
+
+                        File upload = new File(uploadConfig.getFilePath() + "apk" + File.separator);
+
+                        if (!upload.exists()) {
+                            upload.mkdirs();
+                        }
+                        File uploadFile = new File(upload + File.separator + originalFilename + suffix);
+                        try {
+                            fileName = (originalFilename + suffix);
+
+                            file.transferTo(uploadFile);
+                            return ResultGenerator.genSuccessResult(uploadConfig.getHost() + uploadConfig.getPrefix()+ "apk/" + fileName);
+                        } catch (IOException e) {
+                            logger.error("图片上传出错",e);
+                            return ResultGenerator.genResult(ResultEnum.UPLOADED_FAIL);
+                        }
+                    }
+                }
+            }
+        }
+        return ResultGenerator.genResult(ResultEnum.UPLOADED_FAIL);
+    }
+}

+ 184 - 0
base/src/main/java/com/api/base/controll/UserController.java

@@ -0,0 +1,184 @@
+package com.api.base.controll;
+
+import com.api.core.config.AuthUser;
+import com.api.base.config.auth.JwtTokenUtil;
+import com.api.base.model.Role;
+import com.api.base.model.User;
+import com.api.base.service.UserService;
+import com.api.common.JSONUtils;
+import com.api.common.wx.WxCommon;
+import com.api.core.controller.Ctrl;
+import com.api.core.annotation.PowerEnable;
+import com.api.core.response.Result;
+import com.api.core.response.ResultGenerator;
+import com.github.pagehelper.PageHelper;
+import com.github.pagehelper.PageInfo;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiImplicitParams;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.cache.annotation.CacheEvict;
+import org.springframework.cache.annotation.Caching;
+import org.springframework.security.core.Authentication;
+import org.springframework.web.bind.annotation.*;
+import tk.mybatis.mapper.entity.Condition;
+import tk.mybatis.mapper.entity.Example;
+
+import javax.annotation.Resource;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+
+/**
+ * Created by CodeGenerator on 2019/03/25.
+ */
+@PowerEnable(name = "账号管理",url = "/user")
+@Api(value = "账号管理", tags = {"账号管理"})
+@RestController
+@RequestMapping(value = "/user")
+public class UserController extends Ctrl {
+    @Resource
+    private UserService userService;
+
+    @Resource
+    private JwtTokenUtil jwtTokenUtil;
+    @ApiOperation(value = "注册", tags = {"账号管理"}, notes = "注册")
+    @PostMapping(value = "/registered", name = "注册")
+    public Result registered(@RequestParam String username,
+                             @RequestParam String password,
+                             @RequestParam String mobileNumber,
+                             @RequestParam Byte gender,
+                             @RequestParam String email,
+                             @RequestParam String nickname,
+                             @RequestParam String avatar) {
+
+        return userService.registered(username,password,mobileNumber,gender,email,nickname,avatar);
+    }
+
+
+    @ApiOperation(value = "用户列表", tags = {"账号管理"}, notes = "用户列表")
+    @ApiImplicitParams({
+            @ApiImplicitParam(name = "where", value = "条件json", dataType = "String", paramType = "query"),
+            @ApiImplicitParam(name = "page", value = "页数", dataType = "Integer", paramType = "query"),
+            @ApiImplicitParam(name = "size", value = "条数", dataType = "Integer", paramType = "query"),
+    })
+    @PostMapping(value = "/list", name = "用户列表")
+    @ResponseBody
+    public Result list(@RequestParam(defaultValue = "[]") String where,
+                       @RequestParam(defaultValue = "0") Integer page,
+                       @RequestParam(defaultValue = "10") Integer size) {
+        PageHelper.startPage(page, size);
+
+        Condition c = new Condition(User.class);
+        Example.Criteria criteria = c.createCriteria();
+
+        buildWhere(where, criteria);
+
+        List<User> list = userService.findByCondition(c);
+        PageInfo pageInfo = new PageInfo<>(list);
+        return ResultGenerator.genSuccessResult(pageInfo);
+    }
+
+    @ApiOperation(value = "用户添加角色", tags = {"账号管理"}, notes = "用户添加角色")
+    @ApiImplicitParams({
+            @ApiImplicitParam(name = "roles", value = "角色json", dataType = "String", paramType = "query"),
+            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "Long", paramType = "query"),
+    })
+    @PostMapping(value = "/add/role", name = "用户添加角色")
+    @Caching(evict = {@CacheEvict(value = "role", key = "#userId"), @CacheEvict(value = "power", key = "#userId")})
+    public Result addRole(String roles, Long userId) {
+        List<Long> roleids = JSONUtils.json2list(roles, Long.class);
+
+
+        return userService.addRole(roleids, userId);
+    }
+
+    @PostMapping(value = "/get/role", name = "获取用户角色")
+    public Result getRole(@RequestParam Long userId) {
+        List<Role> roles = userService.getRole(userId);
+        return ResultGenerator.genSuccessResult(roles);
+    }
+
+    @ApiOperation(value = "获取登录用户信息", tags = {"账号管理"}, notes = "获取登录用户信息")
+    @PostMapping(value = "get", name = "获取登录用户信息")
+    public Result get(Authentication authentication) {
+        AuthUser authUser = (AuthUser) authentication.getPrincipal();
+        authUser.setPassword("");
+        return ResultGenerator.genSuccessResult(authUser);
+    }
+
+    /**
+     * 绑定微信
+     *
+     * @param openid
+     * @param authentication
+     * @return
+     */
+    @ApiOperation(value = "绑定微信", tags = {"账号管理"}, notes = "绑定微信")
+    @ApiImplicitParams({
+            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "query"),
+    })
+    @PostMapping(value = "wx/bind", name = "绑定微信")
+    public Result bindWx(@RequestParam String openid, Authentication authentication) {
+
+        AuthUser authUser = (AuthUser) authentication.getPrincipal();
+
+        User user = userService.findById(authUser.getId());
+
+        if (user.getOpenid() != null) return ResultGenerator.genFailResult("用户以绑定微信");
+
+        user.setOpenid(openid);
+
+        userService.update(user);
+
+        return ResultGenerator.genSuccessResult();
+    }
+
+    @ApiOperation(value = "根据openid刷新token", tags = {"账号管理"}, notes = "根据open刷新token")
+    @ApiImplicitParams({
+            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "query"),
+    })
+    @PostMapping(value = "refresh/token", name = "根据open刷新token")
+    public Result getTokenByOpenId(@RequestParam String openid) {
+
+        User user = userService.findBy("openid", openid);
+
+        if (user == null) return ResultGenerator.genFailResult("用户不存在");
+        Map<String, Object> res = new HashMap<>();
+
+        String jwtToken = jwtTokenUtil.generateToken(user.getUsername());
+
+        res.put("token", jwtToken);
+
+        return ResultGenerator.genSuccessResult(res);
+    }
+
+
+    @ApiOperation(value = "获取openid", tags = {"账号管理"}, notes = "获取openid")
+    @ApiImplicitParams({
+            @ApiImplicitParam(name = "appid", value = "appid", dataType = "String", paramType = "query"),
+            @ApiImplicitParam(name = "secret", value = "secret", dataType = "String", paramType = "query"),
+            @ApiImplicitParam(name = "jscode", value = "jscode", dataType = "String", paramType = "query"),
+    })
+    @PostMapping(value = "get/openid", name = "获取openId")
+    public Result getOpenId(@RequestParam String appid,
+                            @RequestParam String secret,
+                            @RequestParam String jscode) {
+
+        Map<String, Object> res = WxCommon.getOpenId(appid, secret, jscode);
+        return ResultGenerator.genSuccessResult(res);
+    }
+
+    @ApiOperation(value = "修改密码", tags = {"账号管理"}, notes = "修改密码")
+    @ApiImplicitParams({
+            @ApiImplicitParam(name = "password", value = "新密码", dataType = "String", paramType = "query"),
+            @ApiImplicitParam(name = "oldpassword", value = "旧密码", dataType = "String", paramType = "query"),
+    })
+    @PostMapping(value = "update/password", name = "修改密密")
+    public Result password(String password,String oldpassword,Authentication authentication) {
+        AuthUser authUser = (AuthUser) authentication.getPrincipal();
+        return userService.updatePassword(password,oldpassword,authUser.getId());
+    }
+
+}

+ 18 - 0
base/src/main/java/com/api/base/dao/PowerMapper.java

@@ -0,0 +1,18 @@
+package com.api.base.dao;
+
+
+import com.api.base.model.Power;
+import com.api.common.mybatis.ResultMap;
+import com.api.core.Mapper;
+import org.apache.ibatis.annotations.Param;
+
+import java.util.List;
+
+public interface PowerMapper extends Mapper<Power> {
+
+    List<Power> getByUser(Long id);
+
+    List<Power> getByRole(@Param("roleId") Long roleId);
+
+    List<ResultMap<String, Object>> listAll();
+}

+ 14 - 0
base/src/main/java/com/api/base/dao/RoleMapper.java

@@ -0,0 +1,14 @@
+package com.api.base.dao;
+
+import com.api.base.model.Role;
+import com.api.core.Mapper;
+
+import java.util.List;
+
+public interface RoleMapper extends Mapper<Role> {
+    List<Role> getByUser(Long userId);
+
+    void deletePower(Long roleId);
+
+    Role selectByDescription(String roleUser);
+}

+ 7 - 0
base/src/main/java/com/api/base/dao/RolePowerMapper.java

@@ -0,0 +1,7 @@
+package com.api.base.dao;
+
+import com.api.base.model.RolePower;
+import com.api.core.Mapper;
+
+public interface RolePowerMapper extends Mapper<RolePower> {
+}

+ 10 - 0
base/src/main/java/com/api/base/dao/SysWhitelistMapper.java

@@ -0,0 +1,10 @@
+package com.api.base.dao;
+
+import com.api.base.model.SysWhitelist;
+import com.api.core.Mapper;
+import com.api.core.response.Result;
+import org.apache.ibatis.annotations.Param;
+
+public interface SysWhitelistMapper extends Mapper<SysWhitelist> {
+    void update(@Param("url") String url, @Param("id") String id);
+}

+ 9 - 0
base/src/main/java/com/api/base/dao/UserMapper.java

@@ -0,0 +1,9 @@
+package com.api.base.dao;
+
+import com.api.base.model.User;
+import com.api.core.Mapper;
+
+public interface UserMapper extends Mapper<User> {
+
+    void deleteRoleById(Long userId);
+}

+ 9 - 0
base/src/main/java/com/api/base/dao/UserRoleMapper.java

@@ -0,0 +1,9 @@
+package com.api.base.dao;
+
+
+import com.api.base.model.UserRole;
+import com.api.core.Mapper;
+
+public interface UserRoleMapper extends Mapper<UserRole> {
+    void deleteByUid(Long uid);
+}

+ 29 - 0
base/src/main/java/com/api/base/dao/mapper/PowerMapper.xml

@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.api.base.dao.PowerMapper">
+  <resultMap id="BaseResultMap" type="com.api.base.model.Power">
+    <id column="id" jdbcType="INTEGER" property="id" />
+    <result column="name" jdbcType="VARCHAR" property="name" />
+    <result column="url" jdbcType="VARCHAR" property="url" />
+    <result column="pid" jdbcType="INTEGER" property="pid" />
+  </resultMap>
+
+  <select id="getByUser" parameterType="java.lang.Long" resultType="com.api.base.model.Power">
+    SELECT p.* FROM (SELECT  * FROM sys_user_role WHERE user_id = #{id}) u
+      LEFT JOIN sys_role r ON (r.id = u.role_id)
+        LEFT JOIN sys_role_power rp ON (r.id=rp.role_id)
+          LEFT JOIN sys_power p ON (p.id=rp.power_id)
+          WHERE p.id is not null
+  </select>
+  <select id="getByRole" parameterType="java.lang.Long" resultMap="BaseResultMap">
+    select * from  sys_power p where exists(select id from  sys_role_power r where r.power_id = p.id and role_id= #{roleId} )
+  </select>
+
+  <select id="listAll" resultType="com.api.common.mybatis.ResultMap">
+    select power.*,p.name as p_name from sys_power
+    left join sys_power p on(power.pid = p.id)
+    where power.pid != 0
+  </select>
+
+
+</mapper>

+ 24 - 0
base/src/main/java/com/api/base/dao/mapper/RoleMapper.xml

@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.api.base.dao.RoleMapper">
+  <resultMap id="BaseResultMap" type="com.api.base.model.Role">
+    <!--
+      WARNING - @mbg.generated
+    -->
+    <id column="id" jdbcType="BIGINT" property="id" />
+    <result column="name" jdbcType="VARCHAR" property="name" />
+    <result column="description" jdbcType="VARCHAR" property="description" />
+  </resultMap>
+
+  <select id="getByUser" parameterType="java.lang.Long" resultType="com.api.base.model.Role">
+     SELECT r.* FROM (SELECT  * FROM sys_user_role WHERE user_id = #{userId}) u
+        LEFT JOIN sys_role r ON (r.id = u.role_id)
+   </select>
+
+    <select id="deletePower" parameterType="java.lang.Long" >
+      DELETE FROM sys_role_power WHERE role_id = #{roleId}
+    </select>
+    <select id="selectByDescription" resultMap="BaseResultMap">
+        select * from sys_role where description = #{description}
+    </select>
+</mapper>

+ 8 - 0
base/src/main/java/com/api/base/dao/mapper/RolePowerMapper.xml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.api.base.dao.RolePowerMapper">
+  <resultMap id="BaseResultMap" type="com.api.base.model.RolePower">
+    <id column="role_id" jdbcType="BIGINT" property="roleId" />
+    <id column="power_id" jdbcType="BIGINT" property="powerId" />
+  </resultMap>
+</mapper>

+ 14 - 0
base/src/main/java/com/api/base/dao/mapper/SysWhitelistMapper.xml

@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.api.base.dao.SysWhitelistMapper">
+  <resultMap id="BaseResultMap" type="com.api.base.model.SysWhitelist">
+    <!--
+      WARNING - @mbg.generated
+    -->
+    <id column="url" jdbcType="VARCHAR" property="url" />
+  </resultMap>
+
+  <update id="update" parameterType="java.util.Map">
+    update sys_whitelist set  url=#{url}  where url = #{id} ;
+  </update>
+</mapper>

+ 26 - 0
base/src/main/java/com/api/base/dao/mapper/UserMapper.xml

@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.api.base.dao.UserMapper">
+  <resultMap id="BaseResultMap" type="com.api.base.model.User">
+    <!--
+      WARNING - @mbg.generated
+    -->
+    <id column="id" jdbcType="BIGINT" property="id" />
+    <result column="username" jdbcType="VARCHAR" property="username" />
+    <result column="password" jdbcType="VARCHAR" property="password" />
+    <result column="mobile_number" jdbcType="VARCHAR" property="mobileNumber" />
+    <result column="gender" jdbcType="TINYINT" property="gender" />
+    <result column="alias" jdbcType="VARCHAR" property="alias" />
+    <result column="latest_login_time" jdbcType="TIMESTAMP" property="latestLoginTime" />
+    <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
+    <result column="nickname" jdbcType="VARCHAR" property="nickname" />
+    <result column="avatar" jdbcType="VARCHAR" property="avatar" />
+    <result column="enable" jdbcType="TINYINT" property="enable" />
+    <result column="type" jdbcType="TINYINT" property="type" />
+    <result column="status" jdbcType="TINYINT" property="status" />
+    <result column="openid" jdbcType="VARCHAR" property="openid" />
+  </resultMap>
+  <select id="deleteRoleById" parameterType="java.lang.Long">
+    DELETE FROM sys_user_role WHERE user_id = #{userId}
+  </select>
+</mapper>

+ 11 - 0
base/src/main/java/com/api/base/dao/mapper/UserRoleMapper.xml

@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.api.base.dao.UserRoleMapper">
+  <resultMap id="BaseResultMap" type="com.api.base.model.UserRole">
+    <id column="role_id" jdbcType="BIGINT" property="roleId" />
+    <id column="user_id" jdbcType="BIGINT" property="userId" />
+  </resultMap>
+    <delete id="deleteByUid">
+      delete from sys_user_role where user_id = #{uid}
+    </delete>
+</mapper>

+ 36 - 0
base/src/main/java/com/api/base/dto/ElTree.java

@@ -0,0 +1,36 @@
+package com.api.base.dto;
+
+import java.util.List;
+
+public class ElTree<T> {
+
+    private Object id;
+
+    private String name;
+
+    private List<T> children;
+
+    public Object getId() {
+        return id;
+    }
+
+    public void setId(Object id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public List<T> getChildren() {
+        return children;
+    }
+
+    public void setChildren(List<T> children) {
+        this.children = children;
+    }
+}

+ 54 - 0
base/src/main/java/com/api/base/model/Power.java

@@ -0,0 +1,54 @@
+package com.api.base.model;
+
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import java.io.Serializable;
+
+@Table(name = "sys_power")
+public class Power implements Serializable {
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    private Integer id;
+
+    private String name;
+
+    private String url;
+
+    private Integer pid;
+
+    private static final long serialVersionUID = 1L;
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getUrl() {
+        return url;
+    }
+
+    public void setUrl(String url) {
+        this.url = url;
+    }
+
+    public Integer getPid() {
+        return pid;
+    }
+
+    public void setPid(Integer pid) {
+        this.pid = pid;
+    }
+}

+ 65 - 0
base/src/main/java/com/api/base/model/Role.java

@@ -0,0 +1,65 @@
+package com.api.base.model;
+
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import java.io.Serializable;
+
+@Table(name = "sys_role")
+public class Role implements Serializable {
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    private Long id;
+
+    private String name;
+
+    private String description;
+
+
+    public Role(String name, String description) {
+        this.name = name;
+        this.description = description;
+    }
+
+
+    public Role() {
+    }
+
+
+    public Long getId() {
+        return id;
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    /**
+     * @return name
+     */
+    public String getName() {
+        return name;
+    }
+
+    /**
+     * @param name
+     */
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    /**
+     * @return description
+     */
+    public String getDescription() {
+        return description;
+    }
+
+    /**
+     * @param description
+     */
+    public void setDescription(String description) {
+        this.description = description;
+    }
+}

+ 32 - 0
base/src/main/java/com/api/base/model/RolePower.java

@@ -0,0 +1,32 @@
+package com.api.base.model;
+
+import javax.persistence.Column;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import java.io.Serializable;
+
+@Table(name = "sys_role_power")
+public class RolePower implements Serializable {
+    @Id
+    @Column(name = "role_id")
+    private Long roleId;
+
+    @Column(name = "power_id")
+    private Long powerId;
+
+    public Long getRoleId() {
+        return roleId;
+    }
+
+    public void setRoleId(Long roleId) {
+        this.roleId = roleId;
+    }
+
+    public Long getPowerId() {
+        return powerId;
+    }
+
+    public void setPowerId(Long powerId) {
+        this.powerId = powerId;
+    }
+}

+ 26 - 0
base/src/main/java/com/api/base/model/SysWhitelist.java

@@ -0,0 +1,26 @@
+package com.api.base.model;
+
+import java.io.Serializable;
+import javax.persistence.*;
+
+@Table(name = "sys_whitelist")
+public class SysWhitelist implements Serializable {
+    @Id
+    private String url;
+
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * @return url
+     */
+    public String getUrl() {
+        return url;
+    }
+
+    /**
+     * @param url
+     */
+    public void setUrl(String url) {
+        this.url = url;
+    }
+}

+ 277 - 0
base/src/main/java/com/api/base/model/User.java

@@ -0,0 +1,277 @@
+package com.api.base.model;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.util.Date;
+
+@Table(name = "sys_user")
+public class User implements Serializable {
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    private Long id;
+
+    private String username;
+
+    private String password;
+
+    /**
+     * 手机
+     */
+    @Column(name = "mobile_number")
+    private String mobileNumber;
+
+    /**
+     * 性别
+     */
+    private Byte gender;
+
+    /**
+     * 推送別名
+     */
+    private String alias;
+
+    /**
+     * 最后登录的时间
+     */
+    @Column(name = "latest_login_time")
+    private Date latestLoginTime;
+
+    /**
+     * 创建时间
+     */
+    @Column(name = "create_time")
+    private Date createTime;
+
+    /**
+     * 创建时间
+     */
+    private String nickname;
+
+    /**
+     * 创建时间
+     */
+    private String avatar;
+
+    /**
+     * 0 启用
+     * 1 禁用
+     * 2 禁止退出登录
+     */
+    private Byte enable;
+
+    private Byte type;
+
+    private String openid;
+
+    private Byte status;
+
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * @return id
+     */
+    public Long getId() {
+        return id;
+    }
+
+    /**
+     * @param id
+     */
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    /**
+     * @return username
+     */
+    public String getUsername() {
+        return username;
+    }
+
+    /**
+     * @param username
+     */
+    public void setUsername(String username) {
+        this.username = username;
+    }
+
+    /**
+     * @return password
+     */
+    public String getPassword() {
+        return password;
+    }
+
+    /**
+     * @param password
+     */
+    public void setPassword(String password) {
+        this.password = password;
+    }
+
+    /**
+     * 获取手机
+     *
+     * @return mobile_number - 手机
+     */
+    public String getMobileNumber() {
+        return mobileNumber;
+    }
+
+    /**
+     * 设置手机
+     *
+     * @param mobileNumber 手机
+     */
+    public void setMobileNumber(String mobileNumber) {
+        this.mobileNumber = mobileNumber;
+    }
+
+    /**
+     * 获取性别
+     *
+     * @return gender - 性别
+     */
+    public Byte getGender() {
+        return gender;
+    }
+
+    /**
+     * 设置性别
+     *
+     * @param gender 性别
+     */
+    public void setGender(Byte gender) {
+        this.gender = gender;
+    }
+
+    public String getAlias() {
+        return alias;
+    }
+
+    public void setAlias(String alias) {
+        this.alias = alias;
+    }
+
+    /**
+     * 获取最后登录的时间
+     *
+     * @return latest_login_time - 最后登录的时间
+     */
+    public Date getLatestLoginTime() {
+        return latestLoginTime;
+    }
+
+    /**
+     * 设置最后登录的时间
+     *
+     * @param latestLoginTime 最后登录的时间
+     */
+    public void setLatestLoginTime(Date latestLoginTime) {
+        this.latestLoginTime = latestLoginTime;
+    }
+
+    /**
+     * 获取创建时间
+     *
+     * @return create_time - 创建时间
+     */
+    public Date getCreateTime() {
+        return createTime;
+    }
+
+    /**
+     * 设置创建时间
+     *
+     * @param createTime 创建时间
+     */
+    public void setCreateTime(Date createTime) {
+        this.createTime = createTime;
+    }
+
+    /**
+     * 获取创建时间
+     *
+     * @return nickname - 创建时间
+     */
+    public String getNickname() {
+        return nickname;
+    }
+
+    /**
+     * 设置创建时间
+     *
+     * @param nickname 创建时间
+     */
+    public void setNickname(String nickname) {
+        this.nickname = nickname;
+    }
+
+    /**
+     * 获取创建时间
+     *
+     * @return avatar - 创建时间
+     */
+    public String getAvatar() {
+        return avatar;
+    }
+
+    /**
+     * 设置创建时间
+     *
+     * @param avatar 创建时间
+     */
+    public void setAvatar(String avatar) {
+        this.avatar = avatar;
+    }
+
+    /**
+     * @return enable
+     */
+    public Byte getEnable() {
+        return enable;
+    }
+
+    /**
+     * @param enable
+     */
+    public void setEnable(Byte enable) {
+        this.enable = enable;
+    }
+
+    /**
+     * @return type
+     */
+    public Byte getType() {
+        return type;
+    }
+
+    /**
+     * @param type
+     */
+    public void setType(Byte type) {
+        this.type = type;
+    }
+
+    /**
+     * @return openid
+     */
+    public String getOpenid() {
+        return openid;
+    }
+
+    /**
+     * @param openid
+     */
+    public void setOpenid(String openid) {
+        this.openid = openid;
+    }
+
+    public Byte getStatus() {
+        return status;
+    }
+
+    public void setStatus(Byte status) {
+        this.status = status;
+    }
+}

+ 32 - 0
base/src/main/java/com/api/base/model/UserRole.java

@@ -0,0 +1,32 @@
+package com.api.base.model;
+
+import javax.persistence.Column;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import java.io.Serializable;
+
+@Table(name = "sys_user_role")
+public class UserRole implements Serializable {
+    @Id
+    @Column(name = "role_id")
+    private Long roleId;
+
+    @Column(name = "user_id")
+    private Long userId;
+
+    public Long getRoleId() {
+        return roleId;
+    }
+
+    public void setRoleId(Long roleId) {
+        this.roleId = roleId;
+    }
+
+    public Long getUserId() {
+        return userId;
+    }
+
+    public void setUserId(Long userId) {
+        this.userId = userId;
+    }
+}

+ 22 - 0
base/src/main/java/com/api/base/service/PowerService.java

@@ -0,0 +1,22 @@
+package com.api.base.service;
+
+import com.api.base.model.Power;
+import com.api.common.mybatis.ResultMap;
+import com.api.core.service.Service;
+
+import java.util.List;
+
+
+/**
+ * Created by CodeGenerator on 2019/03/25.
+ */
+public interface PowerService extends Service<Power> {
+
+    @Override
+
+    List<Power> findAll();
+
+    List<ResultMap<String,Object>> listAll();
+
+    List<Power>  getByRole(Long roleId);
+}

+ 11 - 0
base/src/main/java/com/api/base/service/RolePowerService.java

@@ -0,0 +1,11 @@
+package com.api.base.service;
+import com.api.base.model.RolePower;
+import com.api.core.service.Service;
+
+
+/**
+ * Created by CodeGenerator on 2019/03/25.
+ */