From 41da694227da60f5be44687e4c71f2a471f33975 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E6=B2=90?= Date: Tue, 26 Jul 2022 16:01:24 +0800 Subject: [PATCH] =?UTF-8?q?=E8=B0=83=E6=95=B4=E9=A1=B9=E7=9B=AE=E7=BB=93?= =?UTF-8?q?=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fast-boot-framework/pom.xml | 69 ------------ .../maku/framework/common/constant/Constant.java | 25 ----- .../net/maku/framework/common/dao/BaseDao.java | 13 --- .../maku/framework/common/entity/BaseEntity.java | 58 ---------- .../maku/framework/common/exception/ErrorCode.java | 21 ---- .../framework/common/exception/FastException.java | 37 ------- .../common/exception/FastExceptionHandler.java | 51 --------- .../common/handler/FieldMetaObjectHandler.java | 52 --------- .../framework/common/interceptor/DataScope.java | 16 --- .../interceptor/DataScopeInnerInterceptor.java | 81 -------------- .../net/maku/framework/common/page/PageResult.java | 34 ------ .../net/maku/framework/common/query/Query.java | 32 ------ .../maku/framework/common/service/BaseService.java | 13 --- .../common/service/impl/BaseServiceImpl.java | 109 ------------------- .../maku/framework/common/utils/AssertUtils.java | 32 ------ .../net/maku/framework/common/utils/DateUtils.java | 56 ---------- .../framework/common/utils/HttpContextUtils.java | 55 ---------- .../net/maku/framework/common/utils/JsonUtils.java | 68 ------------ .../net/maku/framework/common/utils/RedisKeys.java | 44 -------- .../maku/framework/common/utils/RedisUtils.java | 118 --------------------- .../net/maku/framework/common/utils/Result.java | 52 --------- .../net/maku/framework/common/utils/TreeNode.java | 34 ------ .../net/maku/framework/common/utils/TreeUtils.java | 70 ------------ .../java/net/maku/framework/config/CorsConfig.java | 28 ----- .../maku/framework/config/MybatisPlusConfig.java | 39 ------- .../net/maku/framework/config/RedisConfig.java | 47 -------- .../net/maku/framework/config/SwaggerConfig.java | 43 -------- .../java/net/maku/framework/config/WebConfig.java | 52 --------- .../security/config/AuthorizationServerConfig.java | 76 ------------- .../framework/security/config/PasswordConfig.java | 20 ---- .../framework/security/config/PermitResource.java | 59 ----------- .../security/config/ResourceServerConfig.java | 50 --------- .../security/config/TokenStoreConfig.java | 25 ----- .../security/config/WebSecurityConfig.java | 61 ----------- .../exception/FastAuthenticationException.java | 18 ---- .../security/exception/FastOAuth2Exception.java | 31 ------ .../FastWebResponseExceptionTranslator.java | 78 -------------- .../SecurityAuthenticationEntryPoint.java | 29 ----- .../handler/UserAuthenticationFailureHandler.java | 31 ------ .../security/token/FastTokenEnhancer.java | 34 ------ .../maku/framework/security/user/SecurityUser.java | 33 ------ .../maku/framework/security/user/UserDetail.java | 84 --------------- fast-boot-new/pom.xml | 2 +- fast-boot-system/pom.xml | 2 +- fast-framework/pom.xml | 69 ++++++++++++ .../maku/framework/common/constant/Constant.java | 25 +++++ .../net/maku/framework/common/dao/BaseDao.java | 13 +++ .../maku/framework/common/entity/BaseEntity.java | 58 ++++++++++ .../maku/framework/common/exception/ErrorCode.java | 21 ++++ .../framework/common/exception/FastException.java | 37 +++++++ .../common/exception/FastExceptionHandler.java | 51 +++++++++ .../common/handler/FieldMetaObjectHandler.java | 52 +++++++++ .../framework/common/interceptor/DataScope.java | 16 +++ .../interceptor/DataScopeInnerInterceptor.java | 81 ++++++++++++++ .../net/maku/framework/common/page/PageResult.java | 34 ++++++ .../net/maku/framework/common/query/Query.java | 32 ++++++ .../maku/framework/common/service/BaseService.java | 13 +++ .../common/service/impl/BaseServiceImpl.java | 109 +++++++++++++++++++ .../maku/framework/common/utils/AssertUtils.java | 32 ++++++ .../net/maku/framework/common/utils/DateUtils.java | 56 ++++++++++ .../framework/common/utils/HttpContextUtils.java | 55 ++++++++++ .../net/maku/framework/common/utils/JsonUtils.java | 68 ++++++++++++ .../net/maku/framework/common/utils/RedisKeys.java | 44 ++++++++ .../maku/framework/common/utils/RedisUtils.java | 118 +++++++++++++++++++++ .../net/maku/framework/common/utils/Result.java | 52 +++++++++ .../net/maku/framework/common/utils/TreeNode.java | 34 ++++++ .../net/maku/framework/common/utils/TreeUtils.java | 70 ++++++++++++ .../java/net/maku/framework/config/CorsConfig.java | 28 +++++ .../maku/framework/config/MybatisPlusConfig.java | 39 +++++++ .../net/maku/framework/config/RedisConfig.java | 47 ++++++++ .../net/maku/framework/config/SwaggerConfig.java | 43 ++++++++ .../java/net/maku/framework/config/WebConfig.java | 52 +++++++++ .../security/config/AuthorizationServerConfig.java | 76 +++++++++++++ .../framework/security/config/PasswordConfig.java | 20 ++++ .../framework/security/config/PermitResource.java | 59 +++++++++++ .../security/config/ResourceServerConfig.java | 50 +++++++++ .../security/config/TokenStoreConfig.java | 25 +++++ .../security/config/WebSecurityConfig.java | 61 +++++++++++ .../exception/FastAuthenticationException.java | 18 ++++ .../security/exception/FastOAuth2Exception.java | 31 ++++++ .../FastWebResponseExceptionTranslator.java | 78 ++++++++++++++ .../SecurityAuthenticationEntryPoint.java | 29 +++++ .../handler/UserAuthenticationFailureHandler.java | 31 ++++++ .../security/token/FastTokenEnhancer.java | 34 ++++++ .../maku/framework/security/user/SecurityUser.java | 33 ++++++ .../maku/framework/security/user/UserDetail.java | 84 +++++++++++++++ pom.xml | 2 +- 87 files changed, 1981 insertions(+), 1981 deletions(-) delete mode 100644 fast-boot-framework/pom.xml delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/constant/Constant.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/dao/BaseDao.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/entity/BaseEntity.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/exception/ErrorCode.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/exception/FastException.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/exception/FastExceptionHandler.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/handler/FieldMetaObjectHandler.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/interceptor/DataScope.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/interceptor/DataScopeInnerInterceptor.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/page/PageResult.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/query/Query.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/service/BaseService.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/service/impl/BaseServiceImpl.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/utils/AssertUtils.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/utils/DateUtils.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/utils/HttpContextUtils.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/utils/JsonUtils.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/utils/RedisKeys.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/utils/RedisUtils.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/utils/Result.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/utils/TreeNode.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/common/utils/TreeUtils.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/config/CorsConfig.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/config/MybatisPlusConfig.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/config/RedisConfig.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/config/SwaggerConfig.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/config/WebConfig.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/security/config/AuthorizationServerConfig.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/security/config/PasswordConfig.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/security/config/PermitResource.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/security/config/ResourceServerConfig.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/security/config/TokenStoreConfig.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/security/config/WebSecurityConfig.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/security/exception/FastAuthenticationException.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/security/exception/FastOAuth2Exception.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/security/exception/FastWebResponseExceptionTranslator.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/security/exception/SecurityAuthenticationEntryPoint.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/security/handler/UserAuthenticationFailureHandler.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/security/token/FastTokenEnhancer.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/security/user/SecurityUser.java delete mode 100644 fast-boot-framework/src/main/java/net/maku/framework/security/user/UserDetail.java create mode 100644 fast-framework/pom.xml create mode 100644 fast-framework/src/main/java/net/maku/framework/common/constant/Constant.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/dao/BaseDao.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/entity/BaseEntity.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/exception/ErrorCode.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/exception/FastException.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/exception/FastExceptionHandler.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/handler/FieldMetaObjectHandler.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/interceptor/DataScope.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/interceptor/DataScopeInnerInterceptor.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/page/PageResult.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/query/Query.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/service/BaseService.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/service/impl/BaseServiceImpl.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/utils/AssertUtils.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/utils/DateUtils.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/utils/HttpContextUtils.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/utils/JsonUtils.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/utils/RedisKeys.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/utils/RedisUtils.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/utils/Result.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/utils/TreeNode.java create mode 100644 fast-framework/src/main/java/net/maku/framework/common/utils/TreeUtils.java create mode 100644 fast-framework/src/main/java/net/maku/framework/config/CorsConfig.java create mode 100644 fast-framework/src/main/java/net/maku/framework/config/MybatisPlusConfig.java create mode 100644 fast-framework/src/main/java/net/maku/framework/config/RedisConfig.java create mode 100644 fast-framework/src/main/java/net/maku/framework/config/SwaggerConfig.java create mode 100644 fast-framework/src/main/java/net/maku/framework/config/WebConfig.java create mode 100644 fast-framework/src/main/java/net/maku/framework/security/config/AuthorizationServerConfig.java create mode 100644 fast-framework/src/main/java/net/maku/framework/security/config/PasswordConfig.java create mode 100644 fast-framework/src/main/java/net/maku/framework/security/config/PermitResource.java create mode 100644 fast-framework/src/main/java/net/maku/framework/security/config/ResourceServerConfig.java create mode 100644 fast-framework/src/main/java/net/maku/framework/security/config/TokenStoreConfig.java create mode 100644 fast-framework/src/main/java/net/maku/framework/security/config/WebSecurityConfig.java create mode 100644 fast-framework/src/main/java/net/maku/framework/security/exception/FastAuthenticationException.java create mode 100644 fast-framework/src/main/java/net/maku/framework/security/exception/FastOAuth2Exception.java create mode 100644 fast-framework/src/main/java/net/maku/framework/security/exception/FastWebResponseExceptionTranslator.java create mode 100644 fast-framework/src/main/java/net/maku/framework/security/exception/SecurityAuthenticationEntryPoint.java create mode 100644 fast-framework/src/main/java/net/maku/framework/security/handler/UserAuthenticationFailureHandler.java create mode 100644 fast-framework/src/main/java/net/maku/framework/security/token/FastTokenEnhancer.java create mode 100644 fast-framework/src/main/java/net/maku/framework/security/user/SecurityUser.java create mode 100644 fast-framework/src/main/java/net/maku/framework/security/user/UserDetail.java diff --git a/fast-boot-framework/pom.xml b/fast-boot-framework/pom.xml deleted file mode 100644 index 18ddde5..0000000 --- a/fast-boot-framework/pom.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - net.maku - fast-boot - 1.0.0 - - 4.0.0 - fast-boot-framework - jar - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.springframework.boot - spring-boot-starter-validation - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.boot - spring-boot-starter-data-redis - - - org.springframework.boot - spring-boot-starter-security - - - kotlin-stdlib-jdk7 - org.jetbrains.kotlin - - - kotlin-stdlib-jdk8 - org.jetbrains.kotlin - - - - - org.springframework.security.oauth - spring-security-oauth2 - - - mysql - mysql-connector-java - - - com.baomidou - mybatis-plus-boot-starter - - - org.springdoc - springdoc-openapi-ui - - - cn.hutool - hutool-all - - - \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/constant/Constant.java b/fast-boot-framework/src/main/java/net/maku/framework/common/constant/Constant.java deleted file mode 100644 index 91b95bd..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/constant/Constant.java +++ /dev/null @@ -1,25 +0,0 @@ -package net.maku.framework.common.constant; - -/** - * 常量 - * - * @author 阿沐 babamu@126.com - */ -public interface Constant { - /** - * 根节点标识 - */ - Long ROOT = 0L; - /** - * 当前页码 - */ - String PAGE = "page"; - /** - * 数据权限 - */ - String DATA_SCOPE = "dataScope"; - /** - * 超级管理员 - */ - Integer SUPER_ADMIN = 1; -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/dao/BaseDao.java b/fast-boot-framework/src/main/java/net/maku/framework/common/dao/BaseDao.java deleted file mode 100644 index ce38e5b..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/dao/BaseDao.java +++ /dev/null @@ -1,13 +0,0 @@ -package net.maku.framework.common.dao; - - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; - -/** - * 基础Dao - * - * @author 阿沐 babamu@126.com - */ -public interface BaseDao extends BaseMapper { - -} diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/entity/BaseEntity.java b/fast-boot-framework/src/main/java/net/maku/framework/common/entity/BaseEntity.java deleted file mode 100644 index 7e31e1b..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/entity/BaseEntity.java +++ /dev/null @@ -1,58 +0,0 @@ -package net.maku.framework.common.entity; - -import com.baomidou.mybatisplus.annotation.*; -import lombok.Data; - -import java.util.Date; - -/** - * Entity基类 - * - * @author 阿沐 babamu@126.com - */ -@Data -public abstract class BaseEntity { - /** - * id - */ - @TableId - private Long id; - - /** - * 创建者 - */ - @TableField(fill = FieldFill.INSERT) - private Long creator; - - /** - * 创建时间 - */ - @TableField(fill = FieldFill.INSERT) - private Date createTime; - - /** - * 更新者 - */ - @TableField(fill = FieldFill.INSERT_UPDATE) - private Long updater; - - /** - * 更新时间 - */ - @TableField(fill = FieldFill.INSERT_UPDATE) - private Date updateTime; - - /** - * 版本号 - */ - @Version - @TableField(fill = FieldFill.INSERT) - private Integer version; - - /** - * 删除标记 - */ - @TableLogic - @TableField(fill = FieldFill.INSERT) - private Integer deleted; -} diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/exception/ErrorCode.java b/fast-boot-framework/src/main/java/net/maku/framework/common/exception/ErrorCode.java deleted file mode 100644 index af25107..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/exception/ErrorCode.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.maku.framework.common.exception; - -import lombok.AllArgsConstructor; -import lombok.Getter; - -/** - * 错误编码 - * - * @author 阿沐 babamu@126.com -*/ -@Getter -@AllArgsConstructor -public enum ErrorCode { - UNAUTHORIZED(401, "还未授权,不能访问"), - FORBIDDEN(403, "没有权限,禁止访问"), - INTERNAL_SERVER_ERROR(500, "服务器异常,请稍后再试"), - ACCOUNT_PASSWORD_ERROR(1001, "账号或密码错误"); - - private final int code; - private final String msg; -} diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/exception/FastException.java b/fast-boot-framework/src/main/java/net/maku/framework/common/exception/FastException.java deleted file mode 100644 index 57f0aad..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/exception/FastException.java +++ /dev/null @@ -1,37 +0,0 @@ -package net.maku.framework.common.exception; - -import lombok.Data; -import lombok.EqualsAndHashCode; - -/** - * 自定义异常 - * - * @author 阿沐 babamu@126.com - */ -@Data -@EqualsAndHashCode(callSuper = true) -public class FastException extends RuntimeException { - private static final long serialVersionUID = 1L; - - private int code; - private String msg; - - public FastException(String msg) { - super(msg); - this.code = ErrorCode.INTERNAL_SERVER_ERROR.getCode(); - this.msg = msg; - } - - public FastException(ErrorCode errorCode) { - super(errorCode.getMsg()); - this.code = errorCode.getCode(); - this.msg = errorCode.getMsg(); - } - - public FastException(String msg, Throwable e) { - super(msg, e); - this.code = ErrorCode.INTERNAL_SERVER_ERROR.getCode(); - this.msg = msg; - } - -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/exception/FastExceptionHandler.java b/fast-boot-framework/src/main/java/net/maku/framework/common/exception/FastExceptionHandler.java deleted file mode 100644 index 336b9f6..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/exception/FastExceptionHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -package net.maku.framework.common.exception; - -import lombok.extern.slf4j.Slf4j; -import net.maku.framework.common.utils.Result; -import org.springframework.security.access.AccessDeniedException; -import org.springframework.validation.BindException; -import org.springframework.validation.FieldError; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RestControllerAdvice; - - -/** - * 异常处理器 - * - * @author 阿沐 babamu@126.com - */ -@Slf4j -@RestControllerAdvice -public class FastExceptionHandler { - /** - * 处理自定义异常 - */ - @ExceptionHandler(FastException.class) - public Result handleException(FastException ex){ - - return Result.error(ex.getCode(), ex.getMsg()); - } - - /** - * SpringMVC参数绑定,Validator校验不正确 - */ - @ExceptionHandler(BindException.class) - public Result bindException(BindException ex) { - FieldError fieldError = ex.getFieldError(); - assert fieldError != null; - return Result.error(fieldError.getDefaultMessage()); - } - - @ExceptionHandler(AccessDeniedException.class) - public Result handleAccessDeniedException(Exception ex){ - - return Result.error(ErrorCode.FORBIDDEN); - } - - @ExceptionHandler(Exception.class) - public Result handleException(Exception ex){ - log.error(ex.getMessage(), ex); - return Result.error(ErrorCode.INTERNAL_SERVER_ERROR); - } - -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/handler/FieldMetaObjectHandler.java b/fast-boot-framework/src/main/java/net/maku/framework/common/handler/FieldMetaObjectHandler.java deleted file mode 100644 index 6e55769..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/handler/FieldMetaObjectHandler.java +++ /dev/null @@ -1,52 +0,0 @@ -package net.maku.framework.common.handler; - -import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; -import net.maku.framework.security.user.SecurityUser; -import net.maku.framework.security.user.UserDetail; -import org.apache.ibatis.reflection.MetaObject; - -import java.util.Date; - -/** - * mybatis-plus 自动填充字段 - * - * @author 阿沐 babamu@126.com - */ -public class FieldMetaObjectHandler implements MetaObjectHandler { - private final static String CREATE_TIME = "createTime"; - private final static String CREATOR = "creator"; - private final static String UPDATE_TIME = "updateTime"; - private final static String UPDATER = "updater"; - private final static String ORG_ID = "orgId"; - private final static String VERSION = "version"; - private final static String DELETED = "deleted"; - - @Override - public void insertFill(MetaObject metaObject) { - UserDetail user = SecurityUser.getUser(); - Date date = new Date(); - - // 创建者 - strictInsertFill(metaObject, CREATOR, Long.class, user.getId()); - // 创建时间 - strictInsertFill(metaObject, CREATE_TIME, Date.class, date); - // 更新者 - strictInsertFill(metaObject, UPDATER, Long.class, user.getId()); - // 更新时间 - strictInsertFill(metaObject, UPDATE_TIME, Date.class, date); - // 创建者所属机构 - strictInsertFill(metaObject, ORG_ID, Long.class, user.getOrgId()); - // 版本号 - strictInsertFill(metaObject, VERSION, Integer.class, 0); - // 删除标识 - strictInsertFill(metaObject, DELETED, Integer.class, 0); - } - - @Override - public void updateFill(MetaObject metaObject) { - // 更新者 - strictUpdateFill(metaObject, UPDATER, Long.class, SecurityUser.getUserId()); - // 更新时间 - strictUpdateFill(metaObject, UPDATE_TIME, Date.class, new Date()); - } -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/interceptor/DataScope.java b/fast-boot-framework/src/main/java/net/maku/framework/common/interceptor/DataScope.java deleted file mode 100644 index 2cec15a..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/interceptor/DataScope.java +++ /dev/null @@ -1,16 +0,0 @@ -package net.maku.framework.common.interceptor; - -import lombok.AllArgsConstructor; -import lombok.Data; - -/** - * 数据范围 - * - * @author 阿沐 babamu@126.com - */ -@Data -@AllArgsConstructor -public class DataScope { - private String sqlFilter; - -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/interceptor/DataScopeInnerInterceptor.java b/fast-boot-framework/src/main/java/net/maku/framework/common/interceptor/DataScopeInnerInterceptor.java deleted file mode 100644 index e00795c..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/interceptor/DataScopeInnerInterceptor.java +++ /dev/null @@ -1,81 +0,0 @@ -package net.maku.framework.common.interceptor; - -import cn.hutool.core.util.StrUtil; -import com.baomidou.mybatisplus.core.toolkit.PluginUtils; -import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor; -import net.sf.jsqlparser.JSQLParserException; -import net.sf.jsqlparser.expression.Expression; -import net.sf.jsqlparser.expression.StringValue; -import net.sf.jsqlparser.expression.operators.conditional.AndExpression; -import net.sf.jsqlparser.parser.CCJSqlParserUtil; -import net.sf.jsqlparser.statement.select.PlainSelect; -import net.sf.jsqlparser.statement.select.Select; -import org.apache.ibatis.executor.Executor; -import org.apache.ibatis.mapping.BoundSql; -import org.apache.ibatis.mapping.MappedStatement; -import org.apache.ibatis.session.ResultHandler; -import org.apache.ibatis.session.RowBounds; - -import java.util.Map; - -/** - * 数据权限 - * - * @author 阿沐 babamu@126.com - */ -public class DataScopeInnerInterceptor implements InnerInterceptor { - - @Override - public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) { - DataScope scope = getDataScope(parameter); - // 不进行数据过滤 - if(scope == null || StrUtil.isBlank(scope.getSqlFilter())){ - return; - } - - // 拼接新SQL - String buildSql = getSelect(boundSql.getSql(), scope); - - // 重写SQL - PluginUtils.mpBoundSql(boundSql).sql(buildSql); - } - - private DataScope getDataScope(Object parameter){ - if (parameter == null){ - return null; - } - - // 判断参数里是否有DataScope对象 - if (parameter instanceof Map) { - Map parameterMap = (Map) parameter; - for (Map.Entry entry : parameterMap.entrySet()) { - if (entry.getValue() != null && entry.getValue() instanceof DataScope) { - return (DataScope) entry.getValue(); - } - } - } else if (parameter instanceof DataScope) { - return (DataScope) parameter; - } - - return null; - } - - private String getSelect(String buildSql, DataScope scope){ - try { - Select select = (Select) CCJSqlParserUtil.parse(buildSql); - PlainSelect plainSelect = (PlainSelect) select.getSelectBody(); - - Expression expression = plainSelect.getWhere(); - if(expression == null){ - plainSelect.setWhere(new StringValue(scope.getSqlFilter())); - }else{ - AndExpression andExpression = new AndExpression(expression, new StringValue(scope.getSqlFilter())); - plainSelect.setWhere(andExpression); - } - - return select.toString().replaceAll("'", ""); - }catch (JSQLParserException e){ - return buildSql; - } - } -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/page/PageResult.java b/fast-boot-framework/src/main/java/net/maku/framework/common/page/PageResult.java deleted file mode 100644 index 9633a45..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/page/PageResult.java +++ /dev/null @@ -1,34 +0,0 @@ -package net.maku.framework.common.page; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - -import java.io.Serializable; -import java.util.List; - -/** - * 分页工具类 - * - * @author 阿沐 babamu@126.com - */ -@Data -@Schema(description = "分页数据") -public class PageResult implements Serializable { - private static final long serialVersionUID = 1L; - - @Schema(description = "总记录数") - private int total; - - @Schema(description = "列表数据") - private List list; - - /** - * 分页 - * @param list 列表数据 - * @param total 总记录数 - */ - public PageResult(List list, long total) { - this.list = list; - this.total = (int)total; - } -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/query/Query.java b/fast-boot-framework/src/main/java/net/maku/framework/common/query/Query.java deleted file mode 100644 index b5c3bdb..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/query/Query.java +++ /dev/null @@ -1,32 +0,0 @@ -package net.maku.framework.common.query; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; -import org.hibernate.validator.constraints.Range; - -import javax.validation.constraints.Min; -import javax.validation.constraints.NotNull; - -/** - * 查询公共参数 - * - * @author 阿沐 babamu@126.com - */ -@Data -public class Query { - @NotNull(message = "页码不能为空") - @Min(value = 1, message = "页码最小值为 1") - @Schema(description = "当前页码", required = true) - Integer page; - - @NotNull(message = "每页条数不能为空") - @Range(min = 1, max = 1000, message = "每页条数,取值范围 1-1000") - @Schema(description = "每页条数", required = true) - Integer limit; - - @Schema(description = "排序字段") - String order; - - @Schema(description = "是否升序") - boolean asc; -} diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/service/BaseService.java b/fast-boot-framework/src/main/java/net/maku/framework/common/service/BaseService.java deleted file mode 100644 index fcd3722..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/service/BaseService.java +++ /dev/null @@ -1,13 +0,0 @@ -package net.maku.framework.common.service; - -import com.baomidou.mybatisplus.extension.service.IService; - -/** - * 基础服务接口,所有Service接口都要继承 - * - * @author 阿沐 babamu@126.com - */ -public interface BaseService extends IService { - - -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/service/impl/BaseServiceImpl.java b/fast-boot-framework/src/main/java/net/maku/framework/common/service/impl/BaseServiceImpl.java deleted file mode 100644 index 5d9b790..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/service/impl/BaseServiceImpl.java +++ /dev/null @@ -1,109 +0,0 @@ -package net.maku.framework.common.service.impl; - -import cn.hutool.core.util.StrUtil; -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.baomidou.mybatisplus.core.metadata.IPage; -import com.baomidou.mybatisplus.core.metadata.OrderItem; -import com.baomidou.mybatisplus.core.toolkit.StringUtils; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import net.maku.framework.common.constant.Constant; -import net.maku.framework.common.interceptor.DataScope; -import net.maku.framework.common.query.Query; -import net.maku.framework.common.service.BaseService; -import net.maku.framework.security.user.SecurityUser; -import net.maku.framework.security.user.UserDetail; - -import java.util.List; - - -/** - * 基础服务类,所有Service都要继承 - * - * @author 阿沐 babamu@126.com - */ -public class BaseServiceImpl, T> extends ServiceImpl implements BaseService { - - /** - * 获取分页对象 - * @param query 分页参数 - */ - protected IPage getPage(Query query) { - Page page = new Page<>(query.getPage(), query.getLimit()); - - // 排序 - if(StringUtils.isNotBlank(query.getOrder())){ - if(query.isAsc()) { - return page.addOrder(OrderItem.asc(query.getOrder())); - }else { - return page.addOrder(OrderItem.desc(query.getOrder())); - } - } - - return page; - } - - /** - * 原生SQL 数据权限 - * @param tableAlias 表别名,多表关联时,需要填写表别名 - * @param orgIdAlias 机构ID别名,null:表示org_id - * @return 返回数据权限 - */ - protected DataScope getDataScope(String tableAlias, String orgIdAlias) { - UserDetail user = SecurityUser.getUser(); - // 如果是超级管理员,则不进行数据过滤 - if(user.getSuperAdmin().equals(Constant.SUPER_ADMIN)) { - return null; - } - - // 如果为null,则设置成空字符串 - if(tableAlias == null){ - tableAlias = ""; - } - - // 获取表的别名 - if(StringUtils.isNotBlank(tableAlias)){ - tableAlias += "."; - } - - StringBuilder sqlFilter = new StringBuilder(); - sqlFilter.append(" ("); - - // 数据权限范围 - List dataScopeList = user.getDataScopeList(); - // 全部数据权限 - if (dataScopeList == null){ - return null; - } - // 数据过滤 - if(dataScopeList.size() > 0){ - if(StringUtils.isBlank(orgIdAlias)){ - orgIdAlias = "org_id"; - } - sqlFilter.append(tableAlias).append(orgIdAlias); - - sqlFilter.append(" in(").append(StrUtil.join(",", dataScopeList)).append(")"); - - sqlFilter.append(" or "); - } - - // 查询本人数据 - sqlFilter.append(tableAlias).append("creator").append("=").append(user.getId()); - - sqlFilter.append(")"); - - return new DataScope(sqlFilter.toString()); - } - - /** - * MyBatis-Plus 数据权限 - */ - protected void dataScopeWrapper(LambdaQueryWrapper queryWrapper) { - DataScope dataScope = getDataScope(null, null); - if (dataScope != null){ - queryWrapper.apply(dataScope.getSqlFilter()); - } - } - -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/utils/AssertUtils.java b/fast-boot-framework/src/main/java/net/maku/framework/common/utils/AssertUtils.java deleted file mode 100644 index 094d60a..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/utils/AssertUtils.java +++ /dev/null @@ -1,32 +0,0 @@ -package net.maku.framework.common.utils; - -import cn.hutool.core.util.ArrayUtil; -import cn.hutool.core.util.StrUtil; -import net.maku.framework.common.exception.FastException; - -/** - * 校验工具类 - * - * @author 阿沐 babamu@126.com - */ -public class AssertUtils { - - public static void isBlank(String str, String variable) { - if (StrUtil.isBlank(str)) { - throw new FastException(variable + "不能为空"); - } - } - - public static void isNull(Object object, String variable) { - if (object == null) { - throw new FastException(variable + "不能为空"); - } - } - - public static void isArrayEmpty(Object[] array, String variable) { - if(ArrayUtil.isEmpty(array)){ - throw new FastException(variable + "不能为空"); - } - } - -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/utils/DateUtils.java b/fast-boot-framework/src/main/java/net/maku/framework/common/utils/DateUtils.java deleted file mode 100644 index a5ae202..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/utils/DateUtils.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.maku.framework.common.utils; - - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * 日期处理 - * - * @author 阿沐 babamu@126.com - */ -public class DateUtils { - /** 时间格式(yyyy-MM-dd) */ - public final static String DATE_PATTERN = "yyyy-MM-dd"; - /** 时间格式(yyyy-MM-dd HH:mm:ss) */ - public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; - - /** - * 日期格式化 日期格式为:yyyy-MM-dd - * @param date 日期 - * @return 返回yyyy-MM-dd格式日期 - */ - public static String format(Date date) { - return format(date, DATE_PATTERN); - } - - /** - * 日期格式化 日期格式为:yyyy-MM-dd - * @param date 日期 - * @param pattern 格式,如:DateUtils.DATE_TIME_PATTERN - * @return 返回yyyy-MM-dd格式日期 - */ - public static String format(Date date, String pattern) { - if(date != null){ - SimpleDateFormat df = new SimpleDateFormat(pattern); - return df.format(date); - } - return null; - } - - /** - * 日期解析 - * @param date 日期 - * @param pattern 格式,如:DateUtils.DATE_TIME_PATTERN - * @return 返回Date - */ - public static Date parse(String date, String pattern) { - try { - return new SimpleDateFormat(pattern).parse(date); - } catch (ParseException e) { - e.printStackTrace(); - } - return null; - } -} diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/utils/HttpContextUtils.java b/fast-boot-framework/src/main/java/net/maku/framework/common/utils/HttpContextUtils.java deleted file mode 100644 index 4928c4a..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/utils/HttpContextUtils.java +++ /dev/null @@ -1,55 +0,0 @@ -package net.maku.framework.common.utils; - -import cn.hutool.core.util.StrUtil; -import org.springframework.http.HttpHeaders; -import org.springframework.web.context.request.RequestAttributes; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -import javax.servlet.http.HttpServletRequest; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; - -/** - * Http - * - * @author 阿沐 babamu@126.com - */ -public class HttpContextUtils { - - public static HttpServletRequest getHttpServletRequest() { - RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); - if(requestAttributes == null){ - return null; - } - - return ((ServletRequestAttributes) requestAttributes).getRequest(); - } - - public static Map getParameterMap(HttpServletRequest request) { - Enumeration parameters = request.getParameterNames(); - - Map params = new HashMap<>(); - while (parameters.hasMoreElements()) { - String parameter = parameters.nextElement(); - String value = request.getParameter(parameter); - if (StrUtil.isNotBlank(value)) { - params.put(parameter, value); - } - } - - return params; - } - - public static String getDomain(){ - HttpServletRequest request = getHttpServletRequest(); - StringBuffer url = request.getRequestURL(); - return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString(); - } - - public static String getOrigin(){ - HttpServletRequest request = getHttpServletRequest(); - return request.getHeader(HttpHeaders.ORIGIN); - } -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/utils/JsonUtils.java b/fast-boot-framework/src/main/java/net/maku/framework/common/utils/JsonUtils.java deleted file mode 100644 index 89d99af..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/utils/JsonUtils.java +++ /dev/null @@ -1,68 +0,0 @@ -package net.maku.framework.common.utils; - -import cn.hutool.core.util.ArrayUtil; -import cn.hutool.core.util.StrUtil; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.util.ArrayList; -import java.util.List; - -/** - * JSON 工具类 - * - * @author 阿沐 babamu@126.com - */ -public class JsonUtils { - private static final ObjectMapper objectMapper = new ObjectMapper(); - - public static String toJsonString(Object object) { - try { - return objectMapper.writeValueAsString(object); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - public static T parseObject(String text, Class clazz) { - if (StrUtil.isEmpty(text)) { - return null; - } - try { - return objectMapper.readValue(text, clazz); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - public static T parseObject(byte[] bytes, Class clazz) { - if (ArrayUtil.isEmpty(bytes)) { - return null; - } - try { - return objectMapper.readValue(bytes, clazz); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - public static T parseObject(String text, TypeReference typeReference) { - try { - return objectMapper.readValue(text, typeReference); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - public static List parseArray(String text, Class clazz) { - if (StrUtil.isEmpty(text)) { - return new ArrayList<>(); - } - try { - return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz)); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - -} diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/utils/RedisKeys.java b/fast-boot-framework/src/main/java/net/maku/framework/common/utils/RedisKeys.java deleted file mode 100644 index 2cbea83..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/utils/RedisKeys.java +++ /dev/null @@ -1,44 +0,0 @@ -package net.maku.framework.common.utils; - -/** - * Redis Key管理 - * - * @author 阿沐 babamu@126.com - */ -public class RedisKeys { - - /** - * 验证码Key - */ - public static String getCaptchaKey(String key) { - return "sys:captcha:" + key; - } - - /** - * 授权码Key - */ - public static String getOauthCode(String code) { - return "oauth:code:" + code; - } - - /** - * 微信小程序授权key - * - * @param key - * @return - */ - public static String getWxMpAuthKey(String key) { - return "wx:mp:auth:" + key; - } - - /** - * 微信小程序授权类型key - * - * @param key - * @return - */ - public static String getWxMpAuthTypeKey(String key) { - return "wx:mp:auth:type:" + key; - } - -} diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/utils/RedisUtils.java b/fast-boot-framework/src/main/java/net/maku/framework/common/utils/RedisUtils.java deleted file mode 100644 index 6cb0a0a..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/utils/RedisUtils.java +++ /dev/null @@ -1,118 +0,0 @@ -package net.maku.framework.common.utils; - -import org.springframework.data.redis.core.HashOperations; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.stereotype.Component; - -import javax.annotation.Resource; -import java.util.Collection; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -/** - * Redis工具类 - * - * @author 阿沐 babamu@126.com - */ -@Component -public class RedisUtils { - @Resource - private RedisTemplate redisTemplate; - - /** 默认过期时长为24小时,单位:秒 */ - public final static long DEFAULT_EXPIRE = 60 * 60 * 24L; - /** 过期时长为1小时,单位:秒 */ - public final static long HOUR_ONE_EXPIRE = 60 * 60 * 1L; - /** 过期时长为6小时,单位:秒 */ - public final static long HOUR_SIX_EXPIRE = 60 * 60 * 6L; - /** 不设置过期时长 */ - public final static long NOT_EXPIRE = -1L; - - public void set(String key, Object value, long expire){ - redisTemplate.opsForValue().set(key, value); - if(expire != NOT_EXPIRE){ - expire(key, expire); - } - } - - public void set(String key, Object value){ - set(key, value, DEFAULT_EXPIRE); - } - - public Object get(String key, long expire) { - Object value = redisTemplate.opsForValue().get(key); - if(expire != NOT_EXPIRE){ - expire(key, expire); - } - return value; - } - - public Object get(String key) { - return get(key, NOT_EXPIRE); - } - - public void delete(String key) { - redisTemplate.delete(key); - } - - public void delete(Collection keys) { - redisTemplate.delete(keys); - } - - public Object hGet(String key, String field) { - return redisTemplate.opsForHash().get(key, field); - } - - public Map hGetAll(String key){ - HashOperations hashOperations = redisTemplate.opsForHash(); - return hashOperations.entries(key); - } - - public void hMSet(String key, Map map){ - hMSet(key, map, DEFAULT_EXPIRE); - } - - public void hMSet(String key, Map map, long expire){ - redisTemplate.opsForHash().putAll(key, map); - - if(expire != NOT_EXPIRE){ - expire(key, expire); - } - } - - public void hSet(String key, String field, Object value) { - hSet(key, field, value, DEFAULT_EXPIRE); - } - - public void hSet(String key, String field, Object value, long expire) { - redisTemplate.opsForHash().put(key, field, value); - - if(expire != NOT_EXPIRE){ - expire(key, expire); - } - } - - public void expire(String key, long expire){ - redisTemplate.expire(key, expire, TimeUnit.SECONDS); - } - - public void hDel(String key, Object... fields){ - redisTemplate.opsForHash().delete(key, fields); - } - - public void leftPush(String key, Object value){ - leftPush(key, value, DEFAULT_EXPIRE); - } - - public void leftPush(String key, Object value, long expire){ - redisTemplate.opsForList().leftPush(key, value); - - if(expire != NOT_EXPIRE){ - expire(key, expire); - } - } - - public Object rightPop(String key){ - return redisTemplate.opsForList().rightPop(key); - } -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/utils/Result.java b/fast-boot-framework/src/main/java/net/maku/framework/common/utils/Result.java deleted file mode 100644 index dde0e68..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/utils/Result.java +++ /dev/null @@ -1,52 +0,0 @@ -package net.maku.framework.common.utils; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; -import net.maku.framework.common.exception.ErrorCode; - -/** - * 响应数据 - * - * @author 阿沐 babamu@126.com - */ -@Data -@Schema(description = "响应") -public class Result { - @Schema(description = "编码 0表示成功,其他值表示失败") - private int code = 0; - - @Schema(description = "消息内容") - private String msg = "success"; - - @Schema(description = "响应数据") - private T data; - - public static Result ok() { - return ok(null); - } - - public static Result ok(T data) { - Result result = new Result<>(); - result.setData(data); - return result; - } - - public static Result error() { - return error(ErrorCode.INTERNAL_SERVER_ERROR); - } - - public static Result error(String msg) { - return error(ErrorCode.INTERNAL_SERVER_ERROR.getCode(), msg); - } - - public static Result error(ErrorCode errorCode) { - return error(errorCode.getCode(), errorCode.getMsg()); - } - - public static Result error(int code, String msg) { - Result result = new Result<>(); - result.setCode(code); - result.setMsg(msg); - return result; - } -} diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/utils/TreeNode.java b/fast-boot-framework/src/main/java/net/maku/framework/common/utils/TreeNode.java deleted file mode 100644 index c17b2dd..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/utils/TreeNode.java +++ /dev/null @@ -1,34 +0,0 @@ -package net.maku.framework.common.utils; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - -import javax.validation.constraints.NotNull; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -/** - * 树节点,所有需要实现树节点的,都需要继承该类 - * - * @author 阿沐 babamu@126.com - */ -@Data -public class TreeNode implements Serializable { - private static final long serialVersionUID = 1L; - /** - * 主键 - */ - @Schema(description = "id") - private Long id; - /** - * 上级ID - */ - @Schema(description = "上级ID") - @NotNull(message = "上级ID不能为空") - private Long pid; - /** - * 子节点列表 - */ - private List children = new ArrayList<>(); -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/common/utils/TreeUtils.java b/fast-boot-framework/src/main/java/net/maku/framework/common/utils/TreeUtils.java deleted file mode 100644 index 09165fc..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/common/utils/TreeUtils.java +++ /dev/null @@ -1,70 +0,0 @@ -package net.maku.framework.common.utils; - - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * 树形结构工具类,如:菜单、机构等 - * - * @author 阿沐 babamu@126.com - */ -public class TreeUtils { - - /** - * 根据pid,构建树节点 - */ - public static List build(List treeNodes, Long pid) { - // pid不能为空 - AssertUtils.isNull(pid, "pid"); - - List treeList = new ArrayList<>(); - for(T treeNode : treeNodes) { - if (pid.equals(treeNode.getPid())) { - treeList.add(findChildren(treeNodes, treeNode)); - } - } - - return treeList; - } - - /** - * 查找子节点 - */ - private static T findChildren(List treeNodes, T rootNode) { - for(T treeNode : treeNodes) { - if(rootNode.getId().equals(treeNode.getPid())) { - rootNode.getChildren().add(findChildren(treeNodes, treeNode)); - } - } - return rootNode; - } - - /** - * 构建树节点 - */ - public static List build(List treeNodes) { - List result = new ArrayList<>(); - - // list转map - Map nodeMap = new LinkedHashMap<>(treeNodes.size()); - for(T treeNode : treeNodes){ - nodeMap.put(treeNode.getId(), treeNode); - } - - for(T node : nodeMap.values()) { - T parent = nodeMap.get(node.getPid()); - if(parent != null && !(node.getId().equals(parent.getId()))){ - parent.getChildren().add(node); - continue; - } - - result.add(node); - } - - return result; - } - -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/config/CorsConfig.java b/fast-boot-framework/src/main/java/net/maku/framework/config/CorsConfig.java deleted file mode 100644 index 1329254..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/config/CorsConfig.java +++ /dev/null @@ -1,28 +0,0 @@ -package net.maku.framework.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.cors.CorsConfiguration; -import org.springframework.web.cors.UrlBasedCorsConfigurationSource; -import org.springframework.web.filter.CorsFilter; - -/** - * 跨域配置 - * - * @author 阿沐 babamu@126.com - */ -@Configuration -public class CorsConfig { - - @Bean - public CorsFilter corsFilter() { - final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); - final CorsConfiguration corsConfiguration = new CorsConfiguration(); - corsConfiguration.setAllowCredentials(true); - corsConfiguration.addAllowedHeader("*"); - corsConfiguration.addAllowedOriginPattern("*"); - corsConfiguration.addAllowedMethod("*"); - source.registerCorsConfiguration("/**", corsConfiguration); - return new CorsFilter(source); - } -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/config/MybatisPlusConfig.java b/fast-boot-framework/src/main/java/net/maku/framework/config/MybatisPlusConfig.java deleted file mode 100644 index 2c3dd51..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/config/MybatisPlusConfig.java +++ /dev/null @@ -1,39 +0,0 @@ -package net.maku.framework.config; - -import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; -import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor; -import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; -import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; -import net.maku.framework.common.handler.FieldMetaObjectHandler; -import net.maku.framework.common.interceptor.DataScopeInnerInterceptor; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * mybatis-plus 配置 - * - * @author 阿沐 babamu@126.com - */ -@Configuration -public class MybatisPlusConfig { - - @Bean - public MybatisPlusInterceptor mybatisPlusInterceptor() { - MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor(); - // 数据权限 - mybatisPlusInterceptor.addInnerInterceptor(new DataScopeInnerInterceptor()); - // 分页插件 - mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor()); - // 乐观锁 - mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); - // 防止全表更新与删除 - mybatisPlusInterceptor.addInnerInterceptor(new BlockAttackInnerInterceptor()); - - return mybatisPlusInterceptor; - } - - @Bean - public FieldMetaObjectHandler fieldMetaObjectHandler(){ - return new FieldMetaObjectHandler(); - } -} diff --git a/fast-boot-framework/src/main/java/net/maku/framework/config/RedisConfig.java b/fast-boot-framework/src/main/java/net/maku/framework/config/RedisConfig.java deleted file mode 100644 index 159cd7c..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/config/RedisConfig.java +++ /dev/null @@ -1,47 +0,0 @@ -package net.maku.framework.config; - -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.annotation.PropertyAccessor; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; -import org.springframework.data.redis.serializer.RedisSerializer; - -/** - * Redis配置 - * - * @author 阿沐 babamu@126.com - */ -@Configuration -public class RedisConfig { - - @Bean - public Jackson2JsonRedisSerializer jackson2JsonRedisSerializer(){ - Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); - objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL); - jackson2JsonRedisSerializer.setObjectMapper(objectMapper); - - return jackson2JsonRedisSerializer; - } - - @Bean - public RedisTemplate redisTemplate(RedisConnectionFactory factory) { - RedisTemplate template = new RedisTemplate<>(); - // Key HashKey使用String序列化 - template.setKeySerializer(RedisSerializer.string()); - template.setHashKeySerializer(RedisSerializer.string()); - - // Value HashValue使用Jackson2JsonRedisSerializer序列化 - template.setValueSerializer(jackson2JsonRedisSerializer()); - template.setHashValueSerializer(jackson2JsonRedisSerializer()); - - template.setConnectionFactory(factory); - return template; - } -} diff --git a/fast-boot-framework/src/main/java/net/maku/framework/config/SwaggerConfig.java b/fast-boot-framework/src/main/java/net/maku/framework/config/SwaggerConfig.java deleted file mode 100644 index e4c2afb..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/config/SwaggerConfig.java +++ /dev/null @@ -1,43 +0,0 @@ -package net.maku.framework.config; - -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.info.Contact; -import io.swagger.v3.oas.models.info.Info; -import io.swagger.v3.oas.models.info.License; -import org.springdoc.core.GroupedOpenApi; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * Swagger配置 - * - * @author 阿沐 babamu@126.com - */ -@Configuration -public class SwaggerConfig{ - - @Bean - public GroupedOpenApi userApi(){ - String[] paths = { "/**" }; - String[] packagedToMatch = { "net.maku" }; - return GroupedOpenApi.builder().group("FastBoot") - .pathsToMatch(paths) - .packagesToScan(packagedToMatch).build(); - } - - @Bean - public OpenAPI customOpenAPI() { - Contact contact= new Contact(); - contact.setName("阿沐 babamu@126.com"); - - return new OpenAPI().info(new Info() - .title("FastBoot") - .description( "FastBoot") - .contact(contact) - .version("1.0") - .termsOfService("https://maku.net") - .license(new License().name("MIT") - .url("https://maku.net"))); - } - -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/config/WebConfig.java b/fast-boot-framework/src/main/java/net/maku/framework/config/WebConfig.java deleted file mode 100644 index 483b879..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/config/WebConfig.java +++ /dev/null @@ -1,52 +0,0 @@ -package net.maku.framework.config; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.converter.ByteArrayHttpMessageConverter; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.ResourceHttpMessageConverter; -import org.springframework.http.converter.StringHttpMessageConverter; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -import java.util.List; -import java.util.TimeZone; - -/** - * Web MVC配置 - * - * @author 阿沐 babamu@126.com - */ -@Configuration -public class WebConfig implements WebMvcConfigurer { - - @Override - public void configureMessageConverters(List> converters) { - converters.add(new ByteArrayHttpMessageConverter()); - converters.add(new StringHttpMessageConverter()); - converters.add(new ResourceHttpMessageConverter()); - converters.add(new AllEncompassingFormHttpMessageConverter()); - converters.add(new StringHttpMessageConverter()); - converters.add(jackson2HttpMessageConverter()); - } - - @Bean - public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() { - MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); - ObjectMapper mapper = new ObjectMapper(); - - // 忽略未知属性 - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - - // 统一日期格式转换,不建议开启 - //mapper.setDateFormat(new SimpleDateFormat(DateUtils.DATE_TIME_PATTERN)); - mapper.setTimeZone(TimeZone.getTimeZone("GMT+8")); - - converter.setObjectMapper(mapper); - return converter; - } - -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/security/config/AuthorizationServerConfig.java b/fast-boot-framework/src/main/java/net/maku/framework/security/config/AuthorizationServerConfig.java deleted file mode 100644 index 142a9f6..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/security/config/AuthorizationServerConfig.java +++ /dev/null @@ -1,76 +0,0 @@ -package net.maku.framework.security.config; - -import lombok.AllArgsConstructor; -import net.maku.framework.security.exception.FastWebResponseExceptionTranslator; -import net.maku.framework.security.token.FastTokenEnhancer; -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.core.userdetails.UserDetailsService; -import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; -import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; -import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; -import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; -import org.springframework.security.oauth2.provider.ClientDetailsService; -import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices; -import org.springframework.security.oauth2.provider.token.TokenEnhancer; -import org.springframework.security.oauth2.provider.token.TokenStore; - -/** - * 认证服务器配置 - * - * @author 阿沐 babamu@126.com - */ -@Configuration -@AllArgsConstructor -@EnableAuthorizationServer -public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { - private final AuthenticationManager authenticationManager; - private final ClientDetailsService fastClientDetailsService; - private final UserDetailsService userDetailsService; - private final AuthorizationCodeServices redisAuthorizationCodeServices; - private final TokenStore tokenStore; - - /** - * 配置客户端信息 - */ - @Override - public void configure(ClientDetailsServiceConfigurer clients) throws Exception { - clients.withClientDetails(fastClientDetailsService); - } - - @Override - public void configure(AuthorizationServerEndpointsConfigurer endpoints) { - endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST, HttpMethod.DELETE); - // 密码模式 - endpoints.authenticationManager(authenticationManager); - // 支持刷新令牌 - endpoints.userDetailsService(userDetailsService); - // 令牌管理 - endpoints.tokenStore(tokenStore); - // 令牌增强 - endpoints.tokenEnhancer(tokenEnhancer()); - // 登录或者鉴权失败时的返回信息 - endpoints.exceptionTranslator(new FastWebResponseExceptionTranslator()); - // 配置授权码模式,存放在Redis中 - endpoints.authorizationCodeServices(redisAuthorizationCodeServices); - // 自定义登录地址 - endpoints.pathMapping("/oauth/token","/sys/oauth/token"); - } - - @Bean - public TokenEnhancer tokenEnhancer() { - return new FastTokenEnhancer(); - } - - @Override - public void configure(AuthorizationServerSecurityConfigurer security) { - security - .allowFormAuthenticationForClients() - .tokenKeyAccess("permitAll()") // 匿名可访问/oauth/token_key - .checkTokenAccess("isAuthenticated()") // 认证后可访问/oauth/check_token - ; - } -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/security/config/PasswordConfig.java b/fast-boot-framework/src/main/java/net/maku/framework/security/config/PasswordConfig.java deleted file mode 100644 index 4137a6e..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/security/config/PasswordConfig.java +++ /dev/null @@ -1,20 +0,0 @@ -package net.maku.framework.security.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.crypto.factory.PasswordEncoderFactories; -import org.springframework.security.crypto.password.PasswordEncoder; - -/** - * 加密配置 - * - * @author 阿沐 babamu@126.com - */ -@Configuration -public class PasswordConfig { - - @Bean - public PasswordEncoder passwordEncoder(){ - return PasswordEncoderFactories.createDelegatingPasswordEncoder(); - } -} diff --git a/fast-boot-framework/src/main/java/net/maku/framework/security/config/PermitResource.java b/fast-boot-framework/src/main/java/net/maku/framework/security/config/PermitResource.java deleted file mode 100644 index 8ff764a..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/security/config/PermitResource.java +++ /dev/null @@ -1,59 +0,0 @@ -package net.maku.framework.security.config; - -import lombok.SneakyThrows; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; -import org.springframework.core.io.Resource; -import org.springframework.core.io.support.PathMatchingResourcePatternResolver; -import org.springframework.core.io.support.ResourcePatternResolver; -import org.springframework.stereotype.Component; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -/** - * 允许访问的资源 - * - * @author 阿沐 babamu@126.com - */ -@Component -public class PermitResource { - /** - * 指定被 spring security oauth2.0 忽略的URL - */ - @SneakyThrows - public List getPermitList(){ - ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); - Resource[] resources = resolver.getResources("classpath*:auth.yml"); - String key = "auth.ignore_urls"; - - return getPropertiesList(key, resources); - } - - private List getPropertiesList(String key, Resource... resources){ - List list = new ArrayList<>(); - - // 解析资源文件 - for(Resource resource : resources) { - Properties properties = loadYamlProperties(resource); - - for (Map.Entry entry : properties.entrySet()) { - String tmpKey = StringUtils.substringBefore(entry.getKey().toString(), "["); - if(tmpKey.equalsIgnoreCase(key)){ - list.add(entry.getValue().toString()); - } - } - } - return list; - } - - private Properties loadYamlProperties(Resource... resources) { - YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); - factory.setResources(resources); - factory.afterPropertiesSet(); - - return factory.getObject(); - } -} diff --git a/fast-boot-framework/src/main/java/net/maku/framework/security/config/ResourceServerConfig.java b/fast-boot-framework/src/main/java/net/maku/framework/security/config/ResourceServerConfig.java deleted file mode 100644 index ca5cf45..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/security/config/ResourceServerConfig.java +++ /dev/null @@ -1,50 +0,0 @@ -package net.maku.framework.security.config; - -import lombok.AllArgsConstructor; -import net.maku.framework.security.exception.SecurityAuthenticationEntryPoint; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; -import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; -import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; -import org.springframework.security.oauth2.provider.token.TokenStore; - -import java.util.List; - -/** - * 资源服务器配置 - * - * @author 阿沐 babamu@126.com - */ -@Configuration -@AllArgsConstructor -@EnableResourceServer -@EnableGlobalMethodSecurity(prePostEnabled = true) -public class ResourceServerConfig extends ResourceServerConfigurerAdapter { - private final TokenStore tokenStore; - private final PermitResource permitResource; - - @Override - public void configure(ResourceServerSecurityConfigurer resources) { - resources.tokenStore(tokenStore); - - resources.authenticationEntryPoint(new SecurityAuthenticationEntryPoint()); - } - - @Override - public void configure(HttpSecurity http) throws Exception { - // 忽略授权的地址列表 - List permitList = permitResource.getPermitList(); - String [] permits = permitList.toArray(new String[permitList.size()]); - - http - .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) - .and() - .authorizeRequests() - .antMatchers(permits).permitAll() - .anyRequest().authenticated() - ; - } -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/security/config/TokenStoreConfig.java b/fast-boot-framework/src/main/java/net/maku/framework/security/config/TokenStoreConfig.java deleted file mode 100644 index 44ff06e..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/security/config/TokenStoreConfig.java +++ /dev/null @@ -1,25 +0,0 @@ -package net.maku.framework.security.config; - -import lombok.AllArgsConstructor; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore; - -/** - * TokenStore - * - * @author 阿沐 babamu@126.com - */ -@Configuration -@AllArgsConstructor -public class TokenStoreConfig { - private final RedisConnectionFactory redisConnectionFactory; - - @Bean - public TokenStore tokenStore() { - // 使用redis存储token - return new RedisTokenStore(redisConnectionFactory); - } -} diff --git a/fast-boot-framework/src/main/java/net/maku/framework/security/config/WebSecurityConfig.java b/fast-boot-framework/src/main/java/net/maku/framework/security/config/WebSecurityConfig.java deleted file mode 100644 index e738faf..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/security/config/WebSecurityConfig.java +++ /dev/null @@ -1,61 +0,0 @@ -package net.maku.framework.security.config; - -import lombok.AllArgsConstructor; -import org.springframework.context.annotation.Bean; -import org.springframework.http.HttpMethod; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.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.core.userdetails.UserDetailsService; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; -import org.springframework.web.filter.OncePerRequestFilter; - -/** - * Spring Security配置 - * - * @author 阿沐 babamu@126.com - */ -@AllArgsConstructor -@EnableWebSecurity -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { - private final UserDetailsService userDetailsService; - private final OncePerRequestFilter validateCodeFilter; - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(userDetailsService); - } - - /** - * 密码模式需要 - */ - @Bean - @Override - public AuthenticationManager authenticationManagerBean() throws Exception{ - return super.authenticationManager(); - } - - @Override - public void configure(HttpSecurity http) throws Exception { - http - .addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) - .formLogin() - .loginPage("/login") - .loginProcessingUrl("/login") - .and() - .authorizeRequests() - .antMatchers("/oauth/authorize").authenticated() - .anyRequest().permitAll() - .and().headers().frameOptions().disable() - .and().csrf().disable() - ; - } - - @Override - public void configure(WebSecurity web) { - web.ignoring().antMatchers(HttpMethod.OPTIONS); - } -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/security/exception/FastAuthenticationException.java b/fast-boot-framework/src/main/java/net/maku/framework/security/exception/FastAuthenticationException.java deleted file mode 100644 index 0f952a7..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/security/exception/FastAuthenticationException.java +++ /dev/null @@ -1,18 +0,0 @@ -package net.maku.framework.security.exception; - -import org.springframework.security.core.AuthenticationException; - -/** - * 认证异常类 - * - * @author 阿沐 babamu@126.com - */ -public class FastAuthenticationException extends AuthenticationException { - public FastAuthenticationException(String msg, Throwable t) { - super(msg, t); - } - - public FastAuthenticationException(String msg) { - super(msg); - } -} diff --git a/fast-boot-framework/src/main/java/net/maku/framework/security/exception/FastOAuth2Exception.java b/fast-boot-framework/src/main/java/net/maku/framework/security/exception/FastOAuth2Exception.java deleted file mode 100644 index bf7d7d7..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/security/exception/FastOAuth2Exception.java +++ /dev/null @@ -1,31 +0,0 @@ -package net.maku.framework.security.exception; - -import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; - -/** - * 自定义异常 - * - * @author 阿沐 babamu@126.com - */ -public class FastOAuth2Exception extends OAuth2Exception { - private String msg; - - public FastOAuth2Exception(String msg) { - super(msg); - this.msg = msg; - } - - public FastOAuth2Exception(String msg, Throwable e) { - super(msg, e); - this.msg = msg; - } - - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/security/exception/FastWebResponseExceptionTranslator.java b/fast-boot-framework/src/main/java/net/maku/framework/security/exception/FastWebResponseExceptionTranslator.java deleted file mode 100644 index b3862b3..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/security/exception/FastWebResponseExceptionTranslator.java +++ /dev/null @@ -1,78 +0,0 @@ -package net.maku.framework.security.exception; - -import net.maku.framework.common.exception.ErrorCode; -import net.maku.framework.common.utils.Result; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.AccessDeniedException; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.oauth2.common.DefaultThrowableAnalyzer; -import org.springframework.security.oauth2.common.OAuth2AccessToken; -import org.springframework.security.oauth2.common.exceptions.ClientAuthenticationException; -import org.springframework.security.oauth2.common.exceptions.InsufficientScopeException; -import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; -import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; -import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator; -import org.springframework.security.web.util.ThrowableAnalyzer; -import org.springframework.stereotype.Component; -import org.springframework.web.HttpRequestMethodNotSupportedException; - -/** - * 登录或者鉴权失败时的返回信息 - * - * @author 阿沐 babamu@126.com - */ -@Component -public class FastWebResponseExceptionTranslator implements WebResponseExceptionTranslator { - private final ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer(); - - @Override - public ResponseEntity translate(Exception e) { - Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e); - - Exception exception = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain); - if (exception != null) { - return handleOAuth2Exception(new FastOAuth2Exception(e.getMessage(), e)); - } - - exception = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain); - if (exception != null) { - return handleOAuth2Exception(new FastOAuth2Exception(exception.getMessage(), exception)); - } - - exception = (InvalidGrantException) throwableAnalyzer.getFirstThrowableOfType(InvalidGrantException.class, causeChain); - if (exception != null) { - return handleOAuth2Exception(new FastOAuth2Exception(exception.getMessage(), exception)); - } - - exception = (HttpRequestMethodNotSupportedException) throwableAnalyzer.getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain); - if (exception != null) { - return handleOAuth2Exception(new FastOAuth2Exception(exception.getMessage(), exception)); - } - - exception = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain); - if (exception != null) { - return handleOAuth2Exception((OAuth2Exception) exception); - } - - return handleOAuth2Exception(new FastOAuth2Exception(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), e)); - } - - private ResponseEntity handleOAuth2Exception(OAuth2Exception e) { - int status = e.getHttpErrorCode(); - HttpHeaders headers = new HttpHeaders(); - headers.set(HttpHeaders.CACHE_CONTROL, "no-store"); - headers.set(HttpHeaders.PRAGMA, "no-cache"); - if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) { - headers.set(HttpHeaders.WWW_AUTHENTICATE, String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary())); - } - - if (e instanceof ClientAuthenticationException) { - return new ResponseEntity<>(e, headers, HttpStatus.valueOf(status)); - } - Result result = Result.error(ErrorCode.ACCOUNT_PASSWORD_ERROR); - - return new ResponseEntity(result, headers, HttpStatus.OK); - } -} diff --git a/fast-boot-framework/src/main/java/net/maku/framework/security/exception/SecurityAuthenticationEntryPoint.java b/fast-boot-framework/src/main/java/net/maku/framework/security/exception/SecurityAuthenticationEntryPoint.java deleted file mode 100644 index eb9f3fd..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/security/exception/SecurityAuthenticationEntryPoint.java +++ /dev/null @@ -1,29 +0,0 @@ -package net.maku.framework.security.exception; - -import net.maku.framework.common.exception.ErrorCode; -import net.maku.framework.common.utils.HttpContextUtils; -import net.maku.framework.common.utils.JsonUtils; -import net.maku.framework.common.utils.Result; -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; - -/** - * 匿名用户(token不存在、错误),异常处理器 - * - * @author 阿沐 babamu@126.com - */ -public class SecurityAuthenticationEntryPoint implements AuthenticationEntryPoint { - - @Override - public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { - response.setContentType("application/json; charset=utf-8"); - response.setHeader("Access-Control-Allow-Credentials", "true"); - response.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin()); - - response.getWriter().print(JsonUtils.toJsonString(Result.error(ErrorCode.UNAUTHORIZED))); - } -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/security/handler/UserAuthenticationFailureHandler.java b/fast-boot-framework/src/main/java/net/maku/framework/security/handler/UserAuthenticationFailureHandler.java deleted file mode 100644 index cc25d78..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/security/handler/UserAuthenticationFailureHandler.java +++ /dev/null @@ -1,31 +0,0 @@ -package net.maku.framework.security.handler; - -import lombok.SneakyThrows; -import net.maku.framework.common.utils.HttpContextUtils; -import net.maku.framework.common.utils.JsonUtils; -import net.maku.framework.common.utils.Result; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; -import org.springframework.stereotype.Component; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * 认证失败处理器 - * - * @author 阿沐 babamu@126.com - */ -@Component -public class UserAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { - - @SneakyThrows - @Override - public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) { - response.setContentType("application/json;charset=UTF-8"); - response.setHeader("Access-Control-Allow-Credentials", "true"); - response.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin()); - - response.getWriter().write(JsonUtils.toJsonString(Result.error(e.getMessage()))); - } -} diff --git a/fast-boot-framework/src/main/java/net/maku/framework/security/token/FastTokenEnhancer.java b/fast-boot-framework/src/main/java/net/maku/framework/security/token/FastTokenEnhancer.java deleted file mode 100644 index 82578d7..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/security/token/FastTokenEnhancer.java +++ /dev/null @@ -1,34 +0,0 @@ -package net.maku.framework.security.token; - -import net.maku.framework.common.utils.Result; -import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; -import org.springframework.security.oauth2.common.OAuth2AccessToken; -import org.springframework.security.oauth2.provider.OAuth2Authentication; -import org.springframework.security.oauth2.provider.token.TokenEnhancer; - -import java.util.HashMap; -import java.util.Map; - -/** - * 令牌 - * - * @author 阿沐 babamu@126.com - */ -public class FastTokenEnhancer implements TokenEnhancer { - - @Override - public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { - if(accessToken instanceof DefaultOAuth2AccessToken){ - DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken; - - // 增加额外信息 - Map info = new HashMap<>(); - info.put("code", new Result<>().getCode()); - token.setAdditionalInformation(info); - - return token; - } - - return accessToken; - } -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/security/user/SecurityUser.java b/fast-boot-framework/src/main/java/net/maku/framework/security/user/SecurityUser.java deleted file mode 100644 index 76bba4b..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/security/user/SecurityUser.java +++ /dev/null @@ -1,33 +0,0 @@ -package net.maku.framework.security.user; - -import org.springframework.security.core.context.SecurityContextHolder; - -/** - * 用户 - * - * @author 阿沐 babamu@126.com - */ -public class SecurityUser { - - /** - * 获取用户信息 - */ - public static UserDetail getUser() { - UserDetail user; - try { - user = (UserDetail)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - }catch (Exception e){ - return new UserDetail(); - } - - return user; - } - - /** - * 获取用户ID - */ - public static Long getUserId() { - return getUser().getId(); - } - -} \ No newline at end of file diff --git a/fast-boot-framework/src/main/java/net/maku/framework/security/user/UserDetail.java b/fast-boot-framework/src/main/java/net/maku/framework/security/user/UserDetail.java deleted file mode 100644 index f6753be..0000000 --- a/fast-boot-framework/src/main/java/net/maku/framework/security/user/UserDetail.java +++ /dev/null @@ -1,84 +0,0 @@ -package net.maku.framework.security.user; - -import lombok.Data; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; - -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.Set; - -/** - * 登录用户信息 - * - * @author 阿沐 babamu@126.com - */ -@Data -public class UserDetail implements UserDetails { - private static final long serialVersionUID = 1L; - - private Long id; - private String username; - private String password; - private String realName; - private String avatar; - private Integer gender; - private String email; - private String mobile; - private Long orgId; - private Integer status; - private Integer superAdmin; - private Date createTime; - /** - * 数据权限范围 - * - * null:表示全部数据权限 - */ - private List dataScopeList; - /** - * 帐户是否过期 - */ - private boolean isAccountNonExpired = true; - /** - * 帐户是否被锁定 - */ - private boolean isAccountNonLocked = true; - /** - * 密码是否过期 - */ - private boolean isCredentialsNonExpired = true; - /** - * 帐户是否可用 - */ - private boolean isEnabled = true; - /** - * 拥有权限集合 - */ - private Set authorities; - - @Override - public Collection getAuthorities() { - return this.authorities; - } - - @Override - public boolean isAccountNonExpired() { - return this.isAccountNonExpired; - } - - @Override - public boolean isAccountNonLocked() { - return this.isAccountNonLocked; - } - - @Override - public boolean isCredentialsNonExpired() { - return this.isCredentialsNonExpired; - } - - @Override - public boolean isEnabled() { - return this.isEnabled; - } -} \ No newline at end of file diff --git a/fast-boot-new/pom.xml b/fast-boot-new/pom.xml index 3a75a3c..3936d16 100644 --- a/fast-boot-new/pom.xml +++ b/fast-boot-new/pom.xml @@ -11,7 +11,7 @@ net.maku - fast-boot-framework + fast-framework 1.0.0 diff --git a/fast-boot-system/pom.xml b/fast-boot-system/pom.xml index c3d9d9f..42bbd87 100644 --- a/fast-boot-system/pom.xml +++ b/fast-boot-system/pom.xml @@ -11,7 +11,7 @@ net.maku - fast-boot-framework + fast-framework 1.0.0 diff --git a/fast-framework/pom.xml b/fast-framework/pom.xml new file mode 100644 index 0000000..1a5e413 --- /dev/null +++ b/fast-framework/pom.xml @@ -0,0 +1,69 @@ + + + net.maku + fast-boot + 1.0.0 + + 4.0.0 + fast-framework + jar + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.boot + spring-boot-starter-security + + + kotlin-stdlib-jdk7 + org.jetbrains.kotlin + + + kotlin-stdlib-jdk8 + org.jetbrains.kotlin + + + + + org.springframework.security.oauth + spring-security-oauth2 + + + mysql + mysql-connector-java + + + com.baomidou + mybatis-plus-boot-starter + + + org.springdoc + springdoc-openapi-ui + + + cn.hutool + hutool-all + + + \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/common/constant/Constant.java b/fast-framework/src/main/java/net/maku/framework/common/constant/Constant.java new file mode 100644 index 0000000..91b95bd --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/constant/Constant.java @@ -0,0 +1,25 @@ +package net.maku.framework.common.constant; + +/** + * 常量 + * + * @author 阿沐 babamu@126.com + */ +public interface Constant { + /** + * 根节点标识 + */ + Long ROOT = 0L; + /** + * 当前页码 + */ + String PAGE = "page"; + /** + * 数据权限 + */ + String DATA_SCOPE = "dataScope"; + /** + * 超级管理员 + */ + Integer SUPER_ADMIN = 1; +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/common/dao/BaseDao.java b/fast-framework/src/main/java/net/maku/framework/common/dao/BaseDao.java new file mode 100644 index 0000000..ce38e5b --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/dao/BaseDao.java @@ -0,0 +1,13 @@ +package net.maku.framework.common.dao; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** + * 基础Dao + * + * @author 阿沐 babamu@126.com + */ +public interface BaseDao extends BaseMapper { + +} diff --git a/fast-framework/src/main/java/net/maku/framework/common/entity/BaseEntity.java b/fast-framework/src/main/java/net/maku/framework/common/entity/BaseEntity.java new file mode 100644 index 0000000..7e31e1b --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/entity/BaseEntity.java @@ -0,0 +1,58 @@ +package net.maku.framework.common.entity; + +import com.baomidou.mybatisplus.annotation.*; +import lombok.Data; + +import java.util.Date; + +/** + * Entity基类 + * + * @author 阿沐 babamu@126.com + */ +@Data +public abstract class BaseEntity { + /** + * id + */ + @TableId + private Long id; + + /** + * 创建者 + */ + @TableField(fill = FieldFill.INSERT) + private Long creator; + + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + /** + * 更新者 + */ + @TableField(fill = FieldFill.INSERT_UPDATE) + private Long updater; + + /** + * 更新时间 + */ + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + + /** + * 版本号 + */ + @Version + @TableField(fill = FieldFill.INSERT) + private Integer version; + + /** + * 删除标记 + */ + @TableLogic + @TableField(fill = FieldFill.INSERT) + private Integer deleted; +} diff --git a/fast-framework/src/main/java/net/maku/framework/common/exception/ErrorCode.java b/fast-framework/src/main/java/net/maku/framework/common/exception/ErrorCode.java new file mode 100644 index 0000000..af25107 --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/exception/ErrorCode.java @@ -0,0 +1,21 @@ +package net.maku.framework.common.exception; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +/** + * 错误编码 + * + * @author 阿沐 babamu@126.com +*/ +@Getter +@AllArgsConstructor +public enum ErrorCode { + UNAUTHORIZED(401, "还未授权,不能访问"), + FORBIDDEN(403, "没有权限,禁止访问"), + INTERNAL_SERVER_ERROR(500, "服务器异常,请稍后再试"), + ACCOUNT_PASSWORD_ERROR(1001, "账号或密码错误"); + + private final int code; + private final String msg; +} diff --git a/fast-framework/src/main/java/net/maku/framework/common/exception/FastException.java b/fast-framework/src/main/java/net/maku/framework/common/exception/FastException.java new file mode 100644 index 0000000..57f0aad --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/exception/FastException.java @@ -0,0 +1,37 @@ +package net.maku.framework.common.exception; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * 自定义异常 + * + * @author 阿沐 babamu@126.com + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class FastException extends RuntimeException { + private static final long serialVersionUID = 1L; + + private int code; + private String msg; + + public FastException(String msg) { + super(msg); + this.code = ErrorCode.INTERNAL_SERVER_ERROR.getCode(); + this.msg = msg; + } + + public FastException(ErrorCode errorCode) { + super(errorCode.getMsg()); + this.code = errorCode.getCode(); + this.msg = errorCode.getMsg(); + } + + public FastException(String msg, Throwable e) { + super(msg, e); + this.code = ErrorCode.INTERNAL_SERVER_ERROR.getCode(); + this.msg = msg; + } + +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/common/exception/FastExceptionHandler.java b/fast-framework/src/main/java/net/maku/framework/common/exception/FastExceptionHandler.java new file mode 100644 index 0000000..336b9f6 --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/exception/FastExceptionHandler.java @@ -0,0 +1,51 @@ +package net.maku.framework.common.exception; + +import lombok.extern.slf4j.Slf4j; +import net.maku.framework.common.utils.Result; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.validation.BindException; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + + +/** + * 异常处理器 + * + * @author 阿沐 babamu@126.com + */ +@Slf4j +@RestControllerAdvice +public class FastExceptionHandler { + /** + * 处理自定义异常 + */ + @ExceptionHandler(FastException.class) + public Result handleException(FastException ex){ + + return Result.error(ex.getCode(), ex.getMsg()); + } + + /** + * SpringMVC参数绑定,Validator校验不正确 + */ + @ExceptionHandler(BindException.class) + public Result bindException(BindException ex) { + FieldError fieldError = ex.getFieldError(); + assert fieldError != null; + return Result.error(fieldError.getDefaultMessage()); + } + + @ExceptionHandler(AccessDeniedException.class) + public Result handleAccessDeniedException(Exception ex){ + + return Result.error(ErrorCode.FORBIDDEN); + } + + @ExceptionHandler(Exception.class) + public Result handleException(Exception ex){ + log.error(ex.getMessage(), ex); + return Result.error(ErrorCode.INTERNAL_SERVER_ERROR); + } + +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/common/handler/FieldMetaObjectHandler.java b/fast-framework/src/main/java/net/maku/framework/common/handler/FieldMetaObjectHandler.java new file mode 100644 index 0000000..6e55769 --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/handler/FieldMetaObjectHandler.java @@ -0,0 +1,52 @@ +package net.maku.framework.common.handler; + +import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; +import net.maku.framework.security.user.SecurityUser; +import net.maku.framework.security.user.UserDetail; +import org.apache.ibatis.reflection.MetaObject; + +import java.util.Date; + +/** + * mybatis-plus 自动填充字段 + * + * @author 阿沐 babamu@126.com + */ +public class FieldMetaObjectHandler implements MetaObjectHandler { + private final static String CREATE_TIME = "createTime"; + private final static String CREATOR = "creator"; + private final static String UPDATE_TIME = "updateTime"; + private final static String UPDATER = "updater"; + private final static String ORG_ID = "orgId"; + private final static String VERSION = "version"; + private final static String DELETED = "deleted"; + + @Override + public void insertFill(MetaObject metaObject) { + UserDetail user = SecurityUser.getUser(); + Date date = new Date(); + + // 创建者 + strictInsertFill(metaObject, CREATOR, Long.class, user.getId()); + // 创建时间 + strictInsertFill(metaObject, CREATE_TIME, Date.class, date); + // 更新者 + strictInsertFill(metaObject, UPDATER, Long.class, user.getId()); + // 更新时间 + strictInsertFill(metaObject, UPDATE_TIME, Date.class, date); + // 创建者所属机构 + strictInsertFill(metaObject, ORG_ID, Long.class, user.getOrgId()); + // 版本号 + strictInsertFill(metaObject, VERSION, Integer.class, 0); + // 删除标识 + strictInsertFill(metaObject, DELETED, Integer.class, 0); + } + + @Override + public void updateFill(MetaObject metaObject) { + // 更新者 + strictUpdateFill(metaObject, UPDATER, Long.class, SecurityUser.getUserId()); + // 更新时间 + strictUpdateFill(metaObject, UPDATE_TIME, Date.class, new Date()); + } +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/common/interceptor/DataScope.java b/fast-framework/src/main/java/net/maku/framework/common/interceptor/DataScope.java new file mode 100644 index 0000000..2cec15a --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/interceptor/DataScope.java @@ -0,0 +1,16 @@ +package net.maku.framework.common.interceptor; + +import lombok.AllArgsConstructor; +import lombok.Data; + +/** + * 数据范围 + * + * @author 阿沐 babamu@126.com + */ +@Data +@AllArgsConstructor +public class DataScope { + private String sqlFilter; + +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/common/interceptor/DataScopeInnerInterceptor.java b/fast-framework/src/main/java/net/maku/framework/common/interceptor/DataScopeInnerInterceptor.java new file mode 100644 index 0000000..e00795c --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/interceptor/DataScopeInnerInterceptor.java @@ -0,0 +1,81 @@ +package net.maku.framework.common.interceptor; + +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.toolkit.PluginUtils; +import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor; +import net.sf.jsqlparser.JSQLParserException; +import net.sf.jsqlparser.expression.Expression; +import net.sf.jsqlparser.expression.StringValue; +import net.sf.jsqlparser.expression.operators.conditional.AndExpression; +import net.sf.jsqlparser.parser.CCJSqlParserUtil; +import net.sf.jsqlparser.statement.select.PlainSelect; +import net.sf.jsqlparser.statement.select.Select; +import org.apache.ibatis.executor.Executor; +import org.apache.ibatis.mapping.BoundSql; +import org.apache.ibatis.mapping.MappedStatement; +import org.apache.ibatis.session.ResultHandler; +import org.apache.ibatis.session.RowBounds; + +import java.util.Map; + +/** + * 数据权限 + * + * @author 阿沐 babamu@126.com + */ +public class DataScopeInnerInterceptor implements InnerInterceptor { + + @Override + public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) { + DataScope scope = getDataScope(parameter); + // 不进行数据过滤 + if(scope == null || StrUtil.isBlank(scope.getSqlFilter())){ + return; + } + + // 拼接新SQL + String buildSql = getSelect(boundSql.getSql(), scope); + + // 重写SQL + PluginUtils.mpBoundSql(boundSql).sql(buildSql); + } + + private DataScope getDataScope(Object parameter){ + if (parameter == null){ + return null; + } + + // 判断参数里是否有DataScope对象 + if (parameter instanceof Map) { + Map parameterMap = (Map) parameter; + for (Map.Entry entry : parameterMap.entrySet()) { + if (entry.getValue() != null && entry.getValue() instanceof DataScope) { + return (DataScope) entry.getValue(); + } + } + } else if (parameter instanceof DataScope) { + return (DataScope) parameter; + } + + return null; + } + + private String getSelect(String buildSql, DataScope scope){ + try { + Select select = (Select) CCJSqlParserUtil.parse(buildSql); + PlainSelect plainSelect = (PlainSelect) select.getSelectBody(); + + Expression expression = plainSelect.getWhere(); + if(expression == null){ + plainSelect.setWhere(new StringValue(scope.getSqlFilter())); + }else{ + AndExpression andExpression = new AndExpression(expression, new StringValue(scope.getSqlFilter())); + plainSelect.setWhere(andExpression); + } + + return select.toString().replaceAll("'", ""); + }catch (JSQLParserException e){ + return buildSql; + } + } +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/common/page/PageResult.java b/fast-framework/src/main/java/net/maku/framework/common/page/PageResult.java new file mode 100644 index 0000000..9633a45 --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/page/PageResult.java @@ -0,0 +1,34 @@ +package net.maku.framework.common.page; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +/** + * 分页工具类 + * + * @author 阿沐 babamu@126.com + */ +@Data +@Schema(description = "分页数据") +public class PageResult implements Serializable { + private static final long serialVersionUID = 1L; + + @Schema(description = "总记录数") + private int total; + + @Schema(description = "列表数据") + private List list; + + /** + * 分页 + * @param list 列表数据 + * @param total 总记录数 + */ + public PageResult(List list, long total) { + this.list = list; + this.total = (int)total; + } +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/common/query/Query.java b/fast-framework/src/main/java/net/maku/framework/common/query/Query.java new file mode 100644 index 0000000..b5c3bdb --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/query/Query.java @@ -0,0 +1,32 @@ +package net.maku.framework.common.query; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; +import org.hibernate.validator.constraints.Range; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; + +/** + * 查询公共参数 + * + * @author 阿沐 babamu@126.com + */ +@Data +public class Query { + @NotNull(message = "页码不能为空") + @Min(value = 1, message = "页码最小值为 1") + @Schema(description = "当前页码", required = true) + Integer page; + + @NotNull(message = "每页条数不能为空") + @Range(min = 1, max = 1000, message = "每页条数,取值范围 1-1000") + @Schema(description = "每页条数", required = true) + Integer limit; + + @Schema(description = "排序字段") + String order; + + @Schema(description = "是否升序") + boolean asc; +} diff --git a/fast-framework/src/main/java/net/maku/framework/common/service/BaseService.java b/fast-framework/src/main/java/net/maku/framework/common/service/BaseService.java new file mode 100644 index 0000000..fcd3722 --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/service/BaseService.java @@ -0,0 +1,13 @@ +package net.maku.framework.common.service; + +import com.baomidou.mybatisplus.extension.service.IService; + +/** + * 基础服务接口,所有Service接口都要继承 + * + * @author 阿沐 babamu@126.com + */ +public interface BaseService extends IService { + + +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/common/service/impl/BaseServiceImpl.java b/fast-framework/src/main/java/net/maku/framework/common/service/impl/BaseServiceImpl.java new file mode 100644 index 0000000..5d9b790 --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/service/impl/BaseServiceImpl.java @@ -0,0 +1,109 @@ +package net.maku.framework.common.service.impl; + +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.metadata.OrderItem; +import com.baomidou.mybatisplus.core.toolkit.StringUtils; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import net.maku.framework.common.constant.Constant; +import net.maku.framework.common.interceptor.DataScope; +import net.maku.framework.common.query.Query; +import net.maku.framework.common.service.BaseService; +import net.maku.framework.security.user.SecurityUser; +import net.maku.framework.security.user.UserDetail; + +import java.util.List; + + +/** + * 基础服务类,所有Service都要继承 + * + * @author 阿沐 babamu@126.com + */ +public class BaseServiceImpl, T> extends ServiceImpl implements BaseService { + + /** + * 获取分页对象 + * @param query 分页参数 + */ + protected IPage getPage(Query query) { + Page page = new Page<>(query.getPage(), query.getLimit()); + + // 排序 + if(StringUtils.isNotBlank(query.getOrder())){ + if(query.isAsc()) { + return page.addOrder(OrderItem.asc(query.getOrder())); + }else { + return page.addOrder(OrderItem.desc(query.getOrder())); + } + } + + return page; + } + + /** + * 原生SQL 数据权限 + * @param tableAlias 表别名,多表关联时,需要填写表别名 + * @param orgIdAlias 机构ID别名,null:表示org_id + * @return 返回数据权限 + */ + protected DataScope getDataScope(String tableAlias, String orgIdAlias) { + UserDetail user = SecurityUser.getUser(); + // 如果是超级管理员,则不进行数据过滤 + if(user.getSuperAdmin().equals(Constant.SUPER_ADMIN)) { + return null; + } + + // 如果为null,则设置成空字符串 + if(tableAlias == null){ + tableAlias = ""; + } + + // 获取表的别名 + if(StringUtils.isNotBlank(tableAlias)){ + tableAlias += "."; + } + + StringBuilder sqlFilter = new StringBuilder(); + sqlFilter.append(" ("); + + // 数据权限范围 + List dataScopeList = user.getDataScopeList(); + // 全部数据权限 + if (dataScopeList == null){ + return null; + } + // 数据过滤 + if(dataScopeList.size() > 0){ + if(StringUtils.isBlank(orgIdAlias)){ + orgIdAlias = "org_id"; + } + sqlFilter.append(tableAlias).append(orgIdAlias); + + sqlFilter.append(" in(").append(StrUtil.join(",", dataScopeList)).append(")"); + + sqlFilter.append(" or "); + } + + // 查询本人数据 + sqlFilter.append(tableAlias).append("creator").append("=").append(user.getId()); + + sqlFilter.append(")"); + + return new DataScope(sqlFilter.toString()); + } + + /** + * MyBatis-Plus 数据权限 + */ + protected void dataScopeWrapper(LambdaQueryWrapper queryWrapper) { + DataScope dataScope = getDataScope(null, null); + if (dataScope != null){ + queryWrapper.apply(dataScope.getSqlFilter()); + } + } + +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/common/utils/AssertUtils.java b/fast-framework/src/main/java/net/maku/framework/common/utils/AssertUtils.java new file mode 100644 index 0000000..094d60a --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/utils/AssertUtils.java @@ -0,0 +1,32 @@ +package net.maku.framework.common.utils; + +import cn.hutool.core.util.ArrayUtil; +import cn.hutool.core.util.StrUtil; +import net.maku.framework.common.exception.FastException; + +/** + * 校验工具类 + * + * @author 阿沐 babamu@126.com + */ +public class AssertUtils { + + public static void isBlank(String str, String variable) { + if (StrUtil.isBlank(str)) { + throw new FastException(variable + "不能为空"); + } + } + + public static void isNull(Object object, String variable) { + if (object == null) { + throw new FastException(variable + "不能为空"); + } + } + + public static void isArrayEmpty(Object[] array, String variable) { + if(ArrayUtil.isEmpty(array)){ + throw new FastException(variable + "不能为空"); + } + } + +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/common/utils/DateUtils.java b/fast-framework/src/main/java/net/maku/framework/common/utils/DateUtils.java new file mode 100644 index 0000000..a5ae202 --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/utils/DateUtils.java @@ -0,0 +1,56 @@ +package net.maku.framework.common.utils; + + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * 日期处理 + * + * @author 阿沐 babamu@126.com + */ +public class DateUtils { + /** 时间格式(yyyy-MM-dd) */ + public final static String DATE_PATTERN = "yyyy-MM-dd"; + /** 时间格式(yyyy-MM-dd HH:mm:ss) */ + public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; + + /** + * 日期格式化 日期格式为:yyyy-MM-dd + * @param date 日期 + * @return 返回yyyy-MM-dd格式日期 + */ + public static String format(Date date) { + return format(date, DATE_PATTERN); + } + + /** + * 日期格式化 日期格式为:yyyy-MM-dd + * @param date 日期 + * @param pattern 格式,如:DateUtils.DATE_TIME_PATTERN + * @return 返回yyyy-MM-dd格式日期 + */ + public static String format(Date date, String pattern) { + if(date != null){ + SimpleDateFormat df = new SimpleDateFormat(pattern); + return df.format(date); + } + return null; + } + + /** + * 日期解析 + * @param date 日期 + * @param pattern 格式,如:DateUtils.DATE_TIME_PATTERN + * @return 返回Date + */ + public static Date parse(String date, String pattern) { + try { + return new SimpleDateFormat(pattern).parse(date); + } catch (ParseException e) { + e.printStackTrace(); + } + return null; + } +} diff --git a/fast-framework/src/main/java/net/maku/framework/common/utils/HttpContextUtils.java b/fast-framework/src/main/java/net/maku/framework/common/utils/HttpContextUtils.java new file mode 100644 index 0000000..4928c4a --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/utils/HttpContextUtils.java @@ -0,0 +1,55 @@ +package net.maku.framework.common.utils; + +import cn.hutool.core.util.StrUtil; +import org.springframework.http.HttpHeaders; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; + +/** + * Http + * + * @author 阿沐 babamu@126.com + */ +public class HttpContextUtils { + + public static HttpServletRequest getHttpServletRequest() { + RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); + if(requestAttributes == null){ + return null; + } + + return ((ServletRequestAttributes) requestAttributes).getRequest(); + } + + public static Map getParameterMap(HttpServletRequest request) { + Enumeration parameters = request.getParameterNames(); + + Map params = new HashMap<>(); + while (parameters.hasMoreElements()) { + String parameter = parameters.nextElement(); + String value = request.getParameter(parameter); + if (StrUtil.isNotBlank(value)) { + params.put(parameter, value); + } + } + + return params; + } + + public static String getDomain(){ + HttpServletRequest request = getHttpServletRequest(); + StringBuffer url = request.getRequestURL(); + return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString(); + } + + public static String getOrigin(){ + HttpServletRequest request = getHttpServletRequest(); + return request.getHeader(HttpHeaders.ORIGIN); + } +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/common/utils/JsonUtils.java b/fast-framework/src/main/java/net/maku/framework/common/utils/JsonUtils.java new file mode 100644 index 0000000..89d99af --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/utils/JsonUtils.java @@ -0,0 +1,68 @@ +package net.maku.framework.common.utils; + +import cn.hutool.core.util.ArrayUtil; +import cn.hutool.core.util.StrUtil; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.util.ArrayList; +import java.util.List; + +/** + * JSON 工具类 + * + * @author 阿沐 babamu@126.com + */ +public class JsonUtils { + private static final ObjectMapper objectMapper = new ObjectMapper(); + + public static String toJsonString(Object object) { + try { + return objectMapper.writeValueAsString(object); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static T parseObject(String text, Class clazz) { + if (StrUtil.isEmpty(text)) { + return null; + } + try { + return objectMapper.readValue(text, clazz); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static T parseObject(byte[] bytes, Class clazz) { + if (ArrayUtil.isEmpty(bytes)) { + return null; + } + try { + return objectMapper.readValue(bytes, clazz); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static T parseObject(String text, TypeReference typeReference) { + try { + return objectMapper.readValue(text, typeReference); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static List parseArray(String text, Class clazz) { + if (StrUtil.isEmpty(text)) { + return new ArrayList<>(); + } + try { + return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/fast-framework/src/main/java/net/maku/framework/common/utils/RedisKeys.java b/fast-framework/src/main/java/net/maku/framework/common/utils/RedisKeys.java new file mode 100644 index 0000000..2cbea83 --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/utils/RedisKeys.java @@ -0,0 +1,44 @@ +package net.maku.framework.common.utils; + +/** + * Redis Key管理 + * + * @author 阿沐 babamu@126.com + */ +public class RedisKeys { + + /** + * 验证码Key + */ + public static String getCaptchaKey(String key) { + return "sys:captcha:" + key; + } + + /** + * 授权码Key + */ + public static String getOauthCode(String code) { + return "oauth:code:" + code; + } + + /** + * 微信小程序授权key + * + * @param key + * @return + */ + public static String getWxMpAuthKey(String key) { + return "wx:mp:auth:" + key; + } + + /** + * 微信小程序授权类型key + * + * @param key + * @return + */ + public static String getWxMpAuthTypeKey(String key) { + return "wx:mp:auth:type:" + key; + } + +} diff --git a/fast-framework/src/main/java/net/maku/framework/common/utils/RedisUtils.java b/fast-framework/src/main/java/net/maku/framework/common/utils/RedisUtils.java new file mode 100644 index 0000000..6cb0a0a --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/utils/RedisUtils.java @@ -0,0 +1,118 @@ +package net.maku.framework.common.utils; + +import org.springframework.data.redis.core.HashOperations; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.Collection; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** + * Redis工具类 + * + * @author 阿沐 babamu@126.com + */ +@Component +public class RedisUtils { + @Resource + private RedisTemplate redisTemplate; + + /** 默认过期时长为24小时,单位:秒 */ + public final static long DEFAULT_EXPIRE = 60 * 60 * 24L; + /** 过期时长为1小时,单位:秒 */ + public final static long HOUR_ONE_EXPIRE = 60 * 60 * 1L; + /** 过期时长为6小时,单位:秒 */ + public final static long HOUR_SIX_EXPIRE = 60 * 60 * 6L; + /** 不设置过期时长 */ + public final static long NOT_EXPIRE = -1L; + + public void set(String key, Object value, long expire){ + redisTemplate.opsForValue().set(key, value); + if(expire != NOT_EXPIRE){ + expire(key, expire); + } + } + + public void set(String key, Object value){ + set(key, value, DEFAULT_EXPIRE); + } + + public Object get(String key, long expire) { + Object value = redisTemplate.opsForValue().get(key); + if(expire != NOT_EXPIRE){ + expire(key, expire); + } + return value; + } + + public Object get(String key) { + return get(key, NOT_EXPIRE); + } + + public void delete(String key) { + redisTemplate.delete(key); + } + + public void delete(Collection keys) { + redisTemplate.delete(keys); + } + + public Object hGet(String key, String field) { + return redisTemplate.opsForHash().get(key, field); + } + + public Map hGetAll(String key){ + HashOperations hashOperations = redisTemplate.opsForHash(); + return hashOperations.entries(key); + } + + public void hMSet(String key, Map map){ + hMSet(key, map, DEFAULT_EXPIRE); + } + + public void hMSet(String key, Map map, long expire){ + redisTemplate.opsForHash().putAll(key, map); + + if(expire != NOT_EXPIRE){ + expire(key, expire); + } + } + + public void hSet(String key, String field, Object value) { + hSet(key, field, value, DEFAULT_EXPIRE); + } + + public void hSet(String key, String field, Object value, long expire) { + redisTemplate.opsForHash().put(key, field, value); + + if(expire != NOT_EXPIRE){ + expire(key, expire); + } + } + + public void expire(String key, long expire){ + redisTemplate.expire(key, expire, TimeUnit.SECONDS); + } + + public void hDel(String key, Object... fields){ + redisTemplate.opsForHash().delete(key, fields); + } + + public void leftPush(String key, Object value){ + leftPush(key, value, DEFAULT_EXPIRE); + } + + public void leftPush(String key, Object value, long expire){ + redisTemplate.opsForList().leftPush(key, value); + + if(expire != NOT_EXPIRE){ + expire(key, expire); + } + } + + public Object rightPop(String key){ + return redisTemplate.opsForList().rightPop(key); + } +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/common/utils/Result.java b/fast-framework/src/main/java/net/maku/framework/common/utils/Result.java new file mode 100644 index 0000000..dde0e68 --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/utils/Result.java @@ -0,0 +1,52 @@ +package net.maku.framework.common.utils; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; +import net.maku.framework.common.exception.ErrorCode; + +/** + * 响应数据 + * + * @author 阿沐 babamu@126.com + */ +@Data +@Schema(description = "响应") +public class Result { + @Schema(description = "编码 0表示成功,其他值表示失败") + private int code = 0; + + @Schema(description = "消息内容") + private String msg = "success"; + + @Schema(description = "响应数据") + private T data; + + public static Result ok() { + return ok(null); + } + + public static Result ok(T data) { + Result result = new Result<>(); + result.setData(data); + return result; + } + + public static Result error() { + return error(ErrorCode.INTERNAL_SERVER_ERROR); + } + + public static Result error(String msg) { + return error(ErrorCode.INTERNAL_SERVER_ERROR.getCode(), msg); + } + + public static Result error(ErrorCode errorCode) { + return error(errorCode.getCode(), errorCode.getMsg()); + } + + public static Result error(int code, String msg) { + Result result = new Result<>(); + result.setCode(code); + result.setMsg(msg); + return result; + } +} diff --git a/fast-framework/src/main/java/net/maku/framework/common/utils/TreeNode.java b/fast-framework/src/main/java/net/maku/framework/common/utils/TreeNode.java new file mode 100644 index 0000000..c17b2dd --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/utils/TreeNode.java @@ -0,0 +1,34 @@ +package net.maku.framework.common.utils; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * 树节点,所有需要实现树节点的,都需要继承该类 + * + * @author 阿沐 babamu@126.com + */ +@Data +public class TreeNode implements Serializable { + private static final long serialVersionUID = 1L; + /** + * 主键 + */ + @Schema(description = "id") + private Long id; + /** + * 上级ID + */ + @Schema(description = "上级ID") + @NotNull(message = "上级ID不能为空") + private Long pid; + /** + * 子节点列表 + */ + private List children = new ArrayList<>(); +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/common/utils/TreeUtils.java b/fast-framework/src/main/java/net/maku/framework/common/utils/TreeUtils.java new file mode 100644 index 0000000..09165fc --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/common/utils/TreeUtils.java @@ -0,0 +1,70 @@ +package net.maku.framework.common.utils; + + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * 树形结构工具类,如:菜单、机构等 + * + * @author 阿沐 babamu@126.com + */ +public class TreeUtils { + + /** + * 根据pid,构建树节点 + */ + public static List build(List treeNodes, Long pid) { + // pid不能为空 + AssertUtils.isNull(pid, "pid"); + + List treeList = new ArrayList<>(); + for(T treeNode : treeNodes) { + if (pid.equals(treeNode.getPid())) { + treeList.add(findChildren(treeNodes, treeNode)); + } + } + + return treeList; + } + + /** + * 查找子节点 + */ + private static T findChildren(List treeNodes, T rootNode) { + for(T treeNode : treeNodes) { + if(rootNode.getId().equals(treeNode.getPid())) { + rootNode.getChildren().add(findChildren(treeNodes, treeNode)); + } + } + return rootNode; + } + + /** + * 构建树节点 + */ + public static List build(List treeNodes) { + List result = new ArrayList<>(); + + // list转map + Map nodeMap = new LinkedHashMap<>(treeNodes.size()); + for(T treeNode : treeNodes){ + nodeMap.put(treeNode.getId(), treeNode); + } + + for(T node : nodeMap.values()) { + T parent = nodeMap.get(node.getPid()); + if(parent != null && !(node.getId().equals(parent.getId()))){ + parent.getChildren().add(node); + continue; + } + + result.add(node); + } + + return result; + } + +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/config/CorsConfig.java b/fast-framework/src/main/java/net/maku/framework/config/CorsConfig.java new file mode 100644 index 0000000..1329254 --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/config/CorsConfig.java @@ -0,0 +1,28 @@ +package net.maku.framework.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.filter.CorsFilter; + +/** + * 跨域配置 + * + * @author 阿沐 babamu@126.com + */ +@Configuration +public class CorsConfig { + + @Bean + public CorsFilter corsFilter() { + final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + final CorsConfiguration corsConfiguration = new CorsConfiguration(); + corsConfiguration.setAllowCredentials(true); + corsConfiguration.addAllowedHeader("*"); + corsConfiguration.addAllowedOriginPattern("*"); + corsConfiguration.addAllowedMethod("*"); + source.registerCorsConfiguration("/**", corsConfiguration); + return new CorsFilter(source); + } +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/config/MybatisPlusConfig.java b/fast-framework/src/main/java/net/maku/framework/config/MybatisPlusConfig.java new file mode 100644 index 0000000..2c3dd51 --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/config/MybatisPlusConfig.java @@ -0,0 +1,39 @@ +package net.maku.framework.config; + +import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; +import net.maku.framework.common.handler.FieldMetaObjectHandler; +import net.maku.framework.common.interceptor.DataScopeInnerInterceptor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * mybatis-plus 配置 + * + * @author 阿沐 babamu@126.com + */ +@Configuration +public class MybatisPlusConfig { + + @Bean + public MybatisPlusInterceptor mybatisPlusInterceptor() { + MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor(); + // 数据权限 + mybatisPlusInterceptor.addInnerInterceptor(new DataScopeInnerInterceptor()); + // 分页插件 + mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor()); + // 乐观锁 + mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); + // 防止全表更新与删除 + mybatisPlusInterceptor.addInnerInterceptor(new BlockAttackInnerInterceptor()); + + return mybatisPlusInterceptor; + } + + @Bean + public FieldMetaObjectHandler fieldMetaObjectHandler(){ + return new FieldMetaObjectHandler(); + } +} diff --git a/fast-framework/src/main/java/net/maku/framework/config/RedisConfig.java b/fast-framework/src/main/java/net/maku/framework/config/RedisConfig.java new file mode 100644 index 0000000..159cd7c --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/config/RedisConfig.java @@ -0,0 +1,47 @@ +package net.maku.framework.config; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializer; + +/** + * Redis配置 + * + * @author 阿沐 babamu@126.com + */ +@Configuration +public class RedisConfig { + + @Bean + public Jackson2JsonRedisSerializer jackson2JsonRedisSerializer(){ + Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL); + jackson2JsonRedisSerializer.setObjectMapper(objectMapper); + + return jackson2JsonRedisSerializer; + } + + @Bean + public RedisTemplate redisTemplate(RedisConnectionFactory factory) { + RedisTemplate template = new RedisTemplate<>(); + // Key HashKey使用String序列化 + template.setKeySerializer(RedisSerializer.string()); + template.setHashKeySerializer(RedisSerializer.string()); + + // Value HashValue使用Jackson2JsonRedisSerializer序列化 + template.setValueSerializer(jackson2JsonRedisSerializer()); + template.setHashValueSerializer(jackson2JsonRedisSerializer()); + + template.setConnectionFactory(factory); + return template; + } +} diff --git a/fast-framework/src/main/java/net/maku/framework/config/SwaggerConfig.java b/fast-framework/src/main/java/net/maku/framework/config/SwaggerConfig.java new file mode 100644 index 0000000..e4c2afb --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/config/SwaggerConfig.java @@ -0,0 +1,43 @@ +package net.maku.framework.config; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Contact; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.info.License; +import org.springdoc.core.GroupedOpenApi; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * Swagger配置 + * + * @author 阿沐 babamu@126.com + */ +@Configuration +public class SwaggerConfig{ + + @Bean + public GroupedOpenApi userApi(){ + String[] paths = { "/**" }; + String[] packagedToMatch = { "net.maku" }; + return GroupedOpenApi.builder().group("FastBoot") + .pathsToMatch(paths) + .packagesToScan(packagedToMatch).build(); + } + + @Bean + public OpenAPI customOpenAPI() { + Contact contact= new Contact(); + contact.setName("阿沐 babamu@126.com"); + + return new OpenAPI().info(new Info() + .title("FastBoot") + .description( "FastBoot") + .contact(contact) + .version("1.0") + .termsOfService("https://maku.net") + .license(new License().name("MIT") + .url("https://maku.net"))); + } + +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/config/WebConfig.java b/fast-framework/src/main/java/net/maku/framework/config/WebConfig.java new file mode 100644 index 0000000..483b879 --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/config/WebConfig.java @@ -0,0 +1,52 @@ +package net.maku.framework.config; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.ByteArrayHttpMessageConverter; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.ResourceHttpMessageConverter; +import org.springframework.http.converter.StringHttpMessageConverter; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import java.util.List; +import java.util.TimeZone; + +/** + * Web MVC配置 + * + * @author 阿沐 babamu@126.com + */ +@Configuration +public class WebConfig implements WebMvcConfigurer { + + @Override + public void configureMessageConverters(List> converters) { + converters.add(new ByteArrayHttpMessageConverter()); + converters.add(new StringHttpMessageConverter()); + converters.add(new ResourceHttpMessageConverter()); + converters.add(new AllEncompassingFormHttpMessageConverter()); + converters.add(new StringHttpMessageConverter()); + converters.add(jackson2HttpMessageConverter()); + } + + @Bean + public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() { + MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); + ObjectMapper mapper = new ObjectMapper(); + + // 忽略未知属性 + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + // 统一日期格式转换,不建议开启 + //mapper.setDateFormat(new SimpleDateFormat(DateUtils.DATE_TIME_PATTERN)); + mapper.setTimeZone(TimeZone.getTimeZone("GMT+8")); + + converter.setObjectMapper(mapper); + return converter; + } + +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/security/config/AuthorizationServerConfig.java b/fast-framework/src/main/java/net/maku/framework/security/config/AuthorizationServerConfig.java new file mode 100644 index 0000000..142a9f6 --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/security/config/AuthorizationServerConfig.java @@ -0,0 +1,76 @@ +package net.maku.framework.security.config; + +import lombok.AllArgsConstructor; +import net.maku.framework.security.exception.FastWebResponseExceptionTranslator; +import net.maku.framework.security.token.FastTokenEnhancer; +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.core.userdetails.UserDetailsService; +import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; +import org.springframework.security.oauth2.provider.ClientDetailsService; +import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices; +import org.springframework.security.oauth2.provider.token.TokenEnhancer; +import org.springframework.security.oauth2.provider.token.TokenStore; + +/** + * 认证服务器配置 + * + * @author 阿沐 babamu@126.com + */ +@Configuration +@AllArgsConstructor +@EnableAuthorizationServer +public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { + private final AuthenticationManager authenticationManager; + private final ClientDetailsService fastClientDetailsService; + private final UserDetailsService userDetailsService; + private final AuthorizationCodeServices redisAuthorizationCodeServices; + private final TokenStore tokenStore; + + /** + * 配置客户端信息 + */ + @Override + public void configure(ClientDetailsServiceConfigurer clients) throws Exception { + clients.withClientDetails(fastClientDetailsService); + } + + @Override + public void configure(AuthorizationServerEndpointsConfigurer endpoints) { + endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST, HttpMethod.DELETE); + // 密码模式 + endpoints.authenticationManager(authenticationManager); + // 支持刷新令牌 + endpoints.userDetailsService(userDetailsService); + // 令牌管理 + endpoints.tokenStore(tokenStore); + // 令牌增强 + endpoints.tokenEnhancer(tokenEnhancer()); + // 登录或者鉴权失败时的返回信息 + endpoints.exceptionTranslator(new FastWebResponseExceptionTranslator()); + // 配置授权码模式,存放在Redis中 + endpoints.authorizationCodeServices(redisAuthorizationCodeServices); + // 自定义登录地址 + endpoints.pathMapping("/oauth/token","/sys/oauth/token"); + } + + @Bean + public TokenEnhancer tokenEnhancer() { + return new FastTokenEnhancer(); + } + + @Override + public void configure(AuthorizationServerSecurityConfigurer security) { + security + .allowFormAuthenticationForClients() + .tokenKeyAccess("permitAll()") // 匿名可访问/oauth/token_key + .checkTokenAccess("isAuthenticated()") // 认证后可访问/oauth/check_token + ; + } +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/security/config/PasswordConfig.java b/fast-framework/src/main/java/net/maku/framework/security/config/PasswordConfig.java new file mode 100644 index 0000000..4137a6e --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/security/config/PasswordConfig.java @@ -0,0 +1,20 @@ +package net.maku.framework.security.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.factory.PasswordEncoderFactories; +import org.springframework.security.crypto.password.PasswordEncoder; + +/** + * 加密配置 + * + * @author 阿沐 babamu@126.com + */ +@Configuration +public class PasswordConfig { + + @Bean + public PasswordEncoder passwordEncoder(){ + return PasswordEncoderFactories.createDelegatingPasswordEncoder(); + } +} diff --git a/fast-framework/src/main/java/net/maku/framework/security/config/PermitResource.java b/fast-framework/src/main/java/net/maku/framework/security/config/PermitResource.java new file mode 100644 index 0000000..8ff764a --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/security/config/PermitResource.java @@ -0,0 +1,59 @@ +package net.maku.framework.security.config; + +import lombok.SneakyThrows; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +/** + * 允许访问的资源 + * + * @author 阿沐 babamu@126.com + */ +@Component +public class PermitResource { + /** + * 指定被 spring security oauth2.0 忽略的URL + */ + @SneakyThrows + public List getPermitList(){ + ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); + Resource[] resources = resolver.getResources("classpath*:auth.yml"); + String key = "auth.ignore_urls"; + + return getPropertiesList(key, resources); + } + + private List getPropertiesList(String key, Resource... resources){ + List list = new ArrayList<>(); + + // 解析资源文件 + for(Resource resource : resources) { + Properties properties = loadYamlProperties(resource); + + for (Map.Entry entry : properties.entrySet()) { + String tmpKey = StringUtils.substringBefore(entry.getKey().toString(), "["); + if(tmpKey.equalsIgnoreCase(key)){ + list.add(entry.getValue().toString()); + } + } + } + return list; + } + + private Properties loadYamlProperties(Resource... resources) { + YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); + factory.setResources(resources); + factory.afterPropertiesSet(); + + return factory.getObject(); + } +} diff --git a/fast-framework/src/main/java/net/maku/framework/security/config/ResourceServerConfig.java b/fast-framework/src/main/java/net/maku/framework/security/config/ResourceServerConfig.java new file mode 100644 index 0000000..ca5cf45 --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/security/config/ResourceServerConfig.java @@ -0,0 +1,50 @@ +package net.maku.framework.security.config; + +import lombok.AllArgsConstructor; +import net.maku.framework.security.exception.SecurityAuthenticationEntryPoint; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; +import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; +import org.springframework.security.oauth2.provider.token.TokenStore; + +import java.util.List; + +/** + * 资源服务器配置 + * + * @author 阿沐 babamu@126.com + */ +@Configuration +@AllArgsConstructor +@EnableResourceServer +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class ResourceServerConfig extends ResourceServerConfigurerAdapter { + private final TokenStore tokenStore; + private final PermitResource permitResource; + + @Override + public void configure(ResourceServerSecurityConfigurer resources) { + resources.tokenStore(tokenStore); + + resources.authenticationEntryPoint(new SecurityAuthenticationEntryPoint()); + } + + @Override + public void configure(HttpSecurity http) throws Exception { + // 忽略授权的地址列表 + List permitList = permitResource.getPermitList(); + String [] permits = permitList.toArray(new String[permitList.size()]); + + http + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .and() + .authorizeRequests() + .antMatchers(permits).permitAll() + .anyRequest().authenticated() + ; + } +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/security/config/TokenStoreConfig.java b/fast-framework/src/main/java/net/maku/framework/security/config/TokenStoreConfig.java new file mode 100644 index 0000000..44ff06e --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/security/config/TokenStoreConfig.java @@ -0,0 +1,25 @@ +package net.maku.framework.security.config; + +import lombok.AllArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.security.oauth2.provider.token.TokenStore; +import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore; + +/** + * TokenStore + * + * @author 阿沐 babamu@126.com + */ +@Configuration +@AllArgsConstructor +public class TokenStoreConfig { + private final RedisConnectionFactory redisConnectionFactory; + + @Bean + public TokenStore tokenStore() { + // 使用redis存储token + return new RedisTokenStore(redisConnectionFactory); + } +} diff --git a/fast-framework/src/main/java/net/maku/framework/security/config/WebSecurityConfig.java b/fast-framework/src/main/java/net/maku/framework/security/config/WebSecurityConfig.java new file mode 100644 index 0000000..e738faf --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/security/config/WebSecurityConfig.java @@ -0,0 +1,61 @@ +package net.maku.framework.security.config; + +import lombok.AllArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.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.core.userdetails.UserDetailsService; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.web.filter.OncePerRequestFilter; + +/** + * Spring Security配置 + * + * @author 阿沐 babamu@126.com + */ +@AllArgsConstructor +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + private final UserDetailsService userDetailsService; + private final OncePerRequestFilter validateCodeFilter; + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService); + } + + /** + * 密码模式需要 + */ + @Bean + @Override + public AuthenticationManager authenticationManagerBean() throws Exception{ + return super.authenticationManager(); + } + + @Override + public void configure(HttpSecurity http) throws Exception { + http + .addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) + .formLogin() + .loginPage("/login") + .loginProcessingUrl("/login") + .and() + .authorizeRequests() + .antMatchers("/oauth/authorize").authenticated() + .anyRequest().permitAll() + .and().headers().frameOptions().disable() + .and().csrf().disable() + ; + } + + @Override + public void configure(WebSecurity web) { + web.ignoring().antMatchers(HttpMethod.OPTIONS); + } +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/security/exception/FastAuthenticationException.java b/fast-framework/src/main/java/net/maku/framework/security/exception/FastAuthenticationException.java new file mode 100644 index 0000000..0f952a7 --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/security/exception/FastAuthenticationException.java @@ -0,0 +1,18 @@ +package net.maku.framework.security.exception; + +import org.springframework.security.core.AuthenticationException; + +/** + * 认证异常类 + * + * @author 阿沐 babamu@126.com + */ +public class FastAuthenticationException extends AuthenticationException { + public FastAuthenticationException(String msg, Throwable t) { + super(msg, t); + } + + public FastAuthenticationException(String msg) { + super(msg); + } +} diff --git a/fast-framework/src/main/java/net/maku/framework/security/exception/FastOAuth2Exception.java b/fast-framework/src/main/java/net/maku/framework/security/exception/FastOAuth2Exception.java new file mode 100644 index 0000000..bf7d7d7 --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/security/exception/FastOAuth2Exception.java @@ -0,0 +1,31 @@ +package net.maku.framework.security.exception; + +import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; + +/** + * 自定义异常 + * + * @author 阿沐 babamu@126.com + */ +public class FastOAuth2Exception extends OAuth2Exception { + private String msg; + + public FastOAuth2Exception(String msg) { + super(msg); + this.msg = msg; + } + + public FastOAuth2Exception(String msg, Throwable e) { + super(msg, e); + this.msg = msg; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/security/exception/FastWebResponseExceptionTranslator.java b/fast-framework/src/main/java/net/maku/framework/security/exception/FastWebResponseExceptionTranslator.java new file mode 100644 index 0000000..b3862b3 --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/security/exception/FastWebResponseExceptionTranslator.java @@ -0,0 +1,78 @@ +package net.maku.framework.security.exception; + +import net.maku.framework.common.exception.ErrorCode; +import net.maku.framework.common.utils.Result; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.oauth2.common.DefaultThrowableAnalyzer; +import org.springframework.security.oauth2.common.OAuth2AccessToken; +import org.springframework.security.oauth2.common.exceptions.ClientAuthenticationException; +import org.springframework.security.oauth2.common.exceptions.InsufficientScopeException; +import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; +import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; +import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator; +import org.springframework.security.web.util.ThrowableAnalyzer; +import org.springframework.stereotype.Component; +import org.springframework.web.HttpRequestMethodNotSupportedException; + +/** + * 登录或者鉴权失败时的返回信息 + * + * @author 阿沐 babamu@126.com + */ +@Component +public class FastWebResponseExceptionTranslator implements WebResponseExceptionTranslator { + private final ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer(); + + @Override + public ResponseEntity translate(Exception e) { + Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e); + + Exception exception = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain); + if (exception != null) { + return handleOAuth2Exception(new FastOAuth2Exception(e.getMessage(), e)); + } + + exception = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain); + if (exception != null) { + return handleOAuth2Exception(new FastOAuth2Exception(exception.getMessage(), exception)); + } + + exception = (InvalidGrantException) throwableAnalyzer.getFirstThrowableOfType(InvalidGrantException.class, causeChain); + if (exception != null) { + return handleOAuth2Exception(new FastOAuth2Exception(exception.getMessage(), exception)); + } + + exception = (HttpRequestMethodNotSupportedException) throwableAnalyzer.getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain); + if (exception != null) { + return handleOAuth2Exception(new FastOAuth2Exception(exception.getMessage(), exception)); + } + + exception = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain); + if (exception != null) { + return handleOAuth2Exception((OAuth2Exception) exception); + } + + return handleOAuth2Exception(new FastOAuth2Exception(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), e)); + } + + private ResponseEntity handleOAuth2Exception(OAuth2Exception e) { + int status = e.getHttpErrorCode(); + HttpHeaders headers = new HttpHeaders(); + headers.set(HttpHeaders.CACHE_CONTROL, "no-store"); + headers.set(HttpHeaders.PRAGMA, "no-cache"); + if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) { + headers.set(HttpHeaders.WWW_AUTHENTICATE, String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary())); + } + + if (e instanceof ClientAuthenticationException) { + return new ResponseEntity<>(e, headers, HttpStatus.valueOf(status)); + } + Result result = Result.error(ErrorCode.ACCOUNT_PASSWORD_ERROR); + + return new ResponseEntity(result, headers, HttpStatus.OK); + } +} diff --git a/fast-framework/src/main/java/net/maku/framework/security/exception/SecurityAuthenticationEntryPoint.java b/fast-framework/src/main/java/net/maku/framework/security/exception/SecurityAuthenticationEntryPoint.java new file mode 100644 index 0000000..eb9f3fd --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/security/exception/SecurityAuthenticationEntryPoint.java @@ -0,0 +1,29 @@ +package net.maku.framework.security.exception; + +import net.maku.framework.common.exception.ErrorCode; +import net.maku.framework.common.utils.HttpContextUtils; +import net.maku.framework.common.utils.JsonUtils; +import net.maku.framework.common.utils.Result; +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; + +/** + * 匿名用户(token不存在、错误),异常处理器 + * + * @author 阿沐 babamu@126.com + */ +public class SecurityAuthenticationEntryPoint implements AuthenticationEntryPoint { + + @Override + public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { + response.setContentType("application/json; charset=utf-8"); + response.setHeader("Access-Control-Allow-Credentials", "true"); + response.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin()); + + response.getWriter().print(JsonUtils.toJsonString(Result.error(ErrorCode.UNAUTHORIZED))); + } +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/security/handler/UserAuthenticationFailureHandler.java b/fast-framework/src/main/java/net/maku/framework/security/handler/UserAuthenticationFailureHandler.java new file mode 100644 index 0000000..cc25d78 --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/security/handler/UserAuthenticationFailureHandler.java @@ -0,0 +1,31 @@ +package net.maku.framework.security.handler; + +import lombok.SneakyThrows; +import net.maku.framework.common.utils.HttpContextUtils; +import net.maku.framework.common.utils.JsonUtils; +import net.maku.framework.common.utils.Result; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; +import org.springframework.stereotype.Component; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * 认证失败处理器 + * + * @author 阿沐 babamu@126.com + */ +@Component +public class UserAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { + + @SneakyThrows + @Override + public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) { + response.setContentType("application/json;charset=UTF-8"); + response.setHeader("Access-Control-Allow-Credentials", "true"); + response.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin()); + + response.getWriter().write(JsonUtils.toJsonString(Result.error(e.getMessage()))); + } +} diff --git a/fast-framework/src/main/java/net/maku/framework/security/token/FastTokenEnhancer.java b/fast-framework/src/main/java/net/maku/framework/security/token/FastTokenEnhancer.java new file mode 100644 index 0000000..82578d7 --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/security/token/FastTokenEnhancer.java @@ -0,0 +1,34 @@ +package net.maku.framework.security.token; + +import net.maku.framework.common.utils.Result; +import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; +import org.springframework.security.oauth2.common.OAuth2AccessToken; +import org.springframework.security.oauth2.provider.OAuth2Authentication; +import org.springframework.security.oauth2.provider.token.TokenEnhancer; + +import java.util.HashMap; +import java.util.Map; + +/** + * 令牌 + * + * @author 阿沐 babamu@126.com + */ +public class FastTokenEnhancer implements TokenEnhancer { + + @Override + public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { + if(accessToken instanceof DefaultOAuth2AccessToken){ + DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken; + + // 增加额外信息 + Map info = new HashMap<>(); + info.put("code", new Result<>().getCode()); + token.setAdditionalInformation(info); + + return token; + } + + return accessToken; + } +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/security/user/SecurityUser.java b/fast-framework/src/main/java/net/maku/framework/security/user/SecurityUser.java new file mode 100644 index 0000000..76bba4b --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/security/user/SecurityUser.java @@ -0,0 +1,33 @@ +package net.maku.framework.security.user; + +import org.springframework.security.core.context.SecurityContextHolder; + +/** + * 用户 + * + * @author 阿沐 babamu@126.com + */ +public class SecurityUser { + + /** + * 获取用户信息 + */ + public static UserDetail getUser() { + UserDetail user; + try { + user = (UserDetail)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + }catch (Exception e){ + return new UserDetail(); + } + + return user; + } + + /** + * 获取用户ID + */ + public static Long getUserId() { + return getUser().getId(); + } + +} \ No newline at end of file diff --git a/fast-framework/src/main/java/net/maku/framework/security/user/UserDetail.java b/fast-framework/src/main/java/net/maku/framework/security/user/UserDetail.java new file mode 100644 index 0000000..f6753be --- /dev/null +++ b/fast-framework/src/main/java/net/maku/framework/security/user/UserDetail.java @@ -0,0 +1,84 @@ +package net.maku.framework.security.user; + +import lombok.Data; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Set; + +/** + * 登录用户信息 + * + * @author 阿沐 babamu@126.com + */ +@Data +public class UserDetail implements UserDetails { + private static final long serialVersionUID = 1L; + + private Long id; + private String username; + private String password; + private String realName; + private String avatar; + private Integer gender; + private String email; + private String mobile; + private Long orgId; + private Integer status; + private Integer superAdmin; + private Date createTime; + /** + * 数据权限范围 + * + * null:表示全部数据权限 + */ + private List dataScopeList; + /** + * 帐户是否过期 + */ + private boolean isAccountNonExpired = true; + /** + * 帐户是否被锁定 + */ + private boolean isAccountNonLocked = true; + /** + * 密码是否过期 + */ + private boolean isCredentialsNonExpired = true; + /** + * 帐户是否可用 + */ + private boolean isEnabled = true; + /** + * 拥有权限集合 + */ + private Set authorities; + + @Override + public Collection getAuthorities() { + return this.authorities; + } + + @Override + public boolean isAccountNonExpired() { + return this.isAccountNonExpired; + } + + @Override + public boolean isAccountNonLocked() { + return this.isAccountNonLocked; + } + + @Override + public boolean isCredentialsNonExpired() { + return this.isCredentialsNonExpired; + } + + @Override + public boolean isEnabled() { + return this.isEnabled; + } +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index 62f2da8..91133fa 100644 --- a/pom.xml +++ b/pom.xml @@ -17,9 +17,9 @@ - fast-boot-framework fast-boot-system fast-boot-new + fast-framework fast-server