Browse Source

审批回调修改。定时任务启动授权添加

mazq 1 year ago
parent
commit
ee906b3ba8
17 changed files with 177 additions and 166 deletions
  1. 6 0
      dcuc-auth-model/src/main/java/com/dragoninfo/dcuc/auth/auth/entity/zerotrust/RoleAuthApply.java
  2. 6 0
      dcuc-auth-model/src/main/java/com/dragoninfo/dcuc/auth/auth/entity/zerotrust/ServiceAuthApply.java
  3. 1 2
      dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/audit/service/LogSendService.java
  4. 7 0
      dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/auth/bpo/ServiceAuthResultBPO.java
  5. 6 0
      dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/auth/repo/zerotrust/RoleAuthApplyRepository.java
  6. 7 0
      dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/auth/repo/zerotrust/ServiceAuthApplyRepository.java
  7. 8 3
      dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/auth/service/IServiceAuthResultService.java
  8. 5 25
      dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/auth/service/IStaffAssignAuthInfoService.java
  9. 39 80
      dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/business/impl/zerotrust/RoleAuthCallbackHandler.java
  10. 2 1
      dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/business/impl/zerotrust/RoleOperateCallbackHandler.java
  11. 38 52
      dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/business/impl/zerotrust/ServiceAuthCallbackHandler.java
  12. 3 0
      dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/business/impl/zerotrust/ZeroTrustAuthApplyBusinessImpl.java
  13. 6 0
      dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/business/zerotrust/IRoleAuthCallbackHandler.java
  14. 5 0
      dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/business/zerotrust/IServiceAuthCallbackHandler.java
  15. 25 1
      dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/systemtask/service/AuthMonitorTask.java
  16. 2 2
      dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/util/ThreadPoolHolder.java
  17. 11 0
      dcuc-auth-service/src/main/resources/config/mysql/V4_3_0035__ServiceAuthApply.sql

+ 6 - 0
dcuc-auth-model/src/main/java/com/dragoninfo/dcuc/auth/auth/entity/zerotrust/RoleAuthApply.java

@@ -62,6 +62,12 @@ public class RoleAuthApply extends BaseUpdateEntity implements IdEntity<String>
     @Column(name = "END_TIME")
     private Date endTime;
 
+    /**
+     * 是否待授权 0 否 1是 审批通过后开始时间未到
+     */
+    @Column(name = "TO_BE_AUTHED")
+    private String toBeAuthed;
+
     /**
      * 流程实例id
      */

+ 6 - 0
dcuc-auth-model/src/main/java/com/dragoninfo/dcuc/auth/auth/entity/zerotrust/ServiceAuthApply.java

@@ -56,6 +56,12 @@ public class ServiceAuthApply extends BaseEntity implements IdEntity<String> {
     @Column(name = "END_TIME")
     private Date endTime;
 
+    /**
+     * 是否待授权 0 否 1是 审批通过后开始时间未到
+     */
+    @Column(name = "TO_BE_AUTHED")
+    private String toBeAuthed;
+
     /**
      * 流程实例id
      */

+ 1 - 2
dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/audit/service/LogSendService.java

@@ -6,7 +6,6 @@ import com.dragoninfo.dcuc.auth.audit.dto.AuthenticationLogDto;
 import com.dragoninfo.dcuc.auth.audit.dto.AuthorizeLogDto;
 import com.dragoninfo.dcuc.auth.config.DcucAuthKafkaConfig;
 import com.dragoninfo.duceap.commons.util.kafka.KafkaServer;
-import com.dragonsoft.duceap.base.entity.security.BaseSecurityUser;
 import com.dragonsoft.duceap.base.entity.security.SecurityUser;
 import com.dragonsoft.duceap.base.utils.UserContextUtils;
 import com.dragonsoft.duceap.commons.util.date.DateConst;
@@ -43,7 +42,7 @@ public class LogSendService {
     public void sendAuthorizeLog(AuthorizeLogDto log) {
         String title = "推送授权日志";
         String content = "推送授权日志";
-        SecurityUser securityUser = (SecurityUser) UserContextUtils.getCurrentUser();
+        SecurityUser securityUser = UserContextUtils.getCurrentUser();
         MessageInfoVo messages = getMessageVo(securityUser, title, content, auditConfig.getAuthorizeTopic());
         messages.setContent(JSON.toJSONString(log));
         List<MessageInfoVo> msg = new ArrayList<>();

+ 7 - 0
dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/auth/bpo/ServiceAuthResultBPO.java

@@ -10,6 +10,7 @@ import com.dragonsoft.duceap.core.search.Searchable;
 import org.springframework.data.domain.Page;
 import org.springframework.stereotype.Repository;
 
+import java.util.Date;
 import java.util.List;
 
 /**
@@ -83,4 +84,10 @@ public class ServiceAuthResultBPO extends BaseBPO<ServiceAuthResult, String> {
                 " from t_auth_apply_flow w LEFT JOIN t_service_auth_content c on w.id = c.AUTH_APPLY_ID) as f on f.message_id = t.message_id";
         return PersistentFactory.getJdbcDao().paging(sql, searchable, ServiceAuthResultPO.class);
     }
+
+    public List<ServiceAuthResult> getExpiredAuth() {
+        String sql = " SELECT * FROM T_SERVICE_AUTH_RESULT " +
+                " where deleted='0' and end_time < ?";
+        return PersistentFactory.getJdbcDao().queryForList(sql, ServiceAuthResult.class, new Date());
+    }
 }

+ 6 - 0
dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/auth/repo/zerotrust/RoleAuthApplyRepository.java

@@ -7,6 +7,8 @@ import org.springframework.data.jpa.repository.Query;
 import org.springframework.data.repository.query.Param;
 import org.springframework.stereotype.Repository;
 
+import java.util.List;
+
 /**
  * @author mazq
  * @date 2023/7/13
@@ -22,4 +24,8 @@ public interface RoleAuthApplyRepository extends BaseRepository<RoleAuthApply, S
     @Modifying
     @Query(value = "UPDATE T_AUTH_ROLE_AUTH_APPLY SET APPROVAL_RESULT = :approvalResult WHERE PROCESS_INST_ID = :processInstId AND DELETED = '0'", nativeQuery = true)
     void updateApprovalResult(@Param("processInstId") String processInstId, @Param("approvalResult") String approvalResult);
+
+    @Modifying
+    @Query(value = "UPDATE T_AUTH_ROLE_AUTH_APPLY SET TO_BE_AUTHED = :value WHERE ID IN :ids AND DELETED = '0'", nativeQuery = true)
+    void setToBeAuthed(@Param("ids") List<String> ids, @Param("value") String value);
 }

+ 7 - 0
dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/auth/repo/zerotrust/ServiceAuthApplyRepository.java

@@ -7,6 +7,9 @@ import org.springframework.data.jpa.repository.Query;
 import org.springframework.data.repository.query.Param;
 import org.springframework.stereotype.Repository;
 
+import java.util.Date;
+import java.util.List;
+
 /**
  * @author mazq
  * @date 2023/7/13
@@ -22,4 +25,8 @@ public interface ServiceAuthApplyRepository extends BaseRepository<ServiceAuthAp
     @Modifying
     @Query(value = "UPDATE T_AUTH_SERVICE_AUTH_APPLY SET APPROVAL_RESULT = :approvalResult WHERE PROCESS_INST_ID = :processInstId AND DELETED = '0'", nativeQuery = true)
     void updateApprovalResult(@Param("processInstId") String processInstId, @Param("approvalResult") String approvalResult);
+
+    @Modifying
+    @Query(value = "UPDATE T_AUTH_SERVICE_AUTH_APPLY SET TO_BE_AUTHED = :value WHERE ID IN :ids AND DELETED = '0'", nativeQuery = true)
+    void setToBeAuthed(@Param("ids") List<String> ids, @Param("value") String value);
 }

+ 8 - 3
dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/auth/service/IServiceAuthResultService.java

@@ -5,6 +5,7 @@ import com.dragoninfo.dcuc.auth.auth.dto.ServiceAuthResultDTO;
 import com.dragoninfo.dcuc.auth.auth.dto.WorkFlowResutlAcceptDTO;
 import com.dragoninfo.dcuc.auth.auth.entity.ServiceAuthResult;
 import com.dragoninfo.dcuc.auth.auth.entity.WorkFlow;
+import com.dragoninfo.dcuc.auth.auth.entity.zerotrust.ServiceAuthApply;
 import com.dragoninfo.dcuc.auth.auth.vo.ServiceAuthenticationResVO;
 import com.dragonsoft.duceap.base.entity.http.ResponseDTO;
 import com.dragonsoft.duceap.core.search.Searchable;
@@ -124,9 +125,13 @@ public interface IServiceAuthResultService {
     List<ServiceAuthResult> findAll();
 
     /**
-     * 批量保存服务授权
-     * @param serviceAuthResult
+     * 删除过期的权限
      */
-    void batchSave(List<ServiceAuthResult> serviceAuthResult);
+    void deleteExpireAuth();
 
+    /**
+     * 审批通过后开始服务授权
+     * @param authApplies
+     */
+    void startServiceAuthApply(List<ServiceAuthApply> authApplies);
 }

+ 5 - 25
dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/auth/service/IStaffAssignAuthInfoService.java

@@ -5,13 +5,13 @@ import com.dragoninfo.dcuc.auth.auth.dto.AppDataSensitiveLevelDTO;
 import com.dragoninfo.dcuc.auth.auth.dto.StaffAssignDTO;
 import com.dragoninfo.dcuc.auth.auth.dto.StaffRoleOperateDTO;
 import com.dragoninfo.dcuc.auth.auth.entity.StaffAssignAuthInfo;
+import com.dragoninfo.dcuc.auth.auth.entity.zerotrust.RoleAuthApply;
 import com.dragoninfo.dcuc.auth.auth.vo.ApiAppAuthVo;
 import com.dragoninfo.dcuc.auth.auth.vo.StaffRoleAuthApiVo;
 import com.dragoninfo.dcuc.auth.auth.vo.StaffRoleAuthApiV2Vo;
 import com.dragoninfo.dcuc.auth.auth.vo.StaffRoleAuthReqVo;
 import com.dragonsoft.duceap.base.entity.http.ResponseStatus;
 import com.dragonsoft.duceap.base.entity.search.SearchDTO;
-import com.dragonsoft.duceap.base.entity.security.SecurityUser;
 import org.springframework.data.domain.Page;
 
 import java.util.List;
@@ -25,11 +25,7 @@ public interface IStaffAssignAuthInfoService  {
 
     ResponseStatus saveStaffRoleAuth(StaffRoleOperateDTO dto);
 
-    ResponseStatus deleteAllStaffRole(String staffId);
-
-    void authMonitor(SecurityUser user);
-
-    ResponseStatus changeStaffOrg(String oldOrgId, String newOrgId);
+    void deleteExpireAuth();
 
     /**
      * 查询列表
@@ -50,21 +46,6 @@ public interface IStaffAssignAuthInfoService  {
     ResponseStatus saveStaff(StaffAssignDTO dto);
 
 
-    /**
-     * 保存
-     *
-     * @param roleId     角色id
-     * @param orgId      被操作人机构id
-     * @param appId      应用id
-     * @param userId     审批人用户id
-     * @param userOrg    审批人机构
-     * @param activeTime 赋予被操作人时间
-     * @param staffId    被操作人id
-     */
-    void saveStaffAssign(String roleId, String orgId, String appId,
-                         String userId, String userOrg, String activeTime, String staffId);
-
-
     /**
      * 根据人员ID获取授权信息
      *
@@ -172,9 +153,8 @@ public interface IStaffAssignAuthInfoService  {
     ResponseStatus apiStaffRoleAuth(StaffRoleAuthReqVo reqVo);
 
     /**
-     * 批量保存
-     * @param roleAuths
+     * 审批通过后开始角色授权
+     * @param authApplies
      */
-    void batchSave(List<StaffAssignAuthInfo> roleAuths);
-
+    void startRoleAuthApply(List<RoleAuthApply> authApplies);
 }

+ 39 - 80
dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/business/impl/zerotrust/RoleAuthCallbackHandler.java

@@ -1,22 +1,20 @@
 package com.dragoninfo.dcuc.auth.business.impl.zerotrust;
 
 import com.dragoninfo.dcuc.auth.auth.dto.zerotrust.approval.ApprovalBaseRespDto;
-import com.dragoninfo.dcuc.auth.auth.entity.RoleInfo;
-import com.dragoninfo.dcuc.auth.auth.entity.StaffAssignAuthInfo;
 import com.dragoninfo.dcuc.auth.auth.entity.zerotrust.RoleAuthApply;
 import com.dragoninfo.dcuc.auth.auth.enumresources.zerotrust.approval.AuthApplyStatusEnum;
-import com.dragoninfo.dcuc.auth.auth.service.IRoleInfoService;
 import com.dragoninfo.dcuc.auth.auth.service.IStaffAssignAuthInfoService;
 import com.dragoninfo.dcuc.auth.auth.service.zerotrust.IRoleAuthApplyService;
 import com.dragoninfo.dcuc.auth.business.zerotrust.IRoleAuthCallbackHandler;
-import com.dragoninfo.dcuc.auth.sub.entity.AuthUserInfo;
-import com.dragoninfo.dcuc.auth.sub.service.IAuthUserInfoService;
+import com.dragonsoft.duceap.base.entity.security.SecurityUser;
+import com.dragonsoft.duceap.base.enums.BooleanEnum;
+import com.dragonsoft.duceap.base.utils.UserContextUtils;
 import com.dragonsoft.duceap.commons.util.collections.CollectionUtils;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Transactional;
 
-import java.text.SimpleDateFormat;
 import java.util.*;
 import java.util.stream.Collectors;
 
@@ -32,20 +30,6 @@ public class RoleAuthCallbackHandler implements IRoleAuthCallbackHandler {
 
     private IStaffAssignAuthInfoService staffAssignAuthInfoService;
 
-    private IRoleInfoService roleInfoService;
-
-    private IAuthUserInfoService userInfoService;
-
-    @Autowired
-    public void setUserInfoService(IAuthUserInfoService userInfoService) {
-        this.userInfoService = userInfoService;
-    }
-
-    @Autowired
-    public void setRoleInfoService(IRoleInfoService roleInfoService) {
-        this.roleInfoService = roleInfoService;
-    }
-
     @Autowired
     public void setStaffAssignAuthInfoService(IStaffAssignAuthInfoService staffAssignAuthInfoService) {
         this.staffAssignAuthInfoService = staffAssignAuthInfoService;
@@ -56,6 +40,7 @@ public class RoleAuthCallbackHandler implements IRoleAuthCallbackHandler {
         this.roleAuthApplyService = roleAuthApplyService;
     }
 
+    @Transactional(rollbackFor = Exception.class)
     @Override
     public ApprovalBaseRespDto callBackHandle(String processInstId, String type, String applyStatus) {
         log.info("开始处理角色权限申请");
@@ -70,80 +55,54 @@ public class RoleAuthCallbackHandler implements IRoleAuthCallbackHandler {
         if (!AuthApplyStatusEnum.AGREE.getValue().equals(applyStatus)) {
             return new ApprovalBaseRespDto().success();
         }
+        Date now = new Date();
+
+        // 将未到授权时间的申请设置位待授权
+        List<RoleAuthApply> readyToAuth = filterToBeAuthed(authApplies, now);
+
+        // 过滤有效的权限申请
+        List<RoleAuthApply> activeApplies = getEndTimeActiveApply(readyToAuth, now);
 
         // 保存角色授权
-        saveRoleAuth(authApplies);
+        if (CollectionUtils.isNotEmpty(activeApplies)) {
+            staffAssignAuthInfoService.startRoleAuthApply(activeApplies);
+        }
 
         return new ApprovalBaseRespDto().success();
     }
 
-    /**
-     * 保存角色授权申请
-     * @param authApplies
-     */
-    private void saveRoleAuth(List<RoleAuthApply> authApplies) {
-        // 查询申请人员
-        List<String> userIds = authApplies.stream().map(RoleAuthApply::getUserId).distinct().collect(Collectors.toList());
-        List<AuthUserInfo> userInfos = userInfoService.findByIds(userIds);
-        Map<String, AuthUserInfo> userMap = userInfos.stream().collect(Collectors.toMap(AuthUserInfo::getId, e -> e));
-
-        // 查询应用中的角色
-        List<String> appIds = authApplies.stream().map(RoleAuthApply::getAppId).distinct().collect(Collectors.toList());
-        List<RoleInfo> roles = roleInfoService.getRolesByAppIds(appIds);
-        Map<String, Map<String, String>> appRoleMap = roles.stream().collect(Collectors.groupingBy(RoleInfo::getAppId,
-                Collectors.collectingAndThen(Collectors.toList(),
-                        e -> e.stream().collect(Collectors.toMap(RoleInfo::getCode, RoleInfo::getId)))));
-
-        List<StaffAssignAuthInfo> roleAuths = getStaffAssignAuthInfos(authApplies, appRoleMap, userMap);
-        if (CollectionUtils.isNotEmpty(roleAuths)) {
-            staffAssignAuthInfoService.batchSave(roleAuths);
+    private List<RoleAuthApply> filterToBeAuthed(List<RoleAuthApply> authApplies, Date now) {
+        Map<Boolean, List<RoleAuthApply>> collect = authApplies.stream().collect(Collectors.partitioningBy(e -> {
+            Date startTime = e.getStartTime();
+            // 有效的
+            return Objects.isNull(startTime) || now.after(startTime);
+        }));
+        List<RoleAuthApply> tobeAuthed = collect.get(Boolean.FALSE);
+        if (CollectionUtils.isNotEmpty(tobeAuthed)) {
+            roleAuthApplyService.setToBeAuthed(tobeAuthed, BooleanEnum.TRUE.getValue());
         }
+        return collect.get(Boolean.TRUE);
     }
 
-    private List<StaffAssignAuthInfo> getStaffAssignAuthInfos(List<RoleAuthApply> authApplies, Map<String, Map<String, String>> appRoleMap,
-                                                              Map<String, AuthUserInfo> userMap) {
-        Date createTime = new Date();
-        // 过滤申请中的但还未审批通过的角色和已过期的申请
-        authApplies = authApplies.stream().filter(e-> {
+
+    private List<RoleAuthApply> getEndTimeActiveApply(List<RoleAuthApply> authApplies, Date now) {
+        return authApplies.stream().filter(e -> {
             Date endTime = e.getEndTime();
-            if (Objects.nonNull(endTime) && createTime.after(endTime)) {
-                return false;
-            }
-            String appId = e.getAppId();
-            Map<String, String> roleCods = appRoleMap.get(appId);
-            return Objects.nonNull(roleCods) && roleCods.containsKey(e.getRoleCode());
+            return Objects.isNull(endTime) || now.before(endTime);
         }).collect(Collectors.toList());
-
-        if (CollectionUtils.isEmpty(authApplies)) {
-            return Collections.emptyList();
-        }
-        String activeTime = getActiveTime(authApplies);
-
-        return authApplies.stream().map(e -> {
-            StaffAssignAuthInfo authInfo = new StaffAssignAuthInfo();
-            String roleId = appRoleMap.get(e.getAppId()).get(e.getRoleCode());
-            authInfo.setRoleId(roleId);
-            authInfo.setAppId(e.getAppId());
-
-            AuthUserInfo authUserInfo = userMap.get(e.getUserId());
-            authInfo.setStaffId(e.getUserId());
-            authInfo.setStaffOrgId(authUserInfo.getOrgId());
-
-            authInfo.setCreateTime(createTime);
-            authInfo.setActiveTime(activeTime);
-            return authInfo;
-        }).filter(Objects::nonNull).collect(Collectors.toList());
     }
 
-    private String getActiveTime(List<RoleAuthApply> authApplies) {
-        RoleAuthApply roleAuthApply = authApplies.get(0);
-        Date endTime = roleAuthApply.getEndTime();
-        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-        if (Objects.isNull(endTime)) {
-            return "长期";
-        } else {
-            return format.format(endTime);
+    @Transactional(rollbackFor = Exception.class)
+    @Override
+    public void startRoleAuth() {
+        log.info("授权将要开始的服务授权开始");
+        List<RoleAuthApply> starts = roleAuthApplyService.getStartToAuth();
+        List<RoleAuthApply> activeApply = getEndTimeActiveApply(starts, new Date());
+        if (CollectionUtils.isNotEmpty(activeApply)) {
+            staffAssignAuthInfoService.startRoleAuthApply(activeApply);
+            roleAuthApplyService.setToBeAuthed(activeApply, BooleanEnum.FALSE.getValue());
         }
+        log.info("授权将要开始的服务授权结束");
     }
 
 }

+ 2 - 1
dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/business/impl/zerotrust/RoleOperateCallbackHandler.java

@@ -15,6 +15,7 @@ import com.dragonsoft.duceap.commons.util.string.StringUtils;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Transactional;
 
 /**
  * @author mazq
@@ -36,7 +37,7 @@ public class RoleOperateCallbackHandler implements IRoleOperateCallbackHandler {
     public void setRoleOperateApplyService(IRoleOperateApplyService roleOperateApplyService) {
         this.roleOperateApplyService = roleOperateApplyService;
     }
-
+    @Transactional(rollbackFor = Exception.class)
     @Override
     public ApprovalBaseRespDto callBackHandle(String processInstId, String type, String applyStatus) {
         RoleOperateContent roleOperateContent = roleOperateApplyService.getByProcessInstIdId(processInstId);

+ 38 - 52
dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/business/impl/zerotrust/ServiceAuthCallbackHandler.java

@@ -1,20 +1,20 @@
 package com.dragoninfo.dcuc.auth.business.impl.zerotrust;
 
-import com.dragoninfo.dcuc.app.entity.ApplyInfo;
 import com.dragoninfo.dcuc.app.facade.IApplyInfoFacade;
 import com.dragoninfo.dcuc.app.facade.IServiceResourceFacade;
-import com.dragoninfo.dcuc.app.vo.ServiceResourceVo;
 import com.dragoninfo.dcuc.auth.auth.dto.zerotrust.approval.ApprovalBaseRespDto;
-import com.dragoninfo.dcuc.auth.auth.entity.ServiceAuthResult;
+import com.dragoninfo.dcuc.auth.auth.entity.zerotrust.RoleAuthApply;
 import com.dragoninfo.dcuc.auth.auth.entity.zerotrust.ServiceAuthApply;
 import com.dragoninfo.dcuc.auth.auth.enumresources.zerotrust.approval.AuthApplyStatusEnum;
 import com.dragoninfo.dcuc.auth.auth.service.IServiceAuthResultService;
 import com.dragoninfo.dcuc.auth.auth.service.zerotrust.IServiceAuthApplyService;
 import com.dragoninfo.dcuc.auth.business.zerotrust.IServiceAuthCallbackHandler;
+import com.dragonsoft.duceap.base.enums.BooleanEnum;
 import com.dragonsoft.duceap.commons.util.collections.CollectionUtils;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Transactional;
 
 import java.util.*;
 import java.util.stream.Collectors;
@@ -29,10 +29,6 @@ public class ServiceAuthCallbackHandler implements IServiceAuthCallbackHandler {
 
     private IServiceAuthApplyService serviceAuthApplyService;
 
-    private IServiceResourceFacade serviceResourceFacade;
-
-    private IApplyInfoFacade applyInfoFacade;
-
     private IServiceAuthResultService serviceAuthResultService;
 
     @Autowired
@@ -40,21 +36,12 @@ public class ServiceAuthCallbackHandler implements IServiceAuthCallbackHandler {
         this.serviceAuthResultService = serviceAuthResultService;
     }
 
-    @Autowired
-    public void setServiceResourceFacade(IServiceResourceFacade serviceResourceFacade) {
-        this.serviceResourceFacade = serviceResourceFacade;
-    }
-
-    @Autowired
-    public void setApplyInfoFacade(IApplyInfoFacade applyInfoFacade) {
-        this.applyInfoFacade = applyInfoFacade;
-    }
-
     @Autowired
     public void setServiceAuthApplyService(IServiceAuthApplyService serviceAuthApplyService) {
         this.serviceAuthApplyService = serviceAuthApplyService;
     }
 
+    @Transactional(rollbackFor = Exception.class)
     @Override
     public ApprovalBaseRespDto callBackHandle(String processInstId, String type, String applyStatus) {
         log.info("开始处理服务权限申请");
@@ -69,53 +56,52 @@ public class ServiceAuthCallbackHandler implements IServiceAuthCallbackHandler {
         if (!AuthApplyStatusEnum.AGREE.getValue().equals(applyStatus)) {
             return new ApprovalBaseRespDto().success();
         }
+        Date now = new Date();
+
+        // 将未到授权时间的申请设置位待授权
+        List<ServiceAuthApply> readyToAuth = filterToBeAuthed(authApplies, now);
+
+        // 过滤有效的权限申请
+        List<ServiceAuthApply> activeApplies = getEndTimeActiveApply(readyToAuth, now);
 
         // 保存服务授权
-        saveServiceAuth(authApplies);
+        if (CollectionUtils.isNotEmpty(activeApplies)) {
+            serviceAuthResultService.startServiceAuthApply(authApplies);
+        }
 
         return new ApprovalBaseRespDto().success();
     }
 
-    private void saveServiceAuth(List<ServiceAuthApply> authApplies) {
-        List<ServiceAuthResult> serviceAuthResult = getServiceAuthResult(authApplies);
-        if (CollectionUtils.isNotEmpty(serviceAuthResult)) {
-            serviceAuthResultService.batchSave(serviceAuthResult);
+    @Transactional(rollbackFor = Exception.class)
+    @Override
+    public void startServiceAuth() {
+        log.info("授权将要开始的服务授权开始");
+        List<ServiceAuthApply> starts = serviceAuthApplyService.getStartToAuth();
+        List<ServiceAuthApply> activeApply = getEndTimeActiveApply(starts, new Date());
+        if (CollectionUtils.isNotEmpty(activeApply)) {
+            serviceAuthResultService.startServiceAuthApply(activeApply);
+            serviceAuthApplyService.setToBeAuthed(activeApply, BooleanEnum.FALSE.getValue());
         }
+        log.info("授权将要开始的服务授权结束");
     }
 
-    private List<ServiceAuthResult> getServiceAuthResult(List<ServiceAuthApply> authApplies) {
-        List<String> appIds = authApplies.stream().map(ServiceAuthApply::getAppId).distinct().collect(Collectors.toList());
-        List<String> serviceIds = authApplies.stream().map(ServiceAuthApply::getServiceId).distinct().collect(Collectors.toList());
-        List<ApplyInfo> appInfos = applyInfoFacade.getAppById(appIds);
-        List<ServiceResourceVo> serviceResourceVos = serviceResourceFacade.getServiceByIds(serviceIds);
-        Map<String, ApplyInfo> appMap = appInfos.stream().collect(Collectors.toMap(ApplyInfo::getId, e -> e));
-        Map<String, ServiceResourceVo> serviceMap = serviceResourceVos.stream().collect(Collectors.toMap(ServiceResourceVo::getId, e -> e));
-
-        Date createTime = new Date();
-        authApplies = authApplies.stream().filter(e-> {
-            Date endTime = e.getEndTime();
-            return Objects.isNull(endTime) || createTime.before(endTime);
-        }).collect(Collectors.toList());
-        if (CollectionUtils.isEmpty(authApplies)) {
-            return Collections.emptyList();
+    private List<ServiceAuthApply> filterToBeAuthed(List<ServiceAuthApply> authApplies, Date now) {
+        Map<Boolean, List<ServiceAuthApply>> collect = authApplies.stream().collect(Collectors.partitioningBy(e -> {
+            Date startTime = e.getStartTime();
+            // 有效的
+            return Objects.isNull(startTime) || now.after(startTime);
+        }));
+        List<ServiceAuthApply> tobeAuthed = collect.get(Boolean.FALSE);
+        if (CollectionUtils.isNotEmpty(tobeAuthed)) {
+            serviceAuthApplyService.setToBeAuthed(tobeAuthed, BooleanEnum.TRUE.getValue());
         }
+        return collect.get(Boolean.TRUE);
+    }
 
-        return authApplies.stream().map(e -> {
+    private List<ServiceAuthApply> getEndTimeActiveApply(List<ServiceAuthApply> authApplies, Date now) {
+        return authApplies.stream().filter(e -> {
             Date endTime = e.getEndTime();
-            ServiceAuthResult authResult = new ServiceAuthResult();
-            String serviceId = e.getServiceId();
-            String appId = e.getAppId();
-            ServiceResourceVo serviceResourceVo = serviceMap.get(serviceId);
-            authResult.setServiceId(serviceId);
-            authResult.setServiceCode(serviceResourceVo.getServiceCode());
-            authResult.setAppId(appId);
-            authResult.setAppCode(appMap.get(appId).getApplyCode());
-            authResult.setEndTime(endTime);
-            authResult.setCreateTime(createTime);
-            authResult.setServiceResourceId(serviceResourceVo.getResourceId());
-
-            return authResult;
+            return Objects.isNull(endTime) || now.before(endTime);
         }).collect(Collectors.toList());
     }
-
 }

+ 3 - 0
dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/business/impl/zerotrust/ZeroTrustAuthApplyBusinessImpl.java

@@ -44,6 +44,7 @@ import com.dragonsoft.duceap.commons.util.string.StringUtils;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
 
 import javax.validation.Valid;
 import java.util.*;
@@ -146,6 +147,7 @@ public class ZeroTrustAuthApplyBusinessImpl implements IZeroTrustAuthApplyBusine
         return ZeroTrustDataRespVO.success(respVos);
     }
 
+    @Transactional(rollbackFor = Exception.class)
     @Override
     public ZeroTrustDataRespVO<AuthApplyRespVo> roleAuthApply(ApiRoleAuthReqVo reqVo) {
         log.info("角色授权申请,应用令牌:{}, 申请内容:{}", reqVo.getAppTokenId(), JSONUtil.toJsonStr(reqVo));
@@ -201,6 +203,7 @@ public class ZeroTrustAuthApplyBusinessImpl implements IZeroTrustAuthApplyBusine
         return Result.success(applyInfoVo);
     }
 
+    @Transactional(rollbackFor = Exception.class)
     @Override
     public ZeroTrustDataRespVO<AuthApplyRespVo> serviceAuthApply(ApiServiceAuthReqVo reqVo) {
         log.info("服务授权申请,应用令牌:{}, 申请内容:{}", reqVo.getAppTokenId(), JSONUtil.toJsonStr(reqVo));

+ 6 - 0
dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/business/zerotrust/IRoleAuthCallbackHandler.java

@@ -8,4 +8,10 @@ import com.dragoninfo.dcuc.auth.auth.dto.zerotrust.approval.ApprovalBaseRespDto;
  */
 public interface IRoleAuthCallbackHandler {
     ApprovalBaseRespDto callBackHandle(String processInstId, String type, String applyStatus);
+
+    /**
+     * 新增开始时间到达的角色授权
+     */
+    void startRoleAuth();
+
 }

+ 5 - 0
dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/business/zerotrust/IServiceAuthCallbackHandler.java

@@ -8,4 +8,9 @@ import com.dragoninfo.dcuc.auth.auth.dto.zerotrust.approval.ApprovalBaseRespDto;
  */
 public interface IServiceAuthCallbackHandler {
     ApprovalBaseRespDto callBackHandle(String processInstId, String type, String applyStatus);
+
+    /**
+     * 新增开始时间到达的服务授权
+     */
+    void startServiceAuth();
 }

+ 25 - 1
dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/systemtask/service/AuthMonitorTask.java

@@ -1,9 +1,15 @@
 package com.dragoninfo.dcuc.auth.systemtask.service;
 
+import com.dragoninfo.dcuc.auth.auth.service.IServiceAuthResultService;
 import com.dragoninfo.dcuc.auth.auth.service.IStaffAssignAuthInfoService;
+import com.dragoninfo.dcuc.auth.business.zerotrust.IRoleAuthCallbackHandler;
+import com.dragoninfo.dcuc.auth.business.zerotrust.IServiceAuthCallbackHandler;
+import com.dragoninfo.dcuc.auth.util.ThreadPoolHolder;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
+import java.util.concurrent.ExecutorService;
+
 /**
  * @author Administrator
  * @date 2018/6/6
@@ -14,8 +20,26 @@ public class AuthMonitorTask {
     @Autowired
     private IStaffAssignAuthInfoService staffAssignAuthInfoService;
 
+    @Autowired
+    private IServiceAuthResultService serviceAuthResultService;
+
+    @Autowired
+    private IServiceAuthCallbackHandler serviceAuthCallbackHandler;
+
+    @Autowired
+    private IRoleAuthCallbackHandler roleAuthCallbackHandler;
+
     public void execute() {
-        staffAssignAuthInfoService.authMonitor(null);
+        ExecutorService executor = ThreadPoolHolder.executor;
+        // 删除过期的角色授权
+        executor.execute(()-> staffAssignAuthInfoService.deleteExpireAuth());
+        // 删除过期的服务授权
+        executor.execute(()-> serviceAuthResultService.deleteExpireAuth());
+        // 新增开始时间到达的角色授权
+        executor.execute(()-> roleAuthCallbackHandler.startRoleAuth());
+        // 新增开始时间到达的服务授权
+        executor.execute(()-> serviceAuthCallbackHandler.startServiceAuth());
     }
+
 }
 

+ 2 - 2
dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/auth/async/EvenBusThreadPoolHolder.java → dcuc-auth-service/src/main/java/com/dragoninfo/dcuc/auth/util/ThreadPoolHolder.java

@@ -1,4 +1,4 @@
-package com.dragoninfo.dcuc.auth.auth.async;
+package com.dragoninfo.dcuc.auth.util;
 
 import java.util.concurrent.*;
 
@@ -6,7 +6,7 @@ import java.util.concurrent.*;
  * @author mazq
  * @date 2021/9/10
  */
-public class EvenBusThreadPoolHolder {
+public class ThreadPoolHolder {
     public static final ExecutorService executor = new ThreadPoolExecutor(10,
             20,
             10,

+ 11 - 0
dcuc-auth-service/src/main/resources/config/mysql/V4_3_0035__ServiceAuthApply.sql

@@ -4,6 +4,9 @@ create table T_AUTH_SERVICE_AUTH_APPLY
         primary key,
     APP_ID          varchar(32)            null comment '应用id',
     SERVICE_ID      varchar(32)            null comment '服务id',
+    START_TIME      datetime               null comment '权限开始时间',
+    END_TIME        datetime               null comment '权限结束时间',
+    TO_BE_AUTHED    varchar(2)             null comment '是否待授权 0 否 1是 审批通过后开始时间未到',
     PROCESS_INST_ID varchar(64)            null comment '审批回调后返回的流程实例id',
     TASK_INST_ID    varchar(128)           null comment '审批返回的任务节点',
     APPROVAL_RESULT varchar(10)            null comment '转为后的审批结果',
@@ -16,6 +19,14 @@ create table T_AUTH_SERVICE_AUTH_APPLY
     comment '服务授权申请表';
 
 create index T_AUTH_SERVICE_AUTH_APPLY_INX_INST_ID on T_AUTH_SERVICE_AUTH_APPLY (PROCESS_INST_ID);
+create index T_AUTH_SERVICE_AUTH_APPLY_INX_S_TIME on T_AUTH_SERVICE_AUTH_APPLY (START_TIME);
+create index T_AUTH_SERVICE_AUTH_APPLY_INX_E_TIME on T_AUTH_SERVICE_AUTH_APPLY (END_TIME);
+
+ALTER TABLE T_AUTH_ROLE_AUTH_APPLY ADD COLUMN START_TIME datetime  null comment '权限开始时间';
+ALTER TABLE T_AUTH_ROLE_AUTH_APPLY ADD COLUMN END_TIME datetime  null comment '权限结束时间';
+ALTER TABLE T_AUTH_ROLE_AUTH_APPLY ADD COLUMN TO_BE_AUTHED varchar(2) null comment '是否待授权 0 否 1是 审批通过后开始时间未到';
+create index T_AUTH_ROLE_AUTH_APPLY_INX_S_TIME on T_AUTH_ROLE_AUTH_APPLY (START_TIME);
+create index T_AUTH_ROLE_AUTH_APPLY_INX_E_TIME on T_AUTH_ROLE_AUTH_APPLY (END_TIME);
 
 ALTER TABLE T_AUTH_APP_FUN_AUTH_RESULT DROP COLUMN START_TIME;
 ALTER TABLE T_AUTH_APP_FUN_AUTH_RESULT DROP COLUMN AUTH_STATUS;