Merge branch 'feature/dingdingLogin' into pre

This commit is contained in:
wangli 2026-01-14 10:20:03 +08:00
commit 01b99bea18
6 changed files with 221 additions and 332 deletions

View File

@ -187,6 +187,8 @@ public class FlowableConfiguration {
private Environment environment;
@Value("${ossEnvUrl:http://dev-app.axzo.cn/oss}")
private String ossEvnUrl;
@Value("${rivenEnvUrl:http://dev-app.axzo.cn/riven}")
private String rivenEnvUrl;
private static String POD_NAMESPACE;
static {
@ -205,6 +207,7 @@ public class FlowableConfiguration {
String url = requestTemplate.feignTarget().url();
// 如需修改微服务地址,建议通过外部化参数来调整
url = url.replace("http://oss:9123", ossEvnUrl);
url = url.replace("http://riven:8080", rivenEnvUrl);
String profile = environment.getProperty("spring.profiles.active");
if (Objects.equals(profile, "test") && url.contains("dev-app.axzo.cn")) {
url = url.replace("dev-app", "test-api");

View File

@ -284,16 +284,16 @@ public class WpsUtil {
return Optional.empty();
}
ListOrgNodeUserReq req = new ListOrgNodeUserReq();
if (StringUtils.hasText(assigner.getTenantId())) {
if (StringUtils.hasText(assigner.getTenantId()) && !Objects.equals(assigner.getTenantId(), "null")) {
req.setWorkspaceId(Long.valueOf(assigner.getTenantId()));
}
if (StringUtils.hasText(assigner.getOuId())) {
if (StringUtils.hasText(assigner.getOuId()) && !Objects.equals(assigner.getOuId(), "null")) {
req.setOrganizationalUnitId(Long.valueOf(assigner.getOuId()));
}
if (StringUtils.hasText(assigner.getNodeId())) {
if (StringUtils.hasText(assigner.getNodeId()) && !Objects.equals(assigner.getNodeId(), "null")) {
req.setAncestorNodeIds(Lists.newArrayList(Long.valueOf(assigner.getNodeId())));
}
if (StringUtils.hasText(assigner.getPersonId())) {
if (StringUtils.hasText(assigner.getPersonId()) && !Objects.equals(assigner.getPersonId(), "null")) {
req.setPersonIds(Lists.newArrayList(Long.valueOf(assigner.getPersonId())));
}
req.setNeeds(ListNodeUserReq.Needs.builder().job(true).unit(true).personProfile(true).build());

View File

@ -1,6 +1,9 @@
package cn.axzo.workflow.server.controller.web;
import cn.axzo.framework.domain.data.AssertUtil;
import cn.axzo.riven.client.domain.ThirdPartyUserDTO;
import cn.axzo.riven.client.feign.ThirdPartySyncApi;
import cn.axzo.riven.client.req.ThirdPartyUserReq;
import cn.axzo.workflow.common.model.request.bpmn.process.BpmnProcessInstanceAbortDTO;
import cn.axzo.workflow.common.model.request.bpmn.process.BpmnProcessInstanceCancelDTO;
import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskAuditDTO;
@ -8,16 +11,19 @@ import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskDelegateAssigner;
import cn.axzo.workflow.core.repository.entity.ExtAxProcessLog;
import cn.axzo.workflow.core.service.BpmnProcessTaskService;
import cn.axzo.workflow.core.service.ExtAxProcessLogService;
import cn.axzo.workflow.server.common.util.RpcExternalUtil;
import cn.axzo.workflow.server.controller.web.bpmn.BpmnProcessInstanceController;
import cn.axzo.workflow.server.controller.web.bpmn.BpmnProcessJobController;
import cn.axzo.workflow.server.controller.web.bpmn.BpmnProcessTaskController;
import cn.axzo.workflow.server.service.AuthCodeService;
import cn.axzo.workflow.server.xxljob.DangerSuperOperationJobHandler;
import cn.azxo.framework.common.model.CommonResponse;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
@ -62,65 +68,47 @@ public class DangerOperationController {
@Resource
private ExtAxProcessLogService processLogService;
@Resource
private AuthCodeService authCodeService;
@Resource
private Environment environment;
@Resource
private ThirdPartySyncApi thirdPartySyncApi;
@Value("${dingtalk.appKey:dingfg3ijkpjkqnrgapc}")
private String appKey;
@Value("${dingtalk.appSecret:MECKP45vlYF9zmbpueUsPlPWQIPkMdbNMH4q7kCASFDWkMRDDU8iQ-eQdWWhIVZE}")
private String appSecret;
// 显示表单页面
@GetMapping("/web/process/form")
public String showProcessForm(HttpSession session, Model model) {
log.info("{} 访问流程表单页面", getOperatorInfo(session));
// 检查session中是否已验证授权码
Boolean isAuthenticated = (Boolean) session.getAttribute("isAuthenticated");
model.addAttribute("isAuthenticated", isAuthenticated != null && isAuthenticated);
// 如果已认证尝试获取用户信息并传递给页面
if (isAuthenticated != null && isAuthenticated) {
Object dingUserObj = session.getAttribute("dingUser");
if (dingUserObj instanceof JSONObject) {
String nick = ((JSONObject) dingUserObj).getString("nick");
model.addAttribute("userNick", nick);
}
}
String myPodNamespace = environment.getProperty(K8S_POD_NAME_SPACE);
model.addAttribute("apiBaseUrl", StringUtils.hasText(myPodNamespace) ? "/workflow-engine" : "");
model.addAttribute("dingTalkAppKey", appKey);
// 可以在这里添加需要传递到页面的数据
return "form"; // 对应templates目录下的form.html
}
/**
* 获取授权码
*
* @param password
* @return
*/
@PostMapping("/web/process/get-auth-code")
@ResponseBody
public CommonResponse<String> getAuthCode(@RequestParam String password) {
if (Objects.equals("WANG+lI648438", password)) {
String authCode = authCodeService.generateAuthCode();
return CommonResponse.success(authCode);
}
return CommonResponse.error("密码错误");
}
/**
* 验证用户输入的授权码
*/
@PostMapping("/web/process/validate-auth")
public String validateAuthCode(@RequestParam String authCode, HttpSession session, Model model) {
if (Objects.equals("WANG+lI648438", authCode) || authCodeService.validateAuthCode(authCode)) {
// 验证通过在session中标记
session.setAttribute("isAuthenticated", true);
model.addAttribute("isAuthenticated", true);
} else {
// 验证失败提示错误
model.addAttribute("isAuthenticated", false);
model.addAttribute("authError", "授权码无效或已过期,请重新输入");
}
String myPodNamespace = environment.getProperty(K8S_POD_NAME_SPACE);
model.addAttribute("apiBaseUrl", StringUtils.hasText(myPodNamespace) ? "/workflow-engine" : "");
return "form"; // 重新显示授权码输入框
}
// 处理表单提交
@PostMapping(value = "/web/process/handle")
@ResponseBody
public CommonResponse<String> handleProcess(@Validated @RequestBody DangerSuperOperationJobHandler.DangerOperationJobParam jobParam, Model model) {
public CommonResponse<String> handleProcess(@Validated @RequestBody DangerSuperOperationJobHandler.DangerOperationJobParam jobParam, HttpSession session, Model model) {
// 处理表单提交的逻辑
log.info("请求参入: {}", JSON.toJSONString(jobParam));
log.info("{} 请求操作流程: {}", getOperatorInfo(session), JSON.toJSONString(jobParam));
try {
ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(jobParam.getProcessInstanceId()).singleResult();
@ -237,4 +225,105 @@ public class DangerOperationController {
log.info("撤回操作完成");
}
/**
* 钉钉扫码登录回调
*
* @param authCode 钉钉返回的授权码
*/
@GetMapping("/web/process/dingtalk-callback")
public String dingTalkCallback(@RequestParam("authCode") String authCode, HttpSession session, Model model) {
log.info("收到钉钉登录回调, authCode: {}", authCode);
// 如果没有配置 AppSecret则无法进行后续交互直接返回错误或者为了测试方便这里可以留个后门? 严格处理
if (!StringUtils.hasText(appSecret)) {
log.error("DingTalk AppSecret not configured");
model.addAttribute("authError", "服务端未配置 AppSecret无法登录");
return "form";
}
try {
// 1. 获取 AccessToken
// 文档: https://open.dingtalk.com/document/isvapp/obtain-user-token
JSONObject tokenParams = new JSONObject();
tokenParams.put("clientId", appKey);
tokenParams.put("clientSecret", appSecret);
tokenParams.put("code", authCode);
tokenParams.put("grantType", "authorization_code");
String tokenResponse = HttpRequest.post("https://api.dingtalk.com/v1.0/oauth2/userAccessToken")
.body(tokenParams.toJSONString())
.timeout(5000)
.execute()
.body();
log.info("DingTalk Token Response: {}", tokenResponse);
JSONObject tokenJson = JSON.parseObject(tokenResponse);
String accessToken = tokenJson.getString("accessToken");
if (!StringUtils.hasText(accessToken)) {
log.error("Failed to get access token: {}", tokenResponse);
model.addAttribute("authError", "钉钉登录验证失败: 无法获取 AccessToken");
return "form";
}
// 2. 获取用户详情
// 文档: https://open.dingtalk.com/document/isvapp/obtain-user-information
String userInfoResponse = HttpRequest.get("https://api.dingtalk.com/v1.0/contact/users/me")
.header("x-acs-dingtalk-access-token", accessToken)
.timeout(5000)
.execute()
.body();
log.info("DingTalk User Response: {}", userInfoResponse);
JSONObject userJson = JSON.parseObject(userInfoResponse);
String unionId = userJson.getString("unionId");
String openId = userJson.getString("openId");
String nick = userJson.getString("nick");
if (!StringUtils.hasText(openId) && !StringUtils.hasText(unionId)) {
log.error("Failed to get user info: {}", userInfoResponse);
model.addAttribute("authError", "钉钉登录验证失败: 无法获取用户信息");
return "form";
}
ThirdPartyUserReq build = ThirdPartyUserReq.builder().unionId(unionId).build();
List<ThirdPartyUserDTO> users = RpcExternalUtil.rpcApiResultProcessor(() -> thirdPartySyncApi.getUserInfos(build), "查询用户是否存在", build);
if (CollectionUtils.isEmpty(users)) {
model.addAttribute("authError", "用户未授权!");
return "form";
}
// 3. 登录成功
log.info("DingTalk Login Success: nick={}, unionId={}", nick, unionId);
session.setAttribute("isAuthenticated", true);
// 可以把用户信息也存进去
session.setAttribute("dingUser", userJson);
// 重定向回表单页
return "redirect:/web/process/form";
} catch (Exception e) {
log.error("DingTalk Callback Error", e);
model.addAttribute("authError", "登录过程中发生异常");
return "form";
}
}
/**
* 获取当前操作人信息 (姓名+手机号)
*/
private String getOperatorInfo(HttpSession session) {
if (session == null) {
return "[Unknown]";
}
Object dingUserObj = session.getAttribute("dingUser");
if (dingUserObj instanceof JSONObject) {
JSONObject user = (JSONObject) dingUserObj;
String nick = user.getString("nick");
String mobile = user.getString("mobile"); // DingTalk API 字段通常是 mobile
return String.format("[%s(%s)]", nick, mobile != null ? mobile : "NoMobile");
}
return "[Unknown/Admin]";
}
}

View File

@ -501,16 +501,16 @@ public class PrintAdminController implements PrintAdminApi {
return Optional.empty();
}
ListOrgNodeUserReq req = new ListOrgNodeUserReq();
if (StringUtils.hasText(assigner.getTenantId())) {
if (StringUtils.hasText(assigner.getTenantId()) && !Objects.equals(assigner.getTenantId(), "null")) {
req.setWorkspaceId(Long.valueOf(assigner.getTenantId()));
}
if (StringUtils.hasText(assigner.getOuId())) {
if (StringUtils.hasText(assigner.getOuId()) && !Objects.equals(assigner.getOuId(), "null")) {
req.setOrganizationalUnitId(Long.valueOf(assigner.getOuId()));
}
if (StringUtils.hasText(assigner.getNodeId())) {
if (StringUtils.hasText(assigner.getNodeId()) && !Objects.equals(assigner.getNodeId(), "null")) {
req.setAncestorNodeIds(Lists.newArrayList(Long.valueOf(assigner.getNodeId())));
}
if (StringUtils.hasText(assigner.getPersonId())) {
if (StringUtils.hasText(assigner.getPersonId()) && !Objects.equals(assigner.getPersonId(), "null")) {
req.setPersonIds(Lists.newArrayList(Long.valueOf(assigner.getPersonId())));
}
req.setNeeds(ListNodeUserReq.Needs.builder().job(true).unit(true).personProfile(true).build());

View File

@ -1,46 +0,0 @@
package cn.axzo.workflow.server.service;
import cn.axzo.workflow.server.common.util.RedisUtils;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.Objects;
import java.util.UUID;
/**
* form.html 页面授权码
*
* @author wangli
* @since 2025-11-19 10:51
*/
@Service
public class AuthCodeService {
private static final String AUTH_CODE_KEY_PREFIX = "we:auth_code";
// 授权码有效期1小时可自定义
private static final long EXPIRE_HOURS = 1;
/**
* 生成授权码仅管理员可调用
*/
public String generateAuthCode() {
// 生成随机授权码UUID简化
String authCode = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
RedisUtils.setCacheObject(AUTH_CODE_KEY_PREFIX, authCode, Duration.ofMinutes(1));
return authCode;
}
/**
* 验证授权码是否有效
*/
public boolean validateAuthCode(String authCode) {
if (authCode == null || authCode.isEmpty()) {
return false;
}
String key = RedisUtils.getCacheObject(AUTH_CODE_KEY_PREFIX);
if (key == null || !Objects.equals(key, authCode)) {
return false;
}
RedisUtils.deleteObject(AUTH_CODE_KEY_PREFIX);
return true;
}
}

View File

@ -1,5 +1,6 @@
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
@ -8,6 +9,8 @@
<script src="https://cdn.tailwindcss.com"></script>
<!-- 引入Font Awesome -->
<link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
<!-- 钉钉扫码登录 SDK (2025 Standard) -->
<script src="https://g.alicdn.com/dingding/h5-dingtalk-login/0.21.0/ddlogin.js"></script>
<!-- 配置Tailwind自定义颜色和字体 -->
<script>
@ -93,8 +96,12 @@
// 拼接基础路径和相对路径K8S环境
return `/${normalizedBase}/${normalizedRelative}`;
};
// 钉钉配置
const dingTalkAppKey = [[${dingTalkAppKey}]] || '';
</script>
</head>
<body class="bg-gray-50 font-inter min-h-screen flex flex-col">
<!-- 顶部导航 -->
<header class="bg-white shadow-sm sticky top-0 z-40">
@ -118,7 +125,8 @@
<div class="hidden md:block h-4 w-px bg-gray-300"></div>
<div class="text-gray-600 shrink-0 text-sm">
<i class="fa fa-user-circle-o mr-1"></i>管理员操作
<i class="fa fa-user-circle-o mr-1"></i>
<span th:text="${userNick != null} ? '欢迎,' + ${userNick} : '管理员操作'">管理员操作</span>
</div>
</div>
</div>
@ -133,108 +141,35 @@
<h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-dark mb-2"
th:text="${isAuthenticated} ? '流程操作' : '授权验证'"></h2>
<p class="text-secondary"
th:text="${isAuthenticated} ? '请根据需要选择相应操作并填写表单信息' : '请输入或获取授权码以继续操作'"></p>
th:text="${isAuthenticated} ? '请根据需要选择相应操作并填写表单信息' : '请输入扫码登陆'">
</p>
</div>
<!-- 授权验证区域 - 未认证时显示 -->
<div th:unless="${isAuthenticated}">
<!-- Tab导航 -->
<div class="border-b border-gray-200 mb-6">
<div class="flex -mb-px">
<button id="inputTab"
class="tab-active py-3 px-5 border-b-2 font-medium text-sm form-transition"
onclick="switchTab('input')">
<i class="fa fa-key mr-1"></i>输入授权码
</button>
<button id="getTab"
class="text-gray-500 hover:text-gray-700 py-3 px-5 border-b-2 border-transparent font-medium text-sm form-transition"
onclick="switchTab('get')">
<i class="fa fa-refresh mr-1"></i>获取授权码
</button>
</div>
<!-- 错误提示 Banner -->
<div class="mb-4 bg-red-50 border border-red-200 rounded-lg p-4 flex items-center"
th:if="${authError != null}">
<i class="fa fa-exclamation-circle text-danger text-lg mr-3"></i>
<div>
<h3 class="text-sm font-medium text-danger">验证失败</h3>
<div class="text-sm text-red-600 mt-1" th:text="${authError}"></div>
</div>
</div>
<!-- 钉钉扫码登录区域 -->
<div class="flex flex-col items-center justify-center py-8 space-y-4">
<div class="bg-blue-50 text-primary px-4 py-2 rounded-lg text-sm mb-4">
<i class="fa fa-dingding mr-2"></i>请使用钉钉扫码登录以验证身份
</div>
<!-- 输入授权码表单 -->
<form id="authForm" th:action="${apiBaseUrl} + @{/web/process/validate-auth}" method="post"
class="space-y-6">
<!-- 授权码输入 -->
<div class="form-group">
<label for="authCode" class="block text-sm font-medium text-gray-700 mb-1">
授权码 <span class="text-danger">*</span>
</label>
<div class="relative">
<span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
<i class="fa fa-key"></i>
</span>
<input type="password" id="authCode" name="authCode"
class="w-full pl-10 pr-4 py-2.5 rounded-lg border border-gray-300 form-input-focus form-transition"
placeholder="请输入授权码" required/>
<!-- 钉钉登录容器 -->
<div id="login_container" class="bg-white p-2 rounded-xl shadow-sm border border-gray-100">
</div>
<!-- 授权错误提示 -->
<p class="mt-1 text-xs text-danger hidden" id="authError" th:if="${authError}"
th:text="${authError}">
<i class="fa fa-exclamation-circle mr-1"></i>授权码无效或已过期,请重新输入
<p class="text-xs text-gray-400 mt-4">
<i class="fa fa-shield mr-1"></i>安全由钉钉提供支持
</p>
</div>
<!-- 提交按钮 -->
<div class="pt-4 flex justify-end">
<button type="submit"
class="px-6 py-2.5 bg-primary hover:bg-primary/90 text-white font-medium rounded-lg transition-all duration-300 transform hover:scale-[1.02] active:scale-[0.98] flex items-center">
<i class="fa fa-unlock-alt mr-2"></i>验证授权
</button>
</div>
</form>
<!-- 获取授权码表单 -->
<form id="getAuthForm" class="space-y-6 form-hidden">
<!-- 密码输入 -->
<div class="form-group">
<label for="authPassword" class="block text-sm font-medium text-gray-700 mb-1">
管理员密码 <span class="text-danger">*</span>
</label>
<div class="relative">
<span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
<i class="fa fa-lock"></i>
</span>
<input type="password" id="authPassword"
class="w-full pl-10 pr-4 py-2.5 rounded-lg border border-gray-300 form-input-focus form-transition"
placeholder="请输入管理员密码获取授权码" required/>
</div>
<!-- 获取授权码错误提示 -->
<p class="mt-1 text-xs text-danger hidden" id="getAuthError">
<i class="fa fa-exclamation-circle mr-1"></i>密码错误,无法获取授权码
</p>
</div>
<!-- 授权码展示区域 -->
<div id="authCodeDisplay"
class="form-group form-hidden bg-gray-50 p-4 rounded-lg border border-gray-200">
<p class="text-sm font-medium text-gray-700 mb-2">
<i class="fa fa-info-circle mr-1 text-primary"></i>获取到的授权码
</p>
<div class="flex items-center">
<input type="text" id="displayedAuthCode" readonly
class="flex-grow pl-4 pr-4 py-2 rounded-lg border border-gray-300 bg-white text-gray-800 cursor-default"
placeholder="授权码将显示在这里"/>
<button type="button" onclick="copyAuthCode()"
class="ml-2 px-3 py-2 text-sm bg-primary/10 text-primary rounded-lg hover:bg-primary/20 form-transition">
<i class="fa fa-copy mr-1"></i>复制
</button>
</div>
<p class="mt-2 text-xs text-gray-500">
<i class="fa fa-clock-o mr-1"></i>授权码有效期为30分钟请及时使用
</p>
</div>
<!-- 提交按钮 -->
<div class="pt-4 flex justify-end">
<button type="button" id="getAuthCodeBtn"
class="px-6 py-2.5 bg-primary hover:bg-primary/90 text-white font-medium rounded-lg transition-all duration-300 transform hover:scale-[1.02] active:scale-[0.98] flex items-center">
<i class="fa fa-get-pocket mr-2"></i>获取授权码
</button>
</div>
</form>
</div>
<!-- 流程操作表单 - 验证通过后显示 -->
@ -256,7 +191,8 @@
<option value="ABORT">中止实例</option>
<option value="RESUMER_DEADLINE_JOB">恢复节点</option>
</select>
<div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3 text-gray-500">
<div
class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3 text-gray-500">
<i class="fa fa-chevron-down text-xs"></i>
</div>
</div>
@ -292,8 +228,7 @@
</span>
<input type="text" id="personId" name="personId"
class="w-full pl-10 pr-4 py-2.5 rounded-lg border border-gray-300 form-input-focus form-transition"
placeholder="请输入自然人ID"
oninput="this.value = this.value.replace(/[^0-9]/g, '');"/>
placeholder="请输入自然人ID" oninput="this.value = this.value.replace(/[^0-9]/g, '');"/>
</div>
<p class="mt-1 text-xs text-gray-500 hidden" id="personIdError">
<i class="fa fa-exclamation-circle text-danger mr-1"></i>自然人ID为必填项
@ -358,20 +293,6 @@
</div>
</footer>
<!-- 成功提交提示框 -->
<div id="successToast"
class="fixed top-4 right-4 bg-success text-white px-4 py-3 rounded-lg shadow-lg transform translate-x-full transition-transform duration-500 flex items-center z-50">
<i class="fa fa-check-circle mr-2"></i>
<span>操作提交成功!</span>
</div>
<!-- 复制成功提示框 -->
<div id="copyToast"
class="fixed top-4 right-4 bg-success text-white px-4 py-3 rounded-lg shadow-lg transform translate-x-full transition-transform duration-500 flex items-center z-50">
<i class="fa fa-check-circle mr-2"></i>
<span>授权码已复制!</span>
</div>
<!-- 提交遮罩层 -->
<div id="submitMask"
class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 mask-fade opacity-0 pointer-events-none">
@ -392,14 +313,6 @@
const personId = document.getElementById('personId');
const comment = document.getElementById('comment');
const processForm = document.getElementById('processForm');
const authForm = document.getElementById('authForm');
const getAuthForm = document.getElementById('getAuthForm');
const getAuthCodeBtn = document.getElementById('getAuthCodeBtn');
const authPassword = document.getElementById('authPassword');
const authCodeDisplay = document.getElementById('authCodeDisplay');
const displayedAuthCode = document.getElementById('displayedAuthCode');
const successToast = document.getElementById('successToast');
const copyToast = document.getElementById('copyToast');
const submitMask = document.getElementById('submitMask');
const maskMessage = document.getElementById('maskMessage');
const operationMessage = document.getElementById('operationMessage');
@ -409,46 +322,54 @@
const personIdError = document.getElementById('personIdError');
const commentError = document.getElementById('commentError');
const authError = document.getElementById('authError');
const getAuthError = document.getElementById('getAuthError');
// 清除所有元素的计时器,防止冲突
const elementTimeouts = new Map();
// Tab切换功能
function switchTab(tabType) {
const inputTab = document.getElementById('inputTab');
const getTab = document.getElementById('getTab');
// 钉钉登录初始化
// 计算回调地址:当前 Origin + ContextPath + Callback Endpoint
const redirectUri = window.location.origin + getFullUrl('web/process/dingtalk-callback');
// 重置所有错误提示
if (authError) authError.classList.add('hidden');
if (getAuthError) getAuthError.classList.add('hidden');
if (tabType === 'input') {
// 切换到输入授权码
inputTab.classList.add('tab-active');
inputTab.classList.remove('text-gray-500', 'hover:text-gray-700', 'border-transparent');
getTab.classList.remove('tab-active');
getTab.classList.add('text-gray-500', 'hover:text-gray-700', 'border-transparent');
hideElement(getAuthForm);
setTimeout(() => {
showElement(authForm);
}, 300);
} else {
// 切换到获取授权码
getTab.classList.add('tab-active');
getTab.classList.remove('text-gray-500', 'hover:text-gray-700', 'border-transparent');
inputTab.classList.remove('tab-active');
inputTab.classList.add('text-gray-500', 'hover:text-gray-700', 'border-transparent');
hideElement(authForm);
setTimeout(() => {
showElement(getAuthForm);
// 隐藏授权码显示区域
hideElement(authCodeDisplay);
}, 300);
// 初始化钉钉扫码
// 文档参考: https://open.dingtalk.com/document/isvapp/tutorial-obtaining-user-information-by-scanning-qr-codes-on-websites
const initDingTalkLogin = () => {
if (typeof window.DTFrameLogin !== 'function') {
console.error('DingTalk SDK not loaded');
return;
}
}
window.DTFrameLogin(
{
id: 'login_container',
width: 300,
height: 300,
},
{
redirect_uri: encodeURIComponent(redirectUri),
client_id: dingTalkAppKey,
scope: 'openid', // 2025新版标准 Scope
response_type: 'code',
state: 'STATE_DANGER_OP', // 可选防重放参数
prompt: 'consent',
},
(success) => {
// 扫码成功后的前端回调
console.log('Login Success:', success);
const authCode = success.authCode;
if (authCode) {
// 重定向到后端回调接口,携带 authCode
// 注意:这里手动构建重定向,因为 DTFrameLogin 在某些模式下只返回 Code 不跳转
window.location.href = redirectUri + "?authCode=" + authCode;
}
},
(error) => {
console.error('Login Error:', error);
// 可以在 DOM 中显示错误
const container = document.getElementById('login_container');
container.innerHTML = `<div class="text-danger text-center"><i class="fa fa-exclamation-triangle"></i> 钉钉组件加载失败: ${error}</div>`;
}
);
};
// 显示元素的动画
function showElement(element) {
@ -483,19 +404,6 @@
submitMask.classList.add('opacity-0', 'pointer-events-none');
}
// 复制授权码
function copyAuthCode() {
const code = displayedAuthCode.value;
if (code) {
navigator.clipboard.writeText(code).then(() => {
copyToast.classList.remove('translate-x-full');
setTimeout(() => {
copyToast.classList.add('translate-x-full');
}, 2000);
});
}
}
// 根据选择的操作类型显示对应的表单字段
function updateFormFields() {
const selectedValue = operationType.value;
@ -570,62 +478,13 @@
return isValid;
}
// 显示成功提示
function showSuccessToast() {
successToast.classList.remove('translate-x-full');
setTimeout(() => {
successToast.classList.add('translate-x-full');
}, 3000);
}
// 获取授权码
async function getAuthCode() {
const password = authPassword.value.trim();
if (!password) {
getAuthError.innerHTML = '<i class="fa fa-exclamation-circle mr-1"></i>请输入管理员密码';
getAuthError.classList.remove('hidden');
return;
}
// 显示遮罩层
showMask('请稍候,正在获取授权码...');
getAuthError.classList.add('hidden');
try {
// 使用全局上下文路径变量拼接URL
const url = getFullUrl(`web/process/get-auth-code?password=${encodeURIComponent(password)}`);
// 保持POST请求方式参数通过URL查询参数传递
const response = await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json'
}
});
const result = await response.json();
if (response.ok && result.code === 200 && result.data) {
// 成功获取授权码
displayedAuthCode.value = result.data;
showElement(authCodeDisplay);
// 自动切换到输入标签页并填充授权码
// setTimeout(() => {
// switchTab('input');
// document.getElementById('authCode').value = result.data;
// }, 1000);
// 如果未认证,且存在 login_container则初始化
if (document.getElementById('login_container')) {
// 确保 SDK 加载完成后执行
if (document.readyState === 'complete') {
initDingTalkLogin();
} else {
// 显示错误信息
getAuthError.innerHTML = '<i class="fa fa-exclamation-circle mr-1"></i>' + (result.msg || '密码错误,无法获取授权码');
getAuthError.classList.remove('hidden');
}
} catch (error) {
console.error('获取授权码错误:', error);
getAuthError.innerHTML = '<i class="fa fa-exclamation-circle mr-1"></i>网络错误,请稍后重试';
getAuthError.classList.remove('hidden');
} finally {
// 隐藏遮罩层
hideMask();
window.addEventListener('load', initDingTalkLogin);
}
}
@ -697,23 +556,6 @@
});
}
// 授权码表单提交处理
if (authForm) {
authForm.addEventListener('submit', function (e) {
// 显示遮罩层
showMask('请稍候,正在验证授权码...');
// 清除之前的错误提示
if (authError) {
authError.classList.add('hidden');
}
// 允许表单正常提交
});
}
// 获取授权码按钮点击事件
if (getAuthCodeBtn) {
getAuthCodeBtn.addEventListener('click', getAuthCode);
}
// 初始化
if (operationType) {
@ -742,4 +584,5 @@
});
</script>
</body>
</html>