yusm 1 месяц назад
Родитель
Сommit
83ec78307b

+ 108 - 28
fhKeeper/formulahousekeeper/management-platform/src/main/java/com/management/platform/controller/DingTalkController.java

@@ -1,52 +1,132 @@
 package com.management.platform.controller;
 
-import com.management.platform.entity.DingTalkConfig;
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.management.platform.entity.*;
 
-import com.management.platform.entity.DingTalkUserInfo;
+import com.management.platform.mapper.CompanyMapper;
+import com.management.platform.service.UserService;
 import com.management.platform.service.impl.AuthService;
 import com.management.platform.service.impl.DingTalkService;
+import com.management.platform.util.MessageUtils;
+import com.management.platform.util.UserAgentUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.ResponseEntity;
+import org.springframework.http.*;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.client.RestTemplate;
+import org.springframework.web.servlet.ModelAndView;
+import org.springframework.web.servlet.view.RedirectView;
 
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 
 @RestController
 @RequestMapping("/dingtalk")
+@Slf4j
 public class DingTalkController {
-    
-    private final DingTalkConfig dingTalkConfig;
-    private final DingTalkService dingTalkService;
-    private final AuthService authService;
-
-    @Autowired
-    public DingTalkController(DingTalkConfig dingTalkConfig, 
-                           DingTalkService dingTalkService,
-                           AuthService authService) {
-        this.dingTalkConfig = dingTalkConfig;
-        this.dingTalkService = dingTalkService;
-        this.authService = authService;
-    }
+    @Resource
+    HttpServletRequest request;
+
+    @Resource
+    private UserService userService;
+
+    @Resource
+    private  DingTalkService dingTalkService;
+
+    @Resource
+    private CompanyMapper companyMapper;
+
+    private final String url="https://worktime.ttkuaiban.com/#/";
+
 
     /**
-     * 钉钉回调接口
+     * 钉钉扫码登录
      */
     @GetMapping("/callback")
-    public ResponseEntity<?> callback(@RequestParam("code") String code,
-                                      @RequestParam("state") String state,
-                                      HttpServletResponse response) throws IOException {
+    public ModelAndView callback( String code,String state) {
+        Map<String,Object> reqParam = new HashMap<String,Object>(16);
         // 1. 用code换取用户信息
-        DingTalkUserInfo userInfo = dingTalkService.getUserInfoByCode(code);
-        
-        // 2. 业务系统登录逻辑
-        String userId = "";
-        
-        // 3. 重定向到前端并携带token
-        response.sendRedirect(dingTalkConfig.getRedirectUri() + "?userId=" + userId);
-        return ResponseEntity.ok().build();
+        String userOpenId = dingTalkService.getUserOpenId(code);
+        User user = userService.getOne(new QueryWrapper<User>().eq("dingding_userid", userOpenId));
+        String redirecUrl = null;
+        Integer companyId=0;
+        if (user!=null) {
+            //该用户已存在
+            log.info("找到用户dingding_userid=="+user.getDingdingUserid());
+            log.info("找到用户userId=="+user.getId());
+            companyId= user.getCompanyId();
+            if (user.getIsActive() == 1) {
+                reqParam.put("userId", user.getId());
+            } else {
+                //提示账号已停用
+                //reqParam.put("errorMsg", "您的账号已停用,无法登录");
+                reqParam.put("errorMsg", MessageUtils.message("user.inactive"));
+            }
+        }
+        else {
+                reqParam.put("errorMsg", "尚未绑定钉钉,请使用账号密码登录。");
+        }
+
+        if (!StringUtils.isEmpty(state) && state.length() > 1) {
+            reqParam.put("path", state);
+        }
+        String router = "login";
+        if (companyId > 0) {
+            HashMap compExpireInfo = getCompExpireInfo(companyId);
+            if (compExpireInfo != null) {
+                //过期了
+                router = "expire";
+                reqParam.put("expDate", compExpireInfo.get("expDate"));
+                reqParam.put("version", compExpireInfo.get("version"));
+            }
+        }
+        redirecUrl = url + router;
+        ModelAndView modelAndView = new ModelAndView(
+                new RedirectView(redirecUrl), reqParam);
+        return modelAndView;
+    }
+
+    private HashMap getCompExpireInfo(Integer companyId) {
+        Company company = companyMapper.selectById(companyId);
+        int version = 1;
+        if (company.getPackageProject() == 1) {
+            version = 2;
+        }
+        if (company.getPackageOa() == 1) {
+            version = 3;
+        }
+        if (company.getPackageEngineering() == 1) {
+            version = 4;
+        }
+        boolean hasExp = false;
+        LocalDateTime expirationDate = company.getExpirationDate();
+        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
+        if (null != company.getExpirationDate()) {
+            if (expirationDate.isBefore(LocalDateTime.now())) {
+                hasExp = true;
+            }
+        }
+
+        if (hasExp) {
+            String format = dtf.format(expirationDate);
+            HashMap map = new HashMap();
+            map.put("version", version);
+            map.put("expDate", format);
+            return map;
+        } else {
+            return null;
+        }
     }
 }

+ 60 - 0
fhKeeper/formulahousekeeper/management-platform/src/main/java/com/management/platform/service/impl/DingTalkService.java

@@ -4,6 +4,8 @@ import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.management.platform.entity.DingTalkConfig;
 import com.management.platform.entity.DingTalkUserInfo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpHeaders;
@@ -68,6 +70,64 @@ public class DingTalkService {
         String unionId = userInfo.get("unionid").asText();
         return getUserDetail(unionId);
     }
+
+    /**
+     * 使用临时授权码获取用户信息
+     */
+    public String getUserOpenId(String code) {
+        final Logger logger = LoggerFactory.getLogger(this.getClass());
+
+        try {
+            logger.info("开始获取用户OpenID,临时授权码: {}", code);
+
+            // 1. 构造请求参数
+            String timestamp = String.valueOf(System.currentTimeMillis());
+            String signature = generateSignature(timestamp);
+            logger.debug("生成请求参数 - timestamp: {}, signature: {}", timestamp, signature);
+
+            // 2. 构造请求体
+            Map<String, String> requestBody = new HashMap<>();
+            requestBody.put("tmp_auth_code", code);
+            logger.debug("构造请求体: {}", requestBody);
+
+            // 3. 构造请求URL
+            String url = String.format("%s?accessKey=%s&timestamp=%s&signature=%s",
+                    GET_USER_INFO_URL, "suitejwoq9dw4bxv4stdb", timestamp, signature);
+            logger.info("构造请求URL: {}", url);
+
+            // 4. 发送请求
+            logger.info("开始向钉钉服务器发送请求...");
+            ResponseEntity<String> response = restTemplate.postForEntity(
+                    url,
+                    new HttpEntity<>(requestBody, buildHeaders()),
+                    String.class);
+            logger.info("收到钉钉服务器响应,状态码: {}", response.getStatusCodeValue());
+            logger.debug("完整响应: {}", response.getBody());
+
+            // 5. 解析响应
+            JsonNode jsonNode = parseResponse(response.getBody());
+            if (jsonNode == null) {
+                throw new RuntimeException("解析响应数据失败,返回的JSON为空");
+            }
+
+            JsonNode userInfo = jsonNode.get("user_info");
+            if (userInfo == null) {
+                logger.error("响应中缺少user_info字段,完整响应: {}", jsonNode.toString());
+                throw new RuntimeException("钉钉返回的用户信息不完整");
+            }
+
+            // 6. 获取用户详细信息
+            String unionId = userInfo.get("unionid").asText();
+            String openid = userInfo.get("openid").asText();
+
+            logger.info("成功获取用户信息 - unionId: {}, openid: {}", unionId, openid);
+            return openid;
+
+        } catch (Exception e) {
+            logger.error("获取用户OpenID失败,临时授权码: {},错误信息: {}", code, e.getMessage(), e);
+            throw new RuntimeException("获取用户OpenID失败: " + e.getMessage(), e);
+        }
+    }
     
     /**
      * 获取用户详细信息