From 076fdfaffb95d2473cc28b85893a4345182c21cc Mon Sep 17 00:00:00 2001 From: chenhao <852066789@qq.com> Date: Mon, 30 Nov 2026 17:04:18 +0800 Subject: [PATCH] =?UTF-8?q?feat(hub):=20=E6=8E=A5=E5=85=A5=E7=BB=9F?= =?UTF-8?q?=E4=B8=80=E9=97=A8=E6=88=B7=20dsh-hub=20=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=E5=85=8D=E7=99=BB=E7=99=BB=E5=BD=95=E4=B8=8E=E4=BA=BA=E5=91=98?= =?UTF-8?q?=E7=9B=AE=E5=BD=95=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 framework 层 hub 客户端与登录服务(HubClient/HubLoginService 等),支持票据免登、口令代校验与强制改密 - 登录入口按绑定关系分流:已绑定账号口令交由门户校验,未绑定外部用户继续走本地口令,并补做验证码判定 - 门户要求先改密时返回业务码 603,前端在登录页内改密后直接进入系统 - SysUser 增加 hubUserId、hubSyncTime 字段,已绑定账号不再弹本系统改密与密码过期提醒 - 新增人员目录镜像与全量/增量同步契约(HubDirectory*、HubChangesResult),支持按姓名自动绑定与增量游标 - application-prod.yml 新增 hub 配置,含总开关、口令直登、目录同步、H5 第二应用密钥等逃生与灰度开关 - 前端新增 /sso/hub 免登落地页静态路由并加入白名单,store 与 getters 记录 hubUserId - 退出登录时已绑定账号按门户状态回跳统一门户首页,否则回本地首页 - 个人中心改密页对已绑定账号改用门户口令规则校验,规则读不到时降级不拦人 - 请求拦截器 allowWarning 场景兼容业务码 603 - 新增 api/system/hub 接口封装与测试模板页 test.html --- .../oms_vue/src/layout/components/Navbar.vue | 19 +- oms_web/oms_vue/src/permission.js | 3 +- oms_web/oms_vue/src/router/index.js | 6 + oms_web/oms_vue/src/store/getters.js | 1 + oms_web/oms_vue/src/store/modules/user.js | 9 +- oms_web/oms_vue/src/utils/request.js | 2 +- oms_web/oms_vue/src/views/login.vue | 244 ++++- .../views/system/user/profile/resetPwd.vue | 73 +- .../controller/system/SysIndexController.java | 7 +- .../controller/system/SysLoginController.java | 79 ++ .../src/main/resources/application-prod.yml | 52 +- .../src/main/resources/templates/test.html | 866 ++++++++++++++++++ .../common/core/domain/entity/SysUser.java | 6 + .../ruoyi/framework/hub/HubAccountLookup.java | 34 + .../ruoyi/framework/hub/HubAccountView.java | 78 ++ .../ruoyi/framework/hub/HubChangesResult.java | 117 +++ .../com/ruoyi/framework/hub/HubClient.java | 673 ++++++++++++++ .../framework/hub/HubDirectoryResult.java | 87 ++ .../ruoyi/framework/hub/HubDirectoryUser.java | 132 +++ .../com/ruoyi/framework/hub/HubException.java | 24 + .../framework/hub/HubLoginException.java | 18 + .../ruoyi/framework/hub/HubLoginResult.java | 138 +++ .../ruoyi/framework/hub/HubLoginService.java | 553 +++++++++++ .../hub/HubPasswordChangeResult.java | 113 +++ .../ruoyi/framework/hub/HubPortalToken.java | 35 + .../ruoyi/framework/hub/HubProperties.java | 372 ++++++++ .../ruoyi/framework/hub/HubTicketResult.java | 122 +++ .../framework/shiro/realm/UserRealm.java | 22 + .../quartz/task/HubDirectorySyncTask.java | 67 ++ .../hub/controller/HubH5SsoController.java | 152 +++ .../sip/hub/controller/HubSsoController.java | 272 ++++++ .../sip/hub/controller/HubUserController.java | 165 ++++ .../ruoyi/sip/hub/domain/HubSyncResult.java | 205 +++++ .../com/ruoyi/sip/hub/domain/SysHubUser.java | 123 +++ .../sip/hub/mapper/HubSyncStateMapper.java | 40 + .../sip/hub/mapper/SysHubUserMapper.java | 107 +++ .../hub/service/IHubDirectorySyncService.java | 29 + .../hub/service/IHubUserMirrorService.java | 116 +++ .../service/impl/HubAccountLookupImpl.java | 69 ++ .../impl/HubDirectorySyncServiceImpl.java | 289 ++++++ .../impl/HubUserMirrorServiceImpl.java | 666 ++++++++++++++ .../sip/ExternalApiCallLogItemMapper.xml | 56 ++ .../mapper/sip/ExternalApiCallLogMapper.xml | 105 +++ .../mapper/system/HubSyncStateMapper.xml | 17 + .../mapper/system/SysHubUserMapper.xml | 159 ++++ .../ruoyi/system/mapper/SysUserMapper.java | 44 + .../resources/mapper/system/SysUserMapper.xml | 57 +- 47 files changed, 6581 insertions(+), 42 deletions(-) create mode 100644 ruoyi-admin/src/main/resources/templates/test.html create mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubAccountLookup.java create mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubAccountView.java create mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubChangesResult.java create mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubClient.java create mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubDirectoryResult.java create mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubDirectoryUser.java create mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubException.java create mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubLoginException.java create mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubLoginResult.java create mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubLoginService.java create mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubPasswordChangeResult.java create mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubPortalToken.java create mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubProperties.java create mode 100644 ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubTicketResult.java create mode 100644 ruoyi-sip/src/main/java/com/ruoyi/quartz/task/HubDirectorySyncTask.java create mode 100644 ruoyi-sip/src/main/java/com/ruoyi/sip/hub/controller/HubH5SsoController.java create mode 100644 ruoyi-sip/src/main/java/com/ruoyi/sip/hub/controller/HubSsoController.java create mode 100644 ruoyi-sip/src/main/java/com/ruoyi/sip/hub/controller/HubUserController.java create mode 100644 ruoyi-sip/src/main/java/com/ruoyi/sip/hub/domain/HubSyncResult.java create mode 100644 ruoyi-sip/src/main/java/com/ruoyi/sip/hub/domain/SysHubUser.java create mode 100644 ruoyi-sip/src/main/java/com/ruoyi/sip/hub/mapper/HubSyncStateMapper.java create mode 100644 ruoyi-sip/src/main/java/com/ruoyi/sip/hub/mapper/SysHubUserMapper.java create mode 100644 ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/IHubDirectorySyncService.java create mode 100644 ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/IHubUserMirrorService.java create mode 100644 ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/impl/HubAccountLookupImpl.java create mode 100644 ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/impl/HubDirectorySyncServiceImpl.java create mode 100644 ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/impl/HubUserMirrorServiceImpl.java create mode 100644 ruoyi-sip/src/main/resources/mapper/sip/ExternalApiCallLogItemMapper.xml create mode 100644 ruoyi-sip/src/main/resources/mapper/sip/ExternalApiCallLogMapper.xml create mode 100644 ruoyi-sip/src/main/resources/mapper/system/HubSyncStateMapper.xml create mode 100644 ruoyi-sip/src/main/resources/mapper/system/SysHubUserMapper.xml diff --git a/oms_web/oms_vue/src/layout/components/Navbar.vue b/oms_web/oms_vue/src/layout/components/Navbar.vue index dc98934b..62f5d3e8 100644 --- a/oms_web/oms_vue/src/layout/components/Navbar.vue +++ b/oms_web/oms_vue/src/layout/components/Navbar.vue @@ -52,6 +52,7 @@ + + \ No newline at end of file diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/SysUser.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/SysUser.java index db55dc5c..c7938e1a 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/SysUser.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/SysUser.java @@ -58,6 +58,12 @@ public class SysUser extends BaseEntity /** 用户类型 */ private String userType; + /** dsh-hub 用户ID:非空即内部人员(走 hub 免登、禁用本地口令),为空即外部用户(走本地登录) */ + private Long hubUserId; + + /** 最近一次 hub 目录同步覆盖时间 */ + private Date hubSyncTime; + /** 用户邮箱 */ @Excel(name = "用户邮箱") @Getter(value = AccessLevel.NONE) diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubAccountLookup.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubAccountLookup.java new file mode 100644 index 00000000..ad2d4515 --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubAccountLookup.java @@ -0,0 +1,34 @@ +package com.ruoyi.framework.hub; + +/** + * hub 侧账号信息查询入口。 + * + *

实现放在 {@code ruoyi-sip} 的 hub 人员目录镜像({@code sys_hub_user})上: + * framework 只依赖 {@code ruoyi-system},看不到本项目的业务表,因此这里只声明契约、 + * 由业务侧注入实现。没有实现(模块未加载)时门户直登自动降级为「不可用」, + * 门户票据免登不受影响。

+ * + * @author codex + */ +public interface HubAccountLookup +{ + /** + * 按 hub 用户ID取门户账号信息。 + * + * @param hubUserId {@code sys_user.hub_user_id} + * @return 账号视图;镜像里没有这个人(比如从未跑过全量同步)时返回 null + */ + public HubAccountView findByHubUserId(Long hubUserId); + + /** + * 按统一门户账号(或邮箱)反查这个人,用于「登录页输入的是门户账号」的场景。 + * + *

hub 侧账号匹配是大小写不敏感并去首尾空格的({@code normalizeAccount}), + * 实现方要保持同样口径,否则会出现「hub 能登录、OMS 找不到人」。同时命中多人时 + * 返回 null——宁可不认,也不要把口令判给了另一个人。

+ * + * @param account 用户输入的统一门户账号或邮箱 + * @return 账号视图(含 {@code hubUserId});查不到或不唯一时返回 null + */ + public HubAccountView findByAccount(String account); +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubAccountView.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubAccountView.java new file mode 100644 index 00000000..a91617c7 --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubAccountView.java @@ -0,0 +1,78 @@ +package com.ruoyi.framework.hub; + +/** + * hub 侧账号信息(供 OMS 代理门户口令登录时使用)。 + * + *

内部人员在 OMS 登录页输入的是统一门户的账号,而 hub 校验口令只认它自己的 + * {@code account}(或邮箱),所以两个方向都需要这份来自人员目录镜像的视图: + * 用门户账号找到本地账号({@link #hubUserId}),再用门户账号去 hub 判口令。

+ * + * @author codex + */ +public class HubAccountView +{ + /** hub 用户ID(镜像主键),即 {@code sys_user.hub_user_id} */ + private Long hubUserId; + + /** hub 登录账号(会随企业微信改名,取当时最新值) */ + private String account; + + /** hub 邮箱,账号缺失或超限时用它登录 */ + private String email; + + /** hub 姓名,仅用于日志与提示,不参与校验 */ + private String displayName; + + /** 该 hub 人员是否已被管理员忽略(被忽略者不放行门户登录) */ + private boolean ignored; + + public Long getHubUserId() + { + return hubUserId; + } + + public void setHubUserId(Long hubUserId) + { + this.hubUserId = hubUserId; + } + + public String getAccount() + { + return account; + } + + public void setAccount(String account) + { + this.account = account; + } + + public String getEmail() + { + return email; + } + + public void setEmail(String email) + { + this.email = email; + } + + public String getDisplayName() + { + return displayName; + } + + public void setDisplayName(String displayName) + { + this.displayName = displayName; + } + + public boolean isIgnored() + { + return ignored; + } + + public void setIgnored(boolean ignored) + { + this.ignored = ignored; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubChangesResult.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubChangesResult.java new file mode 100644 index 00000000..21da9c73 --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubChangesResult.java @@ -0,0 +1,117 @@ +package com.ruoyi.framework.hub; + +import java.util.ArrayList; +import java.util.List; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +/** + * hub 增量变更流结果(GET /api/v1/auth/directory/changes)。 + * + *

游标语义:{@code cursor} 是本批最后一条的 seq,本批无变更时等于传入的 since; + * {@code hasMore=true} 时必须用同一个 cursor 继续拉取直到 false 才能提交游标; + * {@code since < oldestSeq} 说明中间流水已不可靠,必须回到全量。

+ * + *

变更写入是尽力而为,写失败只记日志不影响业务请求,因此增量流不能作为唯一可信来源, + * 必须配合每日全量校对。

+ * + * @author codex + */ +public class HubChangesResult +{ + /** 组织状态或父子关系变更:事件只带 id + status / parent_id,不带 path,必须重拉全量 */ + private boolean orgStructureChanged; + + private long cursor; + + private long oldestSeq; + + private long newestSeq; + + private boolean hasMore; + + private List changes = new ArrayList<>(); + + public static HubChangesResult from(JSONObject data) + { + HubChangesResult result = new HubChangesResult(); + if (data == null) + { + return result; + } + result.cursor = data.getLongValue("cursor"); + result.oldestSeq = data.getLongValue("oldest_seq"); + result.newestSeq = data.getLongValue("newest_seq"); + result.hasMore = data.getBooleanValue("has_more"); + JSONArray items = data.getJSONArray("changes"); + if (items != null) + { + List list = new ArrayList<>(items.size()); + for (int i = 0; i < items.size(); i++) + { + JSONObject item = items.getJSONObject(i); + if (item == null) + { + continue; + } + list.add(item); + if (isOrgStructureChange(item)) + { + result.orgStructureChanged = true; + } + } + result.changes = list; + } + return result; + } + + /** + * 组织移动 / 停用事件只描述被操作的节点,子树 path 与状态是隐式变化的, + * 靠增量 payload 推导父子关系会出错,一律标记为需要全量。 + */ + private static boolean isOrgStructureChange(JSONObject item) + { + if (!"organization".equals(item.getString("entity")) || !"upsert".equals(item.getString("op"))) + { + return false; + } + JSONObject payload = item.getJSONObject("data"); + if (payload == null) + { + return false; + } + // 改名与新组织带全量字段,只有移动与停用这类摘要事件需要全量重建 + return payload.containsKey("parent_id") || payload.containsKey("status"); + } + + public boolean isOrgStructureChanged() + { + return orgStructureChanged; + } + + public long getCursor() + { + return cursor; + } + + public long getOldestSeq() + { + return oldestSeq; + } + + public long getNewestSeq() + { + return newestSeq; + } + + public boolean isHasMore() + { + return hasMore; + } + + public List getChanges() + { + return changes; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubClient.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubClient.java new file mode 100644 index 00000000..181a3097 --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubClient.java @@ -0,0 +1,673 @@ +package com.ruoyi.framework.hub; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.ruoyi.common.utils.StringUtils; + +/** + * dsh-hub 开放接口客户端。 + * + *

覆盖下游需要的四件事:校验门户票据、导出全量目录、拉取增量变更、代理门户账号密码登录。 + * 四类调用都用同一把应用密钥({@code X-Integration-Key}),不额外配目录密钥,也都走 + * {@code /api/v1/**} 的统一信封({@code {code,msg,data}}),因此共用 {@link #exchange}。

+ * + *

刻意不调门户站点自用的 {@code /auth/login}:那个接口强制要求它自己的图形验证码, + * 会让用户在本系统那张码之外再多填一张。hub 为「下游自己管人机校验、只要 hub 判口令对错」 + * 专门开了口令代校验(对接指南 2.8),见 {@link #verifyPassword}。

+ * + *

硬性约束(来自 hub 对接指南 8.4):禁止对票据校验自动重试。hub 对票据是 + * 「先查询、立即删除」,超时后无法判断 hub 是否已消费,重试只会让第二次必然 + * {@code ticket_invalid},正确做法是丢弃当前票据让用户重新发起跳转。

+ * + *

本类不抛业务异常给调用方之外的一致性保证:网络与响应体异常统一转成 + * {@link HubException},由调用方决定是「拒绝登录」还是「本轮同步跳过」。

+ * + * @author codex + */ +@Component +public class HubClient +{ + private static final Logger log = LoggerFactory.getLogger(HubClient.class); + + private static final String PATH_TICKET_VERIFY = "/api/v1/auth/tickets/verify"; + + private static final String PATH_DIRECTORY = "/api/v1/auth/directory"; + + private static final String PATH_DIRECTORY_CHANGES = "/api/v1/auth/directory/changes"; + + /** 口令代校验(对接指南 2.8):服务端到服务端,走统一信封与集成密钥,不需要门户验证码 */ + private static final String PATH_PASSWORD_VERIFY = "/api/v1/auth/password-verify"; + + /** 口令要求(免登录可读,裸 JSON:{"requirements":{...}}),改密表单按它校验而不是本系统自定规则 */ + private static final String PATH_SECURITY_POLICY = "/auth/security-policy"; + + /** 服务端改密(对接指南 2.8.1):同一把集成密钥、统一信封,规则由 hub 当场判 */ + private static final String PATH_PASSWORD_CHANGE = "/api/v1/auth/password-change"; + + /** + * hub 口令入参上限(对接指南 2.8:与 2.3 同口径,来自口令安全参数的硬上界)。 + * 越界 hub 回 {@code 400 invalid_request} 而不是「口令错误」,所以本地先拦掉, + * 免得把用户输错的长口令报成「统一门户暂时不可用」。 + */ + private static final int HUB_PASSWORD_MAX_LENGTH = 20; + + private static final String HEADER_INTEGRATION_KEY = "X-Integration-Key"; + + /** hub 统一信封的成功码是字符串 "200",不是数字 200 */ + private static final String CODE_SUCCESS = "200"; + + private final HubProperties properties; + + private final RestTemplate restTemplate; + + public HubClient(HubProperties properties) + { + this.properties = properties; + SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); + factory.setConnectTimeout(properties.getConnectTimeoutMs()); + factory.setReadTimeout(properties.getReadTimeoutMs()); + this.restTemplate = new RestTemplate(factory); + } + + /** + * 校验门户一次性票据。失败(含 active=false)都返回结果对象,由调用方按 reason 分支。 + * + * @param ticket 票据原值 + * @return 校验结果,永不为 null + * @throws HubException 网络异常、信封错误、密钥无效 + */ + public HubTicketResult verifyTicket(String ticket) + { + return verifyTicket(ticket, properties.getIntegrationKey()); + } + + /** + * 用指定应用密钥校验门户票据(H5 在 hub 是独立应用,必须用它自己的密钥)。 + * + * @param ticket 票据原值 + * @param integrationKey 该应用在 hub 的密钥明文 + * @return 校验结果,永不为 null + * @throws HubException 网络异常、信封错误、密钥无效 + */ + public HubTicketResult verifyTicket(String ticket, String integrationKey) + { + JSONObject body = new JSONObject(); + // 使用应用密钥时无需 app_code;传了则必须与密钥同属一个应用,因此这里不传 + body.put("ticket", ticket); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set(HEADER_INTEGRATION_KEY, integrationKey); + JSONObject data = exchange(PATH_TICKET_VERIFY, HttpMethod.POST, new HttpEntity<>(body, headers), "票据校验"); + + HubTicketResult result = new HubTicketResult(); + if (data == null) + { + result.setActive(false); + result.setReason("ticket_invalid"); + return result; + } + result.setActive(data.getBooleanValue("active")); + result.setReason(data.getString("reason")); + result.setSub(data.getString("sub")); + result.setAccount(data.getString("account")); + result.setDisplayName(data.getString("display_name")); + result.setEmail(data.getString("email")); + result.setAppCode(data.getString("app_code")); + return result; + } + + /** + * 全量导出目录。镜像场景必须带 include_disabled 与 include_disabled_users, + * 否则父组织停用后整棵子树(含状态仍为启用的人)会从默认导出里消失,被误判为「人已不在」。 + * + * @param memberLimit 花名册上限,hub 取值 1-5000 + * @throws HubException 调用失败或响应无法解析 + */ + public HubDirectoryResult fetchDirectory(int memberLimit) + { + int limit = memberLimit <= 0 ? properties.getDirectory().getMemberLimit() : memberLimit; + String url = PATH_DIRECTORY + "?include_disabled=true&include_disabled_users=true&member_limit=" + limit; + JSONObject data = exchange(url, HttpMethod.GET, new HttpEntity<>(keyHeaders()), "目录导出"); + + HubDirectoryResult result = new HubDirectoryResult(); + if (data == null) + { + return result; + } + result.setTotalUsers(data.getLongValue("total_users")); + result.setReturnedUsers(data.getLongValue("returned_users")); + result.setMemberLimit(data.getIntValue("member_limit")); + result.setTruncated(data.getBooleanValue("truncated")); + result.setPermissionVersion(data.getLongValue("permission_version")); + result.setUsers(parseUsers(data.getJSONArray("users"))); + return result; + } + + /** + * 拉取增量变更。 + * + * @param since 游标(排他语义),负数按 0 + * @param limit 单批条数,hub 上限 500 + */ + public HubChangesResult fetchChanges(long since, int limit) + { + int size = limit <= 0 ? properties.getDirectory().getChangeLimit() : Math.min(limit, 500); + String url = PATH_DIRECTORY_CHANGES + "?since=" + Math.max(since, 0L) + "&limit=" + size; + JSONObject data = exchange(url, HttpMethod.GET, new HttpEntity<>(keyHeaders()), "增量变更"); + return HubChangesResult.from(data); + } + + /** + * 代校验统一门户口令(对接指南 2.8 的 {@code POST /api/v1/auth/password-verify})。 + * + *

这条链路是 hub 特意为「下游自己管人机校验、只把口令判对判错交给 hub」开的: + * 用同一把 {@code X-Integration-Key},走统一信封,不要求门户图形验证码, + * 也不签发任何 hub 令牌。判定与 hub 登录页同一套(账号是否启用、密码通道、 + * 连续失败锁定、bcrypt 比对),所以在 OMS 这边输错 5 次同样会把这个人的门户账号锁 15 分钟。

+ * + *

OMS 的 {@code login_name} 存的是手机号,与 hub 的 {@code account} 不是一回事, + * 因此调用方必须传镜像表里的 hub 账号;账号缺失时退回邮箱(hub 的 account 字段 + * 同时接受邮箱,见 {@code MySQLUserRepository#FindByAccount})。邮箱也长到超过 + * account 的 190 位上限时不猜,直接判不可用。

+ * + *

口令不记日志;hub 侧审计也只记账号。

+ * + * @param hubAccount hub 登录账号,可为空 + * @param hubEmail hub 邮箱,账号为空时的兜底 + * @param password 用户输入的门户口令原值(hub 不做 trim) + * @return 归一化结果;只有 hub 不可达才归为 {@link HubLoginResult#STATUS_UNAVAILABLE} + */ + public HubLoginResult verifyPassword(String hubAccount, String hubEmail, String password) + { + String account = hubAccount == null ? "" : hubAccount.trim(); + if (account.isEmpty()) + { + account = hubEmail == null ? "" : hubEmail.trim(); + } + if (account.isEmpty() || account.length() > 190) + { + return HubLoginResult.of(HubLoginResult.STATUS_UNAVAILABLE, + "统一门户账号不可用,请联系管理员核对该人员的门户账号"); + } + if (password == null || password.isEmpty() || password.length() > HUB_PASSWORD_MAX_LENGTH) + { + // hub 对越界口令回 400 invalid_request(不是「口令错」),本地先给出可读提示 + return HubLoginResult.of(HubLoginResult.STATUS_INVALID_CREDENTIALS, + password == null || password.isEmpty() ? "请输入统一门户密码" : "密码长度不正确,请重新输入"); + } + + JSONObject body = new JSONObject(); + body.put("account", account); + // 与票据校验同一口径:密钥本身已标识应用,app_code 只在用 bootstrap 目录密钥时才需要, + // 这里不传,免得把「app_code 与密钥不属于同一应用」变成一个新的失败面 + body.put("password", password); + + JSONObject data; + try + { + data = exchange(PATH_PASSWORD_VERIFY, HttpMethod.POST, new HttpEntity<>(body, keyHeaders()), "口令校验"); + } + catch (HubException e) + { + // 「hub 不可达」与「口令错」必须分开:前者可能允许回退本地口令,后者绝不能回退 + return HubLoginResult.of(HubLoginResult.STATUS_UNAVAILABLE, e.getMessage()); + } + if (data == null) + { + return HubLoginResult.of(HubLoginResult.STATUS_UNAVAILABLE, "统一门户未返回口令校验结果,请稍后重试"); + } + return toVerifyResult(data); + } + + /** + * 把口令代校验的 {@code data} 归一成 {@link HubLoginResult}。 + * + *

hub 的口径与票据校验一致:口令层面的不通过也是 HTTP 200 + {@code active:false} + + * {@code reason}(三种 reason 见对接指南 2.8 的表),只有调用方自己的凭据有问题才是 + * 401/403,那种情况已被 {@code exchange} 转成 HubException 归为不可达。

+ */ + private HubLoginResult toVerifyResult(JSONObject data) + { + HubLoginResult result = new HubLoginResult(); + if (!data.getBooleanValue("active")) + { + String reason = data.getString("reason"); + if ("account_locked".equals(reason)) + { + result.setStatus(HubLoginResult.STATUS_ACCOUNT_LOCKED); + result.setMessage("统一门户账号已锁定,请稍后再试"); + } + else if ("password_login_disabled".equals(reason)) + { + result.setStatus(HubLoginResult.STATUS_PASSWORD_LOGIN_DISABLED); + result.setMessage("该账号在统一门户未开启密码登录,请改从门户卡片免登进入或联系管理员开通"); + } + else + { + // invalid_credentials:账号不存在 / 已停用 / 口令不对,hub 故意不区分,防枚举 + if (reason != null && !"invalid_credentials".equals(reason)) + { + log.warn("hub 口令校验返回未预期 reason={}", reason); + } + result.setStatus(HubLoginResult.STATUS_INVALID_CREDENTIALS); + result.setMessage("账号或密码错误"); + } + return result; + } + // 口令对了再看强制改密:hub 的改密闸门只管 hub 自己签发的会话,管不到 OMS 会话, + // 所以这里必须由 OMS 自己把人先导到 hub 的改密页(对接指南 2.8 明确要求)。 + if (data.getBooleanValue("password_change_required")) + { + result.setStatus(HubLoginResult.STATUS_PASSWORD_CHANGE_REQUIRED); + result.setPasswordChangeUrl(absoluteUrl(data.getString("password_change_url"))); + result.setMessage("统一门户要求先修改密码,请在弹窗中设置新密码"); + return result; + } + result.setStatus(HubLoginResult.STATUS_SUCCESS); + String sub = data.getString("sub"); + if (sub != null && !sub.trim().isEmpty()) + { + try + { + result.setHubUserId(Long.valueOf(sub.trim())); + } + catch (NumberFormatException e) + { + log.error("hub 口令校验返回的 sub 不是数字, sub={}", sub); + } + } + result.setAccount(data.getString("account")); + result.setDisplayName(data.getString("display_name")); + result.setEmail(data.getString("email")); + return result; + } + + /** + * 读统一门户当前生效的口令要求(长度、字符类别、是否禁常见口令)。 + * + *

改密表单的校验规则属于 hub,本系统不要抄一份写死的规则(对接指南 2.7、2.8 + * 都强调了这一点),因此直接把它读回来给前端用。这个接口免登录,返回裸 JSON。

+ * + * @return requirements 节点;读不到时返回空对象(前端按「不额外限制」降级,不阻断改密) + */ + public JSONObject fetchPasswordRequirements() + { + RawResponse response = rawCall(PATH_SECURITY_POLICY, HttpMethod.GET, null, "口令要求"); + if (response.status != 200) + { + log.warn("读取统一门户口令要求失败, http={}", response.status); + return new JSONObject(); + } + JSONObject requirements = response.body.getJSONObject("requirements"); + return requirements == null ? new JSONObject() : requirements; + } + + /** + * 服务端改密(对接指南 2.8.1:{@code POST /api/v1/auth/password-change})。 + * + *

与口令代校验同一把集成密钥、同一个统一信封、同一条判定链:账号是否启用、密码通道是否 + * 开通、失败锁定、当前口令比对全部由 hub 判,本系统不复刻口令规则。当前口令必填——hub 用它 + * 证明「改的是谁的口令」,应用密钥只证明「谁在调」。

+ * + *

口令不合规时 hub 会把当时生效的 requirements 一起回出来,前端按它重新渲染表单, + * 不要在本系统写死长度与字符类别(对接指南 2.7、11)。

+ * + * @param hubAccount hub 登录账号,可为空 + * @param hubEmail hub 邮箱,账号为空时的兜底 + * @param currentPassword 当前口令原值(hub 不做 trim) + * @param newPassword 新口令原值 + * @return 归一化结果,永不返回 null + */ + public HubPasswordChangeResult changePassword(String hubAccount, String hubEmail, String currentPassword, + String newPassword) + { + String account = StringUtils.trimToEmpty(hubAccount); + if (account.isEmpty()) + { + account = StringUtils.trimToEmpty(hubEmail); + } + if (account.isEmpty() || account.length() > 190) + { + return HubPasswordChangeResult.unavailable("统一门户账号不可用,请联系管理员核对该人员的门户账号"); + } + if (currentPassword == null || currentPassword.isEmpty() || currentPassword.length() > HUB_PASSWORD_MAX_LENGTH) + { + // 越界 hub 回 400 invalid_request 而不是「口令错」,本地先给可读提示 + return HubPasswordChangeResult.rejected(HubPasswordChangeResult.REASON_INVALID_CREDENTIALS, null, + currentPassword == null || currentPassword.isEmpty() ? "请输入当前密码" : "当前密码长度不正确,请重新输入"); + } + if (newPassword == null || newPassword.isEmpty() || newPassword.length() > HUB_PASSWORD_MAX_LENGTH) + { + return HubPasswordChangeResult.rejected(HubPasswordChangeResult.REASON_WEAK, "password_length", + newPassword == null || newPassword.isEmpty() ? "请输入新密码" : "新密码长度不正确,请重新输入"); + } + + JSONObject body = new JSONObject(); + body.put("account", account); + body.put("current_password", currentPassword); + body.put("new_password", newPassword); + // app_code 的口径与口令代校验一致:密钥本身已标识应用,这里不传 + + JSONObject data; + try + { + data = exchange(PATH_PASSWORD_CHANGE, HttpMethod.POST, new HttpEntity<>(body, keyHeaders()), "口令修改"); + } + catch (HubException e) + { + // 「门户不可达」与「口令不对」必须分开:前者不该让人反复改密码 + return HubPasswordChangeResult.unavailable(e.getMessage()); + } + if (data == null) + { + return HubPasswordChangeResult.unavailable("统一门户未返回口令修改结果,请稍后重试"); + } + return toChangeResult(data); + } + + /** + * 把改密响应的 {@code data} 归一成 {@link HubPasswordChangeResult}。 + * + *

hub 的口径与代校验一致:口令层面的不通过也是 HTTP 200 + {@code changed:false} + + * {@code reason}(五种取值见对接指南 2.8.1 的表),调用方凭据有问题才是 401/403, + * 那种情况已被 {@code exchange} 转成 HubException 归为不可达。

+ */ + private HubPasswordChangeResult toChangeResult(JSONObject data) + { + if (data.getBooleanValue("changed")) + { + HubPasswordChangeResult ok = HubPasswordChangeResult.success(); + String sub = data.getString("sub"); + if (StringUtils.isNotEmpty(sub)) + { + try + { + ok.setHubUserId(Long.valueOf(sub.trim())); + } + catch (NumberFormatException e) + { + log.error("hub 口令修改返回的 sub 不是数字, sub={}", sub); + } + } + return ok; + } + String reason = StringUtils.trimToEmpty(data.getString("reason")); + String passwordCode = data.getString("password_code"); + if (HubPasswordChangeResult.REASON_ACCOUNT_LOCKED.equals(reason)) + { + return HubPasswordChangeResult.rejected(reason, passwordCode, "统一门户账号已锁定,请稍后再试"); + } + if (HubPasswordChangeResult.REASON_PASSWORD_DISABLED.equals(reason)) + { + return HubPasswordChangeResult.rejected(reason, passwordCode, "该账号在统一门户未开启密码登录,请联系管理员开通"); + } + if (HubPasswordChangeResult.REASON_UNCHANGED.equals(reason)) + { + // 与「长度不够」分开说:否则正在重复输旧密码的人会一直去改长度(对接指南 2.4) + return HubPasswordChangeResult.rejected(reason, passwordCode, "新密码不能与当前密码相同,请换一个"); + } + if (HubPasswordChangeResult.REASON_WEAK.equals(reason)) + { + // 规则本身让前端按需再读一次 /passwordPolicy,这里只把「哪一条没过」说清楚 + return HubPasswordChangeResult.rejected(reason, passwordCode, weakPasswordMessage(passwordCode)); + } + if (!reason.isEmpty() && !HubPasswordChangeResult.REASON_INVALID_CREDENTIALS.equals(reason)) + { + log.warn("hub 口令修改返回未预期 reason={}", reason); + } + // invalid_credentials:当前密码不对 / 账号不存在 / 已停用 / 尚未设密码,hub 故意同一句(防枚举) + return HubPasswordChangeResult.rejected(HubPasswordChangeResult.REASON_INVALID_CREDENTIALS, passwordCode, + "当前密码不正确"); + } + + /** 按 hub 的 password_code 说清是哪一条没过,而不是笼统一句「密码太弱」 */ + private String weakPasswordMessage(String passwordCode) + { + if ("password_classes".equals(passwordCode)) + { + return "新密码包含的字符类别不够,请按页面提示的规则设置"; + } + if ("password_common".equals(passwordCode)) + { + return "新密码过于常见,请换一个更难猜的"; + } + if ("password_contains_account".equals(passwordCode)) + { + return "新密码不能包含统一门户账号"; + } + return "新密码不符合统一门户的密码规则"; + } + + /** 门户返回的改密地址是相对路径(对接指南 2.3.2),拼上 hub 基地址才能跳转 */ + private String absoluteUrl(String path) + { + if (path == null || path.trim().isEmpty()) + { + return null; + } + String value = path.trim(); + if (value.startsWith("http://") || value.startsWith("https://")) + { + return value; + } + return properties.getNormalizedBaseUrl() + (value.startsWith("/") ? value : "/" + value); + } + + /** + * 调用门户站点的裸接口:不剥信封,非 2xx 也原样带回状态码与已解析响应体。 + * + *

门户的 {@code /auth/**} 是裸 JSON(如免登录的口令要求),不带统一信封, + * 所以这里不抛业务异常,由调用方按状态码自行判定。

+ */ + private RawResponse rawCall(String path, HttpMethod method, HttpEntity entity, String action) + { + String url = properties.getNormalizedBaseUrl() + path; + ResponseEntity response; + try + { + response = restTemplate.exchange(url, method, entity, String.class); + } + catch (HttpStatusCodeException e) + { + return new RawResponse(e.getRawStatusCode(), parseJsonQuietly(e.getResponseBodyAsString())); + } + catch (RestClientException e) + { + log.error("hub {} 调用异常(超时或地址不可达): {}", action, e.getMessage()); + throw new HubException("统一门户暂时不可用,请稍后重试", e); + } + return new RawResponse(response.getStatusCodeValue(), parseJsonQuietly(response.getBody())); + } + + private JSONObject parseJsonQuietly(String raw) + { + if (raw == null || raw.trim().isEmpty()) + { + return new JSONObject(); + } + try + { + JSONObject json = JSON.parseObject(raw); + return json == null ? new JSONObject() : json; + } + catch (Exception e) + { + // 门户异常时可能回 HTML 页面,解析不出来按空对象处理 + return new JSONObject(); + } + } + + private List parseUsers(JSONArray array) + { + if (array == null || array.isEmpty()) + { + return Collections.emptyList(); + } + List users = new ArrayList<>(array.size()); + for (int i = 0; i < array.size(); i++) + { + JSONObject item = array.getJSONObject(i); + if (item == null || item.getLong("user_id") == null) + { + continue; + } + HubDirectoryUser user = new HubDirectoryUser(); + user.setUserId(item.getLong("user_id")); + user.setAccount(item.getString("account")); + user.setWecomUserId(item.getString("wecom_userid")); + user.setDisplayName(item.getString("display_name")); + user.setEmail(item.getString("email")); + // 全量目录不含 phone,只有 source=wecom 的增量事件会带;取不到就留空 + user.setPhone(item.getString("phone")); + user.setOrganizationId(item.getLong("organization_id")); + user.setStatus(item.getInteger("status")); + users.add(user); + } + return users; + } + + /** + * 统一发起调用并剥掉 hub 信封。 + * + *

日志只记路径、HTTP 状态与 hub 业务码,不记票据与密钥,也不记完整响应体 + * (票据不能进日志,响应体里含个人信息)。

+ */ + private JSONObject exchange(String path, HttpMethod method, HttpEntity entity, String action) + { + String url = properties.getNormalizedBaseUrl() + path; + ResponseEntity response; + try + { + response = restTemplate.exchange(url, method, entity, String.class); + } + catch (HttpStatusCodeException e) + { + // 401/403/404 属密钥与应用配置问题,把 hub 的业务码带出来便于定位,不带 body 原文 + String code = parseErrorCode(e.getResponseBodyAsString()); + log.error("hub {} 调用失败, status={}, hubCode={}", action, e.getRawStatusCode(), code); + throw new HubException("统一门户" + action + "失败(" + describeHttp(e.getRawStatusCode(), code) + ")", e); + } + catch (RestClientException e) + { + log.error("hub {} 调用异常, url 解析失败或超时: {}", action, e.getMessage()); + throw new HubException("统一门户" + action + "暂不可用,请稍后重试", e); + } + + JSONObject envelope = parseEnvelope(response.getBody(), action); + String code = envelope.getString("code"); + if (!CODE_SUCCESS.equals(code)) + { + log.error("hub {} 返回业务失败, http={}, hubCode={}", action, response.getStatusCodeValue(), code); + throw new HubException("统一门户" + action + "失败(" + code + ")"); + } + return envelope.getJSONObject("data"); + } + + private JSONObject parseEnvelope(String raw, String action) + { + if (raw == null || raw.trim().isEmpty()) + { + throw new HubException("统一门户" + action + "返回空响应"); + } + try + { + JSONObject envelope = JSON.parseObject(raw); + if (envelope == null || !envelope.containsKey("code")) + { + throw new HubException("统一门户" + action + "响应格式异常"); + } + return envelope; + } + catch (HubException e) + { + throw e; + } + catch (Exception e) + { + throw new HubException("统一门户" + action + "响应格式异常", e); + } + } + + private String parseErrorCode(String rawBody) + { + if (rawBody == null || rawBody.trim().isEmpty()) + { + return ""; + } + try + { + JSONObject json = JSON.parseObject(rawBody); + String code = json == null ? null : json.getString("code"); + return code == null ? "" : code; + } + catch (Exception e) + { + return ""; + } + } + + /** + * 把 hub 的密钥类错误翻译成运维能直接行动的话(对接指南 8.5)。 + */ + private String describeHttp(int status, String hubCode) + { + if (status == 401) + { + return "401,对接密钥缺失或无效,请检查 hub.integration-key 与 hub 侧应用是否被停用"; + } + if (status == 403) + { + return "403,密钥与应用编码不对应,请检查 hub.app-code"; + } + if (status == 404) + { + return "404,hub 侧未找到该应用"; + } + if (status == 400) + { + return "400,请求参数无效"; + } + return String.valueOf(status) + (hubCode == null || hubCode.isEmpty() ? "" : "/" + hubCode); + } + + private HttpHeaders keyHeaders() + { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set(HEADER_INTEGRATION_KEY, properties.getIntegrationKey()); + return headers; + } + + /** 门户裸接口的 HTTP 状态码与已解析响应体 */ + private static final class RawResponse + { + private final int status; + + private final JSONObject body; + + private RawResponse(int status, JSONObject body) + { + this.status = status; + this.body = body; + } + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubDirectoryResult.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubDirectoryResult.java new file mode 100644 index 00000000..18c18fae --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubDirectoryResult.java @@ -0,0 +1,87 @@ +package com.ruoyi.framework.hub; + +import java.util.ArrayList; +import java.util.List; + +/** + * hub 全量目录导出结果(只取同步需要的用户维度)。 + * + *

{@link #isTruncated()} 为 true 说明被 member_limit 截断,必须提高上限重拉, + * 不能把这一份当完整目录用,否则会把没返回的人误判成「hub 已没有这个人」。

+ * + * @author codex + */ +public class HubDirectoryResult +{ + private List users = new ArrayList<>(); + + private long totalUsers; + + private long returnedUsers; + + private int memberLimit; + + private boolean truncated; + + private long permissionVersion; + + public List getUsers() + { + return users; + } + + public void setUsers(List users) + { + this.users = users == null ? new ArrayList<>() : users; + } + + public long getTotalUsers() + { + return totalUsers; + } + + public void setTotalUsers(long totalUsers) + { + this.totalUsers = totalUsers; + } + + public long getReturnedUsers() + { + return returnedUsers; + } + + public void setReturnedUsers(long returnedUsers) + { + this.returnedUsers = returnedUsers; + } + + public int getMemberLimit() + { + return memberLimit; + } + + public void setMemberLimit(int memberLimit) + { + this.memberLimit = memberLimit; + } + + public boolean isTruncated() + { + return truncated; + } + + public void setTruncated(boolean truncated) + { + this.truncated = truncated; + } + + public long getPermissionVersion() + { + return permissionVersion; + } + + public void setPermissionVersion(long permissionVersion) + { + this.permissionVersion = permissionVersion; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubDirectoryUser.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubDirectoryUser.java new file mode 100644 index 00000000..35ffef74 --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubDirectoryUser.java @@ -0,0 +1,132 @@ +package com.ruoyi.framework.hub; + +/** + * hub 全量目录成员项(GET /api/v1/auth/directory 的 users 元素)。 + * + *

注意 hub 侧的已知限制:全量目录的成员项不含 phone,只有 + * {@code source=wecom} 的增量事件才携带手机号,因此 {@link #getPhone()} 在全量场景恒为空, + * 手机号为空一律跳过匹配(方案已定口径)。

+ * + * @author codex + */ +public class HubDirectoryUser +{ + /** hub 用户 ID,等同票据校验的 sub(数值形式) */ + private Long userId; + + /** hub 登录账号,会随企业微信「Hub账号」属性改名,只用于首次匹配 */ + private String account; + + /** 企业微信 userid,非唯一、可改绑,只用于对账 */ + private String wecomUserId; + + private String displayName; + + private String email; + + /** 增量事件才会带;全量目录恒空 */ + private String phone; + + private Long organizationId; + + /** hub 状态:0 停用 1 启用 2 待审核 3 已驳回 */ + private Integer status; + + public Long getUserId() + { + return userId; + } + + public void setUserId(Long userId) + { + this.userId = userId; + } + + public String getAccount() + { + return account; + } + + public void setAccount(String account) + { + this.account = account; + } + + public String getWecomUserId() + { + return wecomUserId; + } + + public void setWecomUserId(String wecomUserId) + { + this.wecomUserId = wecomUserId; + } + + public String getDisplayName() + { + return displayName; + } + + public void setDisplayName(String displayName) + { + this.displayName = displayName; + } + + public String getEmail() + { + return email; + } + + public void setEmail(String email) + { + this.email = email; + } + + public String getPhone() + { + return phone; + } + + public void setPhone(String phone) + { + this.phone = phone; + } + + public Long getOrganizationId() + { + return organizationId; + } + + public void setOrganizationId(Long organizationId) + { + this.organizationId = organizationId; + } + + public Integer getStatus() + { + return status; + } + + public void setStatus(Integer status) + { + this.status = status; + } + + /** hub 侧是否处于可用状态 */ + public boolean isEnabled() + { + return status != null && status == 1; + } + + /** + * hub 侧是否「明确处于停用」。 + * + *

必须与 {@link #isEnabled()} 分开:增量流的摘要事件(如调整组织只带 + * {@code {id, organization_id}})不带 status,此时 status 为 null, + * 若按「非启用即停用」处理,一次调整组织就会把在职人员停用。

+ */ + public boolean isKnownDisabled() + { + return status != null && status != 1; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubException.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubException.java new file mode 100644 index 00000000..ce937144 --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubException.java @@ -0,0 +1,24 @@ +package com.ruoyi.framework.hub; + +/** + * hub 调用异常:网络不可达、信封异常、密钥无效等「无法得出结论」的情况。 + * + *

与「hub 明确回答这个人不行」(票据 active=false)区分开:后者是正常业务结果, + * 走 {@link HubTicketResult#getReason()},不走异常。

+ * + * @author codex + */ +public class HubException extends RuntimeException +{ + private static final long serialVersionUID = 1L; + + public HubException(String message) + { + super(message); + } + + public HubException(String message, Throwable cause) + { + super(message, cause); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubLoginException.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubLoginException.java new file mode 100644 index 00000000..a586c2e3 --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubLoginException.java @@ -0,0 +1,18 @@ +package com.ruoyi.framework.hub; + +/** + * hub 免登失败:票据无效、账号未绑定、账号已停用等「本次登录不成立」的情况。 + * + *

调用方一律把用户送回统一门户,不得回落到本地口令登录。

+ * + * @author codex + */ +public class HubLoginException extends RuntimeException +{ + private static final long serialVersionUID = 1L; + + public HubLoginException(String message) + { + super(message); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubLoginResult.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubLoginResult.java new file mode 100644 index 00000000..37551e4e --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubLoginResult.java @@ -0,0 +1,138 @@ +package com.ruoyi.framework.hub; + +/** + * hub 账号密码登录结果(POST /auth/login,裸 JSON,不走统一信封)。 + * + *

本系统不保存内部人员的口令,OMS 登录页对已绑定账号只做「代理校验」:把用户在 + * OMS 输入的门户口令转交 hub 校验,hub 说了算。因此这里必须把 hub 的每一种失败 + * 都区分开,让上层能给出可行动的提示,不能统统压成「账号或密码错误」。

+ * + *

hub 侧状态码语义(对接指南 2.3、2.3.1、9.3): + * 200 成功(含「口令正确但需强制改密」);400 验证码错/参数无效; + * 401 账号或密码错误;403 账号锁定 / 该账号已关闭密码登录。

+ * + * @author codex + */ +public class HubLoginResult +{ + /** hub 判定成功,可直接建立本地会话 */ + public static final String STATUS_SUCCESS = "success"; + + /** 门户口令正确但 hub 要求先改密,本次不建会话 */ + public static final String STATUS_PASSWORD_CHANGE_REQUIRED = "password_change_required"; + + /** 账号或密码错误 */ + public static final String STATUS_INVALID_CREDENTIALS = "invalid_credentials"; + + /** 门户账号被锁定(连续失败达阈值) */ + public static final String STATUS_ACCOUNT_LOCKED = "account_locked"; + + /** 门户未开启该账号的密码登录通道 */ + public static final String STATUS_PASSWORD_LOGIN_DISABLED = "password_login_disabled"; + + /** 门户不可用(网络/5xx/响应异常),由配置决定能否回退本地口令 */ + public static final String STATUS_UNAVAILABLE = "unavailable"; + + /** 该账号不走门户(未绑定 / 统一登录未启用 / 已被管理员忽略),继续用本系统口令登录 */ + public static final String STATUS_LOCAL_LOGIN = "local_login"; + + private String status; + + /** hub 用户ID(票据 sub 的数值形式),仅成功时有值 */ + private Long hubUserId; + + private String account; + + private String displayName; + + private String email; + + /** 强制改密页绝对地址(hub base + 门户返回的相对路径) */ + private String passwordChangeUrl; + + /** 可直接展示给用户的原因,不含敏感信息 */ + private String message; + + public static HubLoginResult of(String status, String message) + { + HubLoginResult result = new HubLoginResult(); + result.setStatus(status); + result.setMessage(message); + return result; + } + + public boolean isSuccess() + { + return STATUS_SUCCESS.equals(status); + } + + public String getStatus() + { + return status; + } + + public void setStatus(String status) + { + this.status = status; + } + + public Long getHubUserId() + { + return hubUserId; + } + + public void setHubUserId(Long hubUserId) + { + this.hubUserId = hubUserId; + } + + public String getAccount() + { + return account; + } + + public void setAccount(String account) + { + this.account = account; + } + + public String getDisplayName() + { + return displayName; + } + + public void setDisplayName(String displayName) + { + this.displayName = displayName; + } + + public String getEmail() + { + return email; + } + + public void setEmail(String email) + { + this.email = email; + } + + public String getPasswordChangeUrl() + { + return passwordChangeUrl; + } + + public void setPasswordChangeUrl(String passwordChangeUrl) + { + this.passwordChangeUrl = passwordChangeUrl; + } + + public String getMessage() + { + return message; + } + + public void setMessage(String message) + { + this.message = message; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubLoginService.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubLoginService.java new file mode 100644 index 00000000..d464dc4d --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubLoginService.java @@ -0,0 +1,553 @@ +package com.ruoyi.framework.hub; + +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.subject.Subject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.stereotype.Component; + +import com.alibaba.fastjson.JSONObject; +import com.ruoyi.common.constant.Constants; +import com.ruoyi.common.core.domain.entity.SysUser; +import com.ruoyi.common.enums.UserStatus; +import com.ruoyi.common.utils.ShiroUtils; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.framework.manager.AsyncManager; +import com.ruoyi.framework.manager.factory.AsyncFactory; +import com.ruoyi.framework.shiro.service.SysLoginService; +import com.ruoyi.system.mapper.SysUserMapper; + +/** + * hub 门户票据免登:把一次性票据换成本地 Shiro 会话。 + * + *

认证走 {@link HubPortalToken} + 既有 {@code UserRealm},从而与账号密码登录共用同一条 + * 会话与在线用户登记链路(kickout、onlineSession、sys_user_online 全部照常生效), + * 不另起一套 WebSubject。参照 {@code McpBotAuthFilter} 的先例,但那里是请求级临时主体, + * 免登需要可复用的持久会话,因此必须走 {@code subject.login}。

+ * + *

本类还负责「在 OMS 登录页用统一门户账号密码直接登录」:已绑定账号的口令由 hub 校验, + * OMS 只是代理。走的是 hub 的「口令代校验」(对接指南 2.8):用集成密钥只问「这个账号配这个 + * 口令对不对」,hub 不签发令牌、也不要它自己的图形验证码,因此前端始终只有一张本系统验证码, + * 人机校验由本系统承担({@link #usesHubPassword} 供 {@code /login} 分流, + * {@link #loginByPassword} 完成校验与会话建立)。OMS 不保存也不比对内部人员的口令。

+ * + *

硬性约束:票据缺失、过期或 {@code active:false} 时一律拒绝并结束本次登录, + * 不得回落到本地口令校验,也不得复用旧会话。门户直登同样不得在「门户判定口令错误」时 + * 回退本地口令,只有门户不可达且显式开启 {@code hub.login.allow-local-fallback} 才回退。

+ * + * @author codex + */ +@Component +public class HubLoginService +{ + private static final Logger log = LoggerFactory.getLogger(HubLoginService.class); + + private final HubProperties properties; + + private final HubClient hubClient; + + private final SysUserMapper userMapper; + + private final SysLoginService loginService; + + /** 门户账号信息来源(ruoyi-sip 的人员目录镜像);实现缺失时门户直登降级为不可用 */ + private final ObjectProvider accountLookupProvider; + + public HubLoginService(HubProperties properties, HubClient hubClient, SysUserMapper userMapper, + SysLoginService loginService, ObjectProvider accountLookupProvider) + { + this.properties = properties; + this.hubClient = hubClient; + this.userMapper = userMapper; + this.loginService = loginService; + this.accountLookupProvider = accountLookupProvider; + } + + /** 是否启用了「在 OMS 登录页用门户口令登录」 */ + public boolean isPasswordLoginEnabled() + { + return properties.isConfigured() && properties.getLogin().isPasswordLoginEnabled(); + } + + /** + * 这个账号该由统一门户判口令,还是由本系统判口令({@code /login} 的分流依据)。 + * + *

统一登录未启用、账号未绑定,一律走本地口令,外部用户与 {@code admin} 不受影响。 + * 已绑定但目录镜像里查不到门户账号、或该人员被管理员忽略,仍然按「走门户」处理, + * 由 {@link #loginByPassword} 给出可行动的原因;这种时候放回本地口令等于悄悄放行了一份 + * 建号时的默认密码,是统一登录的漏洞,不能图省事放行。

+ */ + public boolean usesHubPassword(SysUser user) + { + return isPasswordLoginEnabled() && user != null && user.getHubUserId() != null; + } + + /** + * 用户在登录页输入的是统一门户账号时,反查它对应的本地账号。 + * + *

内部人员的身份与口令都在门户那边,账号自然也应该是门户账号;但本系统的 + * {@code sys_user.login_name} 是历史数据(手机号 / 域账号),两者不同源,所以只能靠 + * 人员目录镜像把门户账号换算成 {@code hub_user_id},再找回绑定的本地账号。

+ * + *

查不到、不唯一、该人被管理员忽略,都返回 {@code null} 让调用方继续按本地账号处理, + * 绝不因为「像是门户账号」就把外部用户的本地登录抢走。

+ * + * @param account 用户输入的登录名(此处按门户账号理解) + * @return 对应的本地账号;无对应关系时为 null + */ + public SysUser resolveUserByHubAccount(String account) + { + if (!isPasswordLoginEnabled() || StringUtils.isEmpty(account)) + { + return null; + } + HubAccountLookup lookup = accountLookupProvider.getIfAvailable(); + if (lookup == null) + { + return null; + } + HubAccountView view; + try + { + view = lookup.findByAccount(account.trim()); + } + catch (Exception e) + { + log.warn("按统一门户账号反查本地账号失败, 原因={}", e.getMessage()); + return null; + } + if (view == null || view.getHubUserId() == null || view.isIgnored()) + { + return null; + } + SysUser user = userMapper.selectUserByHubUserId(view.getHubUserId()); + if (user == null) + { + // 门户有这个人,但还没在 OMS 落地(未绑定),让他走原本地口令或等管理员处理 + log.debug("统一门户账号已同步到目录但尚未绑定本系统账号, hubUserId={}", view.getHubUserId()); + return null; + } + return user; + } + + /** + * 用统一门户的账号密码完成登录并建立本地会话。 + * + *

hub 侧走「口令代校验」(对接指南 2.8):用集成密钥只判口令,不签发 hub 令牌, + * 也不要求门户图形验证码——人机校验由本系统自己那张验证码承担。注意调用方必须自己 + * 检查 {@code ShiroConstants.CURRENT_CAPTCHA}:{@code captchaValidate} 过滤器只把失败结论 + * 写成请求属性、不拦请求,而本方法不经过 {@code SysLoginService#login},漏检等于免验证码。

+ * + * @param user 按登录名查出的本地账号,必须已绑定 hub + * @param password 用户在 OMS 输入的门户口令,不入库不记日志 + * @return 归一化结果;成功时已建立会话 + */ + public HubLoginResult loginByPassword(SysUser user, String password) + { + if (!isPasswordLoginEnabled()) + { + return HubLoginResult.of(HubLoginResult.STATUS_UNAVAILABLE, "统一登录未启用,请使用本系统密码登录"); + } + if (user == null || user.getHubUserId() == null) + { + return HubLoginResult.of(HubLoginResult.STATUS_LOCAL_LOGIN, "该账号使用本系统密码登录"); + } + if (StringUtils.isEmpty(password)) + { + return HubLoginResult.of(HubLoginResult.STATUS_INVALID_CREDENTIALS, "请输入统一门户密码"); + } + HubAccountView view = findHubAccount(user.getHubUserId()); + if (view == null) + { + return HubLoginResult.of(HubLoginResult.STATUS_UNAVAILABLE, + "尚未同步到该人员的统一门户账号,请联系管理员同步人员目录后再登录"); + } + if (view.isIgnored()) + { + return HubLoginResult.of(HubLoginResult.STATUS_UNAVAILABLE, + "该人员已被管理员忽略,请在「hub人员目录」页恢复处理后再登录"); + } + + HubLoginResult result = hubClient.verifyPassword(view.getAccount(), view.getEmail(), password); + if (!result.isSuccess()) + { + if (HubLoginResult.STATUS_UNAVAILABLE.equals(result.getStatus()) + && properties.getLogin().isAllowLocalFallback()) + { + return fallbackToLocalPassword(user, password); + } + return result; + } + if (!user.getHubUserId().equals(result.getHubUserId())) + { + // 门户判定口令正确,但这个人已经不是当初绑定的那个人(账号改绑/合并),宁可不登录 + log.error("统一门户返回的账号与本地绑定不一致, 本地绑定={}, 门户返回={}", user.getHubUserId(), + result.getHubUserId()); + return HubLoginResult.of(HubLoginResult.STATUS_UNAVAILABLE, + "统一门户账号与本地绑定不一致,请联系管理员核对后重新绑定"); + } + if (UserStatus.DISABLE.getCode().equals(user.getStatus())) + { + return HubLoginResult.of(HubLoginResult.STATUS_UNAVAILABLE, "账号已停用,请联系管理员"); + } + establishSession(user, "统一门户账号密码登录成功"); + return result; + } + + /** + * 已绑定统一门户的账号改口令:新口令交给门户校验并写入(对接指南 2.8.1)。 + * + *

内部人员的口令不在本系统,所以「个人中心改密码」必须改走门户:留在本地改,改的是 + * 一条没人再用的历史口令,本人下次用门户密码进来还是旧的。

+ * + *

门户要求当前口令必填:应用密钥只证明「哪个系统在调」,当前口令才证明「改的是 + * 谁的口令」,这一条也挡住了密钥泄露后静默改写全员口令。判定链与登录、代校验共用, + * 当前口令错一样计入失败锁定(5 次锁 15 分钟),所以本系统不要拿它当免费的口令字典。

+ * + *

「需要强制改密」不影响这里:门户的认证链只比对口令,口令过期照样证明得了身份 + * ({@code authenticate} 的口径),所以登录被 603 拦下的人也能用这台接口当场改完。

+ * + * @param user 本地账号,必须已绑定 hub + * @param currentPassword 当前门户口令原值,不入库不记日志 + * @param newPassword 新口令原值,规则由门户判,本系统不复刻 + * @return 归一化结果,永不返回 null + */ + public HubPasswordChangeResult changePassword(SysUser user, String currentPassword, String newPassword) + { + // 只看总闸,不看「允许在 OMS 登录页直登」:改密自带当前口令证明,与那个开关无关。 + // 用错开关会让管理员一关直登,内部人连改密码都改不了。 + if (!isEnabled()) + { + return HubPasswordChangeResult.unavailable("统一登录未启用,请使用本系统密码修改"); + } + if (user == null || user.getHubUserId() == null) + { + return HubPasswordChangeResult.unavailable("该账号未绑定统一门户,请在个人中心修改本系统密码"); + } + HubAccountView view = findHubAccount(user.getHubUserId()); + if (view == null) + { + return HubPasswordChangeResult.unavailable( + "尚未同步到该人员的统一门户账号,请联系管理员同步人员目录后再试"); + } + if (view.isIgnored()) + { + return HubPasswordChangeResult.unavailable("该人员已被管理员忽略,请在「hub人员目录」页恢复处理后再试"); + } + HubPasswordChangeResult result = hubClient.changePassword(view.getAccount(), view.getEmail(), + currentPassword, newPassword); + if (result.isChanged() && result.getHubUserId() != null + && !user.getHubUserId().equals(result.getHubUserId())) + { + // 口令确实改了,但改的不是当初绑定的那个人(门户账号改绑/合并),必须让人知道 + log.error("统一门户改密返回的账号与本地绑定不一致, 本地绑定={}, 门户返回={}", user.getHubUserId(), + result.getHubUserId()); + return HubPasswordChangeResult.unavailable("统一门户账号与本地绑定不一致,口令已修改,请用新口令重新登录"); + } + if (!result.isChanged() && !result.isUnavailable()) + { + // 只记结论,不记口令 + log.warn("统一门户改密未通过, loginName={}, reason={}", user.getLoginName(), result.getReason()); + } + return result; + } + + /** + * 门户免登录的口令要求,供改密表单按它校验,不在本系统写死长度与字符类别。 + * + * @return requirements 节点;读不到时返回空对象,前端按「不额外限制」降级 + */ + public JSONObject passwordRequirements() + { + // 只用于给表单写提示,读不到就降级为「不额外限制」,不能让门户故障挡住改密 + try + { + return hubClient.fetchPasswordRequirements(); + } + catch (HubException e) + { + log.warn("读取统一门户口令要求失败, 原因={}", e.getMessage()); + return new JSONObject(); + } + } + + /** + * 登录页改密用:按用户输入的账号找回已绑定门户的本地账号。 + * + *

查找顺序与 {@code /login} 完全一致(先本地登录名、再按门户账号反查),两处顺序不同 + * 会让「在登录页改密码」和「在登录页登录」认成不同的人。

+ * + * @param account 用户在登录页输入的账号 + * @return 已绑定门户的本地账号;未绑定或查不到返回 null + */ + public SysUser resolveBoundUser(String account) + { + if (StringUtils.isEmpty(account)) + { + return null; + } + SysUser user = userMapper.selectUserByLoginName(account.trim()); + if (user != null && user.getHubUserId() != null) + { + return user; + } + return resolveUserByHubAccount(account); + } + + /** 为已绑定门户的账号建立本地会话(登录页改密成功后就地登录) */ + public void signIn(SysUser user) + { + establishSession(user, "统一门户修改密码后登录"); + } + + /** + * 门户不可达时的本地口令兜底(默认关闭,需显式开 {@code hub.login.allow-local-fallback})。 + * + *

只在「门户不可达」这一种情况下走到这里:门户明确判定口令错误 / 账号锁定时绝不允许回退, + * 否则等于给统一登录开了个本地后门。改密不走这条兜底(见 {@link #changePassword})。

+ */ + private HubLoginResult fallbackToLocalPassword(SysUser user, String password) + { + try + { + loginService.login(user.getLoginName(), password); + } + catch (AuthenticationException e) + { + log.warn("统一门户不可用且本地口令校验未通过, loginName={}, 原因={}", user.getLoginName(), + e.getMessage()); + return HubLoginResult.of(HubLoginResult.STATUS_INVALID_CREDENTIALS, "统一门户不可用,本系统密码也不正确"); + } + catch (Exception e) + { + log.warn("统一门户不可用且本地口令校验异常, loginName={}, 原因={}", user.getLoginName(), e.getMessage()); + return HubLoginResult.of(HubLoginResult.STATUS_INVALID_CREDENTIALS, "统一门户不可用,本系统密码也不正确"); + } + HubLoginResult result = HubLoginResult.of(HubLoginResult.STATUS_SUCCESS, "统一门户暂不可用,已用本系统密码登录"); + establishSession(user, "统一门户不可用,本地口令兜底登录成功"); + return result; + } + + /** 取门户账号信息;没有实现或没查到都返回 null */ + private HubAccountView findHubAccount(Long hubUserId) + { + HubAccountLookup lookup = accountLookupProvider.getIfAvailable(); + if (lookup == null) + { + log.debug("未提供 HubAccountLookup 实现,无法代理统一门户登录"); + return null; + } + try + { + return lookup.findByHubUserId(hubUserId); + } + catch (Exception e) + { + log.warn("查询统一门户账号信息失败, hubUserId={}, 原因={}", hubUserId, e.getMessage()); + return null; + } + } + + /** + * 用已确认身份的本地账号建立会话(门户票据免登与门户直登共用)。 + */ + private void establishSession(SysUser user, String loginSuccessMessage) + { + Subject subject = SecurityUtils.getSubject(); + if (subject.isAuthenticated()) + { + SysUser current = ShiroUtils.getSysUser(); + if (current != null && user.getUserId().equals(current.getUserId())) + { + recordLoginInfo(user); + recordLogininfor(user.getLoginName(), Constants.LOGIN_SUCCESS, loginSuccessMessage + "(复用现有会话)"); + return; + } + // 已有别人的会话:先断开再重建,避免串号 + subject.logout(); + } + + try + { + SecurityUtils.getSubject().login(new HubPortalToken(user.getLoginName(), user)); + } + catch (AuthenticationException e) + { + log.warn("统一门户建立本地会话失败, hubUserId={}, cause={}", user.getHubUserId(), e.getMessage()); + throw new HubLoginException("登录状态建立失败,请重新登录"); + } + recordLoginInfo(user); + recordLogininfor(user.getLoginName(), Constants.LOGIN_SUCCESS, loginSuccessMessage); + } + + /** + * 用门户票据建立本地会话。 + * + * @param ticket 一次性票据原值,调用方不得记录到日志 + * @param requestState 落地页生成的 state,可为空(门户跳转不携带 state) + * @param expectedState 会话中记录的 state,可为空 + * @return 登录成功的本地账号 + * @throws HubLoginException 票据无效、账号未绑定或已停用 + */ + public SysUser loginByTicket(String ticket, String requestState, String expectedState) + { + return loginByAppTicket(ticket, requestState, expectedState, + properties.getIntegrationKey(), properties.getAppCode(), "统一门户免登成功"); + } + + /** + * H5 用自己在 hub 的应用凭据换本地会话(H5 在 hub 是独立应用,票据按应用隔离)。 + * + * @throws HubLoginException H5 免登未配置、票据无效、账号未绑定或已停用 + */ + public SysUser loginH5ByTicket(String ticket, String requestState, String expectedState) + { + if (!properties.isH5Configured()) + { + throw new HubLoginException("H5 统一登录未启用或配置不完整"); + } + return loginByAppTicket(ticket, requestState, expectedState, + properties.getH5().getIntegrationKey(), properties.getH5().getAppCode(), "统一门户 H5 免登成功"); + } + + /** 认人与建会话的口径与管理端一致(只认 sub,ADR-0015),差异只在用哪个应用的密钥验票 */ + private SysUser loginByAppTicket(String ticket, String requestState, String expectedState, + String integrationKey, String expectedAppCode, String loginSuccessMessage) + { + if (!properties.isConfigured()) + { + throw new HubLoginException("统一登录未启用或配置不完整"); + } + if (ticket == null || ticket.trim().isEmpty()) + { + throw new HubLoginException("缺少登录票据,请从统一门户进入"); + } + // hub 门户跳转不替下游生成 state(MyApps.tsx 请求体为空),因此 state 只作尽力校验: + // 会话里有记录就必须一致,没有记录则完全依赖一次性票据防线。 + if (expectedState != null && !expectedState.isEmpty() && !expectedState.equals(requestState)) + { + throw new HubLoginException("登录状态校验失败,请回到统一门户重新进入"); + } + + HubTicketResult result; + try + { + result = hubClient.verifyTicket(ticket.trim(), integrationKey); + } + catch (HubException e) + { + // 不自动重试:hub 是「先查询立即删除」,超时无法判断是否已消费 + log.error("hub 免登票据校验异常: {}", e.getMessage()); + throw new HubLoginException("统一门户暂时不可用,请稍后重试"); + } + + if (!result.isActive()) + { + throw new HubLoginException(result.getReasonMessage()); + } + if (isAppCodeMismatch(result.getAppCode(), expectedAppCode)) + { + log.error("hub 票据应用编码与本系统不一致, hub 回显={}, 本系统={}", result.getAppCode(), expectedAppCode); + throw new HubLoginException("登录票据与本系统不匹配,请回到统一门户重新进入"); + } + + Long hubUserId = parseSub(result.getSub()); + SysUser user = userMapper.selectUserByHubUserId(hubUserId); + if (user == null) + { + // 认人只认 sub:命中不了就是没同步到,绝不用 account 兜底去猜(ADR-0015) + log.warn("hub 票据校验通过但本地无绑定账号, hubUserId={}", hubUserId); + throw new HubLoginException("账号尚未同步到本系统,请稍后重试或联系管理员"); + } + if (UserStatus.DISABLE.getCode().equals(user.getStatus())) + { + throw new HubLoginException("账号已停用,请联系管理员"); + } + if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) + { + throw new HubLoginException("账号已被删除,请联系管理员"); + } + + establishSession(user, loginSuccessMessage); + // 正常应为会话中的主体;取不到时退回已校验的账号,避免调用方拿到 null 再解引用 + SysUser current = ShiroUtils.getSysUser(); + return current != null ? current : user; + } + + private boolean isAppCodeMismatch(String hubAppCode, String expectedAppCode) + { + String expected = expectedAppCode; + if (expected == null || expected.trim().isEmpty()) + { + // 未配置 app-code 时不做比对,但 hub 回显为空同样放行(老版本兼容) + return false; + } + return hubAppCode != null && !hubAppCode.trim().isEmpty() + && !expected.trim().equalsIgnoreCase(hubAppCode.trim()); + } + + private Long parseSub(String sub) + { + if (sub == null || sub.trim().isEmpty()) + { + throw new HubLoginException("统一门户未返回账号标识,请重新进入"); + } + try + { + return Long.valueOf(sub.trim()); + } + catch (NumberFormatException e) + { + throw new HubLoginException("统一门户返回的账号标识格式异常"); + } + } + + /** + * 记录最后登录信息。账号密码登录由 {@link SysLoginService} 在口令校验通过后调用同一方法, + * 免登不经过那个分支,因此在这里补齐,保证「最后登录IP/时间」两类登录行为一致。 + */ + private void recordLoginInfo(SysUser user) + { + try + { + loginService.recordLoginInfo(user.getUserId()); + } + catch (Exception e) + { + log.warn("hub 免登记录登录信息失败, userId={}", user.getUserId(), e); + } + } + + /** 已绑定 hub 的账号是否禁止本地口令登录 */ + public boolean isRejectBoundLocalLogin() + { + return properties.isEnabled() && properties.getLogin().isRejectBoundLocalLogin(); + } + + /** + * 登录日志。账号密码登录的日志由 {@code SysLoginService#login} 内部记录,免登不经过那里, + * 在此补齐,使 sys_logininfor 能区分「统一门户免登」与本地口令登录。 + */ + private void recordLogininfor(String loginName, String status, String message) + { + AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, status, message)); + } + + /** 免登总闸是否可用 */ + public boolean isEnabled() + { + return properties.isConfigured(); + } + + public String getHubBaseUrl() + { + return properties.getNormalizedBaseUrl(); + } + + public boolean isLogoutRedirectHub() + { + return properties.isEnabled() && properties.getLogin().isLogoutRedirectHub(); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubPasswordChangeResult.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubPasswordChangeResult.java new file mode 100644 index 00000000..cccd750e --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubPasswordChangeResult.java @@ -0,0 +1,113 @@ +package com.ruoyi.framework.hub; + +/** + * 统一门户服务端改密结果(对接指南 2.8.1:{@code POST /api/v1/auth/password-change})。 + * + *

hub 的口令类不通过也是 HTTP 200 + {@code changed:false} + {@code reason},只有调用方凭据 + * 有问题才是 401/403,网络与门户故障另归「不可达」——三者必须分开:把人误报成「当前密码不正确」 + * 会让人反复重试直到账号被锁。

+ * + * @author codex + */ +public class HubPasswordChangeResult +{ + /** 门户已写入新密码 */ + public static final String STATUS_CHANGED = "changed"; + + /** 门户拒绝了这次修改,原因见 {@link #getReason()},可改密码后重试 */ + public static final String STATUS_REJECTED = "rejected"; + + /** 门户不可达(网络/超时/凭据配置问题),此时不要让人改密码 */ + public static final String STATUS_UNAVAILABLE = "unavailable"; + + /** 当前口令不对、账号不存在或已停用、账号还没有口令(hub 同一句,防枚举) */ + public static final String REASON_INVALID_CREDENTIALS = "invalid_credentials"; + + /** 连续失败触发锁定(与门户登录同一套:5 次锁 15 分钟) */ + public static final String REASON_ACCOUNT_LOCKED = "account_locked"; + + /** 该账号未开通密码登录,hub 明确拒绝代为改密 */ + public static final String REASON_PASSWORD_DISABLED = "password_login_disabled"; + + /** 新口令就是当前口令 */ + public static final String REASON_UNCHANGED = "password_unchanged"; + + /** 新口令不满足门户口令安全参数,细分见 password_code */ + public static final String REASON_WEAK = "weak_password"; + + private final String status; + + private final String reason; + + /** 仅 {@link #REASON_WEAK} 有值:password_length / password_classes / password_common / password_contains_account */ + private final String passwordCode; + + /** 可直接展示给用户的话,不含敏感信息 */ + private final String message; + + /** 改密成功时门户回带的用户ID,用于与本地绑定比对 */ + private Long hubUserId; + + private HubPasswordChangeResult(String status, String reason, String passwordCode, String message) + { + this.status = status; + this.reason = reason; + this.passwordCode = passwordCode; + this.message = message; + } + + public static HubPasswordChangeResult success() + { + return new HubPasswordChangeResult(STATUS_CHANGED, null, null, "密码修改成功"); + } + + public static HubPasswordChangeResult rejected(String reason, String passwordCode, String message) + { + return new HubPasswordChangeResult(STATUS_REJECTED, reason, passwordCode, message); + } + + public static HubPasswordChangeResult unavailable(String message) + { + return new HubPasswordChangeResult(STATUS_UNAVAILABLE, null, null, message); + } + + public boolean isChanged() + { + return STATUS_CHANGED.equals(status); + } + + public boolean isUnavailable() + { + return STATUS_UNAVAILABLE.equals(status); + } + + public String getStatus() + { + return status; + } + + public String getReason() + { + return reason; + } + + public String getPasswordCode() + { + return passwordCode; + } + + public String getMessage() + { + return message; + } + + public Long getHubUserId() + { + return hubUserId; + } + + public void setHubUserId(Long hubUserId) + { + this.hubUserId = hubUserId; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubPortalToken.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubPortalToken.java new file mode 100644 index 00000000..27c9e848 --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubPortalToken.java @@ -0,0 +1,35 @@ +package com.ruoyi.framework.hub; + +import org.apache.shiro.authc.UsernamePasswordToken; + +import com.ruoyi.common.core.domain.entity.SysUser; + +/** + * hub 门户票据免登所用的认证令牌。 + * + *

继承 {@link UsernamePasswordToken} 是为了复用 {@code UserRealm} 与既有的会话、 + * 在线用户登记链路,同时用 {@link #getHubUser()} 让 Realm 识别「身份已由 hub 确认、 + * 不再校验本地口令」。密码位填一个恒不匹配的占位值,避免 null 进入 Realm。

+ * + * @author codex + */ +public class HubPortalToken extends UsernamePasswordToken +{ + private static final long serialVersionUID = 1L; + + /** 占位口令:不是任何合法哈希,即使误入口令校验分支也必然失败 */ + private static final String NOT_VERIFIED = "!hub-ticket-verified-no-local-password!"; + + private final transient SysUser hubUser; + + public HubPortalToken(String username, SysUser hubUser) + { + super(username, NOT_VERIFIED, false); + this.hubUser = hubUser; + } + + public SysUser getHubUser() + { + return hubUser; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubProperties.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubProperties.java new file mode 100644 index 00000000..fbf290cb --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubProperties.java @@ -0,0 +1,372 @@ +package com.ruoyi.framework.hub; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * dsh-hub 统一登录与人员同步配置。 + * + *

密钥只从环境变量或配置中心注入,不落仓库;{@link #enabled} 为 false 时 + * 登录、同步、退出行为必须与接入 hub 之前完全一致(一键退回的逃生开关)。

+ * + * @author codex + */ +@Component +@ConfigurationProperties(prefix = "hub") +public class HubProperties +{ + /** 总闸:false 时不验票、不同步、不拦截本地登录 */ + private boolean enabled = false; + + /** hub 站点基地址,生产必须 https,结尾不带 / */ + private String baseUrl = ""; + + /** 本系统在 hub 注册的应用编码,验票响应必须回显同一值(防串号) */ + private String appCode = ""; + + /** 应用密钥明文,同时用于票据校验与目录导出;用环境变量注入 */ + private String integrationKey = ""; + + /** 连接与读取超时(毫秒) */ + private int connectTimeoutMs = 3000; + + private int readTimeoutMs = 10000; + + private Login login = new Login(); + + private Directory directory = new Directory(); + + private H5 h5 = new H5(); + + public static class Login + { + /** + * 已绑定 hub 的账号提交本地 {@code /login} 时是否拒绝。 + * + *

true(默认):绑定账号的口令由 hub 校验,本地 {@code /login} 直接拒绝并提示走门户, + * 避免有人用旧的 OMS 口令绕过统一登录。false:绑定账号也能用本地口令登录。

+ */ + private boolean rejectBoundLocalLogin = true; + + /** + * 是否允许「在 OMS 登录页用统一门户账号密码直接登录」。 + * + *

true(默认):已绑定账号在 OMS 登录页输入的口令转发 hub 校验,门户挂了就是登不进来; + * false:登录页只服务外部用户,内部人员一律从门户卡片免登进入。

+ */ + private boolean passwordLoginEnabled = true; + + /** + * hub 不可达时是否允许绑定账号回退本地口令登录。 + * + *

默认 false,即「统一登录开启时本地口令不参与登录」,与 OMS 口令只作为 + * 建号初始密码的口径一致。设为 true 时,只有在 hub 网络异常/5xx(不是口令错) + * 的情况下才会用本地口令兜底,口令错与锁定一律不回退。

+ */ + private boolean allowLocalFallback = false; + + /** 内部用户退出后是否跳转 hub 站点首页 */ + private boolean logoutRedirectHub = true; + + public boolean isRejectBoundLocalLogin() + { + return rejectBoundLocalLogin; + } + + public boolean isPasswordLoginEnabled() + { + return passwordLoginEnabled; + } + + public void setPasswordLoginEnabled(boolean passwordLoginEnabled) + { + this.passwordLoginEnabled = passwordLoginEnabled; + } + + public void setRejectBoundLocalLogin(boolean rejectBoundLocalLogin) + { + this.rejectBoundLocalLogin = rejectBoundLocalLogin; + } + + public boolean isAllowLocalFallback() + { + return allowLocalFallback; + } + + public void setAllowLocalFallback(boolean allowLocalFallback) + { + this.allowLocalFallback = allowLocalFallback; + } + + public boolean isLogoutRedirectHub() + { + return logoutRedirectHub; + } + + public void setLogoutRedirectHub(boolean logoutRedirectHub) + { + this.logoutRedirectHub = logoutRedirectHub; + } + } + + public static class Directory + { + /** 目录同步开关,与登录开关解耦,可先只镜像不接管登录 */ + private boolean enabled = true; + + /** 花名册条数,hub 取值 1-5000,默认 2000 */ + private int memberLimit = 2000; + + /** + * 是否按「姓名唯一命中」自动将 hub 人员绑定到存量 OMS 账号。 + * + *

关掉它等于全部交人工:镜像照做,但一个都不自动绑,管理员在「hub 人员目录」页 + * 逐个确认。首次上线建议先关掉跑一轮全量、核对绑定结果,再打开。

+ */ + private boolean autoBindByName = true; + + /** + * hub 侧新增的人(增量事件里本地镜像没有这个人)是否自动建号并绑定。 + * + *

只作用于新增;首次全量里匹配不上的人不建号,留在镜像表由管理员处理(ADR-0017)。

+ */ + private boolean autoCreateNew = true; + + /** 同步是否停用本地账号(hub 侧 status 非 1) */ + private boolean disableMissing = true; + + /** 单批增量条数,hub 上限 500 */ + private int changeLimit = 200; + + public boolean isEnabled() + { + return enabled; + } + + public void setEnabled(boolean enabled) + { + this.enabled = enabled; + } + + public int getMemberLimit() + { + return memberLimit; + } + + public void setMemberLimit(int memberLimit) + { + this.memberLimit = memberLimit; + } + + public boolean isAutoBindByName() + { + return autoBindByName; + } + + public void setAutoBindByName(boolean autoBindByName) + { + this.autoBindByName = autoBindByName; + } + + public boolean isAutoCreateNew() + { + return autoCreateNew; + } + + public void setAutoCreateNew(boolean autoCreateNew) + { + this.autoCreateNew = autoCreateNew; + } + + public boolean isDisableMissing() + { + return disableMissing; + } + + public void setDisableMissing(boolean disableMissing) + { + this.disableMissing = disableMissing; + } + + public int getChangeLimit() + { + return changeLimit; + } + + public void setChangeLimit(int changeLimit) + { + this.changeLimit = changeLimit; + } + } + + public boolean isEnabled() + { + return enabled; + } + + public void setEnabled(boolean enabled) + { + this.enabled = enabled; + } + + public String getBaseUrl() + { + return baseUrl; + } + + public void setBaseUrl(String baseUrl) + { + this.baseUrl = baseUrl; + } + + public String getAppCode() + { + return appCode; + } + + public void setAppCode(String appCode) + { + this.appCode = appCode; + } + + public String getIntegrationKey() + { + return integrationKey; + } + + public void setIntegrationKey(String integrationKey) + { + this.integrationKey = integrationKey; + } + + public int getConnectTimeoutMs() + { + return connectTimeoutMs; + } + + public void setConnectTimeoutMs(int connectTimeoutMs) + { + this.connectTimeoutMs = connectTimeoutMs; + } + + public int getReadTimeoutMs() + { + return readTimeoutMs; + } + + public void setReadTimeoutMs(int readTimeoutMs) + { + this.readTimeoutMs = readTimeoutMs; + } + + public Login getLogin() + { + return login; + } + + public void setLogin(Login login) + { + this.login = login; + } + + public Directory getDirectory() + { + return directory; + } + + public void setDirectory(Directory directory) + { + this.directory = directory; + } + + public H5 getH5() + { + return h5; + } + + public void setH5(H5 h5) + { + this.h5 = h5; + } + + /** + * H5 审批系统在 hub 注册的第二个应用。 + * + *

hub 的票据按应用隔离(验票会比对票据所属应用与调用方密钥),所以 H5 不能用管理端那把 + * 密钥验自己的票,必须单独注册应用、单独下发密钥,混用必然 {@code ticket_audience_mismatch}。

+ */ + public static class H5 + { + /** H5 免登开关,与总闸 {@code hub.enabled} 是与关系 */ + private boolean enabled = true; + + /** H5 在 hub 注册的应用编码,用于校验验票回显防串号 */ + private String appCode = ""; + + /** H5 的应用密钥明文,只从环境变量注入,不落仓库 */ + private String integrationKey = ""; + + public boolean isEnabled() + { + return enabled; + } + + public void setEnabled(boolean enabled) + { + this.enabled = enabled; + } + + public String getAppCode() + { + return appCode; + } + + public void setAppCode(String appCode) + { + this.appCode = appCode; + } + + public String getIntegrationKey() + { + return integrationKey; + } + + public void setIntegrationKey(String integrationKey) + { + this.integrationKey = integrationKey; + } + } + + /** 配置是否足以发起 hub 调用 */ + public boolean isConfigured() + { + return enabled + && baseUrl != null && !baseUrl.trim().isEmpty() + && integrationKey != null && !integrationKey.trim().isEmpty(); + } + + /** + * H5 免登是否可用:总闸与管理端凭据齐备({@code loginByAppTicket} 同样要求它), + * 且 H5 自己的开关与密钥齐备。 + * + *

这里刻意与管理端调用同口径:否则 {@code /status} 会报 enabled:true 而验票时再失败, + * 前端只能看到一个更晚、更难解释的错误。

+ */ + public boolean isH5Configured() + { + return isConfigured() + && h5 != null && h5.isEnabled() + && h5.getIntegrationKey() != null && !h5.getIntegrationKey().trim().isEmpty(); + } + + /** 去掉结尾斜杠,避免拼出 //api/v1 这种路径 */ + public String getNormalizedBaseUrl() + { + String value = baseUrl == null ? "" : baseUrl.trim(); + while (value.endsWith("/")) + { + value = value.substring(0, value.length() - 1); + } + return value; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubTicketResult.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubTicketResult.java new file mode 100644 index 00000000..164165df --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/hub/HubTicketResult.java @@ -0,0 +1,122 @@ +package com.ruoyi.framework.hub; + +/** + * hub 票据校验结果(POST /api/v1/auth/tickets/verify 的 data)。 + * + *

票据类失败一律 HTTP 200 且 code 为 "200",由 {@code active=false} 与 {@code reason} + * 表达,因此判定成功必须看 active,不能只看 HTTP 状态码。

+ * + * @author codex + */ +public class HubTicketResult +{ + private boolean active; + + /** 失败原因:ticket_invalid / ticket_audience_mismatch / ticket_expired / user_inactive */ + private String reason; + + /** hub 用户 ID 的十进制字符串,下游以此作为唯一映射键 */ + private String sub; + + private String account; + + private String displayName; + + private String email; + + /** 票据所属应用编码,与自身 appCode 比对可防串号 */ + private String appCode; + + public boolean isActive() + { + return active; + } + + public void setActive(boolean active) + { + this.active = active; + } + + public String getReason() + { + return reason; + } + + public void setReason(String reason) + { + this.reason = reason; + } + + public String getSub() + { + return sub; + } + + public void setSub(String sub) + { + this.sub = sub; + } + + public String getAccount() + { + return account; + } + + public void setAccount(String account) + { + this.account = account; + } + + public String getDisplayName() + { + return displayName; + } + + public void setDisplayName(String displayName) + { + this.displayName = displayName; + } + + public String getEmail() + { + return email; + } + + public void setEmail(String email) + { + this.email = email; + } + + public String getAppCode() + { + return appCode; + } + + public void setAppCode(String appCode) + { + this.appCode = appCode; + } + + /** + * 把失败原因翻译成可直接展示的中文,不泄露内部细节。 + */ + public String getReasonMessage() + { + if (reason == null) + { + return "统一登录校验失败,请重新从门户进入"; + } + switch (reason) + { + case "ticket_expired": + return "登录票据已过期,请回到统一门户重新进入"; + case "ticket_audience_mismatch": + return "登录票据不属于本系统,请回到统一门户重新进入"; + case "user_inactive": + return "账号已在统一门户停用或不存在,请联系管理员"; + case "ticket_invalid": + default: + return "登录票据无效或已被使用,请回到统一门户重新进入"; + } + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/realm/UserRealm.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/realm/UserRealm.java index 8cda35e2..60854981 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/realm/UserRealm.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/realm/UserRealm.java @@ -28,6 +28,7 @@ import com.ruoyi.common.exception.user.UserNotExistsException; import com.ruoyi.common.exception.user.UserPasswordNotMatchException; import com.ruoyi.common.exception.user.UserPasswordRetryLimitExceedException; import com.ruoyi.common.utils.ShiroUtils; +import com.ruoyi.framework.hub.HubPortalToken; import com.ruoyi.framework.shiro.service.SysLoginService; import com.ruoyi.system.service.ISysMenuService; import com.ruoyi.system.service.ISysRoleService; @@ -86,6 +87,12 @@ public class UserRealm extends AuthorizingRealm @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { + // hub 门户票据免登:身份已在 HubLoginService 验票确认,不再校验本地口令 + if (token instanceof HubPortalToken) + { + return authenticateByHub((HubPortalToken) token); + } + UsernamePasswordToken upToken = (UsernamePasswordToken) token; String username = upToken.getUsername(); String password = ""; @@ -132,6 +139,21 @@ public class UserRealm extends AuthorizingRealm return info; } + /** + * hub 免登认证。票据已在 HubLoginService 校验通过并据此查出本地账号, + * 这里只做与账号密码登录等价的收尾(补齐角色权限属性,供数据权限使用),不碰口令。 + */ + private AuthenticationInfo authenticateByHub(HubPortalToken token) + { + SysUser user = token.getHubUser(); + if (user == null) + { + throw new UnknownAccountException("统一门户返回的账号在本系统不存在"); + } + loginService.setRolePermission(user); + return new SimpleAuthenticationInfo(user, token.getPassword(), getName()); + } + /** * 清理指定用户授权信息缓存 */ diff --git a/ruoyi-sip/src/main/java/com/ruoyi/quartz/task/HubDirectorySyncTask.java b/ruoyi-sip/src/main/java/com/ruoyi/quartz/task/HubDirectorySyncTask.java new file mode 100644 index 00000000..69aae724 --- /dev/null +++ b/ruoyi-sip/src/main/java/com/ruoyi/quartz/task/HubDirectorySyncTask.java @@ -0,0 +1,67 @@ +package com.ruoyi.quartz.task; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.ruoyi.sip.hub.domain.HubSyncResult; +import com.ruoyi.sip.hub.service.IHubDirectorySyncService; + +/** + * hub 目录同步定时任务。 + * + *

放在 {@code com.ruoyi.quartz.task}(与 {@code RyTask} 同包)以命中 quartz 白名单 + * {@code Constants.JOB_WHITELIST_STR},与仓库内定时任务类的既有位置保持一致;类文件本身仍在 + * {@code ruoyi-sip} 模块内,因为 {@code ruoyi-quartz} 只依赖 {@code ruoyi-common}, + * 看不到本模块的同步服务。可直接在「系统监控 > 定时任务」里配置调用目标 + * {@code hubDirectorySyncTask.xxx()}。

+ * + *

两个入口都必须能在 hub 未启用时空转返回,不能抛异常,否则定时任务页会持续报红。

+ * + * @author codex + */ +@Component("hubDirectorySyncTask") +public class HubDirectorySyncTask +{ + private static final Logger log = LoggerFactory.getLogger(HubDirectorySyncTask.class); + + @Autowired + private IHubDirectorySyncService syncService; + + /** 全量校对:每日一次,兜住事件缺失与父子关系变化 */ + public void fullSync() + { + try + { + HubSyncResult result = syncService.fullSync(); + logIfWorked("全量", result); + } + catch (Exception e) + { + log.error("hub 目录全量同步异常", e); + } + } + + /** 增量轮询:固定周期,30-60 秒一次 */ + public void incrementalSync() + { + try + { + HubSyncResult result = syncService.incrementalSync(); + logIfWorked("增量", result); + } + catch (Exception e) + { + log.error("hub 目录增量同步异常", e); + } + } + + private void logIfWorked(String pass, HubSyncResult result) + { + if (result != null && result.getFetched() > 0) + { + log.info("hub 目录{}同步有变更: {}", pass, result.summary()); + } + } +} diff --git a/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/controller/HubH5SsoController.java b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/controller/HubH5SsoController.java new file mode 100644 index 00000000..1b0288f5 --- /dev/null +++ b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/controller/HubH5SsoController.java @@ -0,0 +1,152 @@ +package com.ruoyi.sip.hub.controller; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpSession; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.ruoyi.common.annotation.Anonymous; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.domain.entity.SysUser; +import com.ruoyi.framework.hub.HubLoginException; +import com.ruoyi.framework.hub.HubLoginService; +import com.ruoyi.framework.hub.HubProperties; + +/** + * H5 审批系统的门户票据免登入口。 + * + *

H5({@code D:\java\workspace\ai\oms_vue},Vue3 + Vant)与本系统同域部署在同一台机器上, + * 认证同样依赖 Shiro 会话 Cookie,所以免登只需要「验票 + 建会话」,不需要另外签发令牌。

+ * + *

落地链路:门户点 H5 卡片 → hub 302 到 {@code https:///sso?ticket=..} → + * H5 落地页把 ticket POST 给本接口 → 后端用 H5 自己的应用密钥验票 → 建立本地会话。 + * hub 的票据按应用隔离(对接指南 8.1),管理端密钥验不了 H5 的票,因此配置段是 + * {@code hub.h5.*},密钥必须在 hub 管理端单独注册应用后单独下发。

+ * + *

安全约定与管理端一致(对接指南 8.4、11):ticket 不入库、不写日志、不重试; + * 票据无效一律回门户,不回落本地口令。

+ * + * @author codex + */ +@RestController +@RequestMapping("/sso/hub/h5") +public class HubH5SsoController extends BaseController +{ + private static final Logger log = LoggerFactory.getLogger(HubH5SsoController.class); + + /** 发起跳转时在 H5 生成、由本接口消费的一次性 state 会话键,与管理端分开以免互相覆盖 */ + private static final String SESSION_STATE_KEY = "HUB_H5_SSO_STATE"; + + /** 人机校验开关,与登录页共用 {@code shiro.user.captchaEnabled},供改密表单决定是否显示验证码 */ + @Value("${shiro.user.captchaEnabled:false}") + private boolean captchaEnabled; + + @Autowired + private HubLoginService hubLoginService; + + @Autowired + private HubProperties hubProperties; + + /** + * H5 免登是否可用与门户地址,供前端决定提示文案与退出后跳去哪里。 + * + *

只暴露非敏感信息,绝不下发密钥。

+ */ + @Anonymous + @GetMapping("/status") + public AjaxResult status() + { + Map data = new HashMap<>(); + data.put("enabled", hubProperties.isH5Configured()); + data.put("hubHomeUrl", hubLoginService.getHubBaseUrl()); + data.put("logoutRedirectHub", hubLoginService.isLogoutRedirectHub()); + data.put("captchaEnabled", captchaEnabled); + return AjaxResult.success(data); + } + + /** + * 账号是否已绑定统一门户,供 H5「忘记密码」页决定改密走门户还是走原本的邮箱验证码。 + * + *

已绑定账号的口令归门户管,用本系统的邮箱重置只会改掉一份没人再用的本地口令, + * 所以前端必须先问一句。未绑定(外部用户)返回 {@code bound:false},原流程不变。

+ */ + @Anonymous + @GetMapping("/bound") + public AjaxResult bound(String account) + { + Map data = new HashMap<>(); + boolean bound = hubLoginService.isEnabled() && hubLoginService.resolveBoundUser(account) != null; + data.put("bound", bound); + if (bound) + { + // 门户改密需要当前口令,且靠本系统的图形验证码做人机校验,前端按它渲染表单 + data.put("captchaEnabled", captchaEnabled); + } + return AjaxResult.success(data); + } + + /** + * 记录 H5 生成的 state,供验票时比对。 + */ + @Anonymous + @PostMapping("/state") + public AjaxResult prepareState(@RequestBody Map body, HttpSession session) + { + if (!hubProperties.isH5Configured()) + { + return AjaxResult.error("H5 统一登录未启用"); + } + String state = body == null ? null : body.get("state"); + if (state == null || state.trim().isEmpty() || state.length() > 64) + { + return AjaxResult.error("登录状态参数异常"); + } + session.setAttribute(SESSION_STATE_KEY, state.trim()); + return AjaxResult.success(); + } + + /** + * 用一次性票据换取 H5 的本地会话。 + */ + @Anonymous + @PostMapping("/verify") + public AjaxResult verify(@RequestBody Map body, HttpSession session) + { + if (!hubProperties.isH5Configured()) + { + return AjaxResult.error("H5 统一登录未启用,请使用账号密码登录"); + } + String ticket = body == null ? null : body.get("ticket"); + String state = body == null ? null : body.get("state"); + String expectedState = session.getAttribute(SESSION_STATE_KEY) == null + ? null : String.valueOf(session.getAttribute(SESSION_STATE_KEY)); + // 一次性使用:无论成败都清掉,避免同一个 state 被反复提交 + session.removeAttribute(SESSION_STATE_KEY); + try + { + SysUser user = hubLoginService.loginH5ByTicket(ticket, state, expectedState); + Map data = new HashMap<>(); + data.put("userId", user.getUserId()); + data.put("loginName", user.getLoginName()); + data.put("userName", user.getUserName()); + return AjaxResult.success(data); + } + catch (HubLoginException e) + { + // 只记结论,不记票据 + log.warn("hub H5 免登失败: {}", e.getMessage()); + return AjaxResult.error(e.getMessage()); + } + } +} diff --git a/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/controller/HubSsoController.java b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/controller/HubSsoController.java new file mode 100644 index 00000000..6c0c84ea --- /dev/null +++ b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/controller/HubSsoController.java @@ -0,0 +1,272 @@ +package com.ruoyi.sip.hub.controller; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpSession; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.google.code.kaptcha.Constants; +import com.ruoyi.common.annotation.Anonymous; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.domain.entity.SysUser; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.framework.hub.HubLoginException; +import com.ruoyi.framework.hub.HubLoginService; +import com.ruoyi.framework.hub.HubPasswordChangeResult; +import com.ruoyi.framework.hub.HubProperties; + +/** + * hub 门户票据免登入口(Vue 侧)。 + * + *

落地链路:门户点卡片 → hub 302 到前端 {@code /sso/hub?ticket=..&state=..} → + * 前端把 ticket POST 给本接口 → 后端带 {@code X-Integration-Key} 服务端验票 → + * 建立本地会话。票据只在后端与 hub 之间出现,浏览器不参与校验。

+ * + *

「不常上门户的人直接在 OMS 登录页登录」不在本类:那条路复用本系统的 + * {@code POST /login},由它按绑定关系决定口令归谁判(见 {@code SysLoginController} + * 与 {@code HubLoginService#loginByPassword}),前端始终只有一张本系统验证码。

+ * + *

安全约定(对接指南 8.4、11):ticket 不入库、不写日志、不重试; + * state 尽力校验(门户跳转不生成 state);票据无效一律回 hub,不回落本地口令。

+ * + * @author codex + */ +@RestController +@RequestMapping("/sso/hub") +public class HubSsoController extends BaseController +{ + private static final Logger log = LoggerFactory.getLogger(HubSsoController.class); + + /** 发起跳转时在前端生成、由本接口消费的一次性 state 会话键 */ + private static final String SESSION_STATE_KEY = "HUB_SSO_STATE"; + + /** 人机校验开关,与登录页共用 {@code shiro.user.captchaEnabled} */ + @Value("${shiro.user.captchaEnabled:false}") + private boolean captchaEnabled; + + @Autowired + private HubLoginService hubLoginService; + + @Autowired + private HubProperties hubProperties; + + /** + * 免登开关与 hub 基地址,供前端决定是否显示门户入口、退出后跳去哪里。 + * + *

只暴露非敏感信息,绝不下发密钥。

+ */ + @Anonymous + @GetMapping("/status") + public AjaxResult status() + { + Map data = new HashMap<>(); + data.put("enabled", hubProperties.isConfigured()); + data.put("loginEnabled", hubProperties.isConfigured()); + data.put("hubHomeUrl", hubLoginService.getHubBaseUrl()); + data.put("logoutRedirectHub", hubLoginService.isLogoutRedirectHub()); + data.put("rejectBoundLocalLogin", hubLoginService.isRejectBoundLocalLogin()); + data.put("passwordLoginEnabled", hubLoginService.isPasswordLoginEnabled()); + return AjaxResult.success(data); + } + + /** + * 记录前端生成的 state,供验票时比对。 + */ + @Anonymous + @PostMapping("/state") + public AjaxResult prepareState(@RequestBody Map body, HttpSession session) + { + if (!hubProperties.isConfigured()) + { + return AjaxResult.error("统一登录未启用"); + } + String state = body == null ? null : body.get("state"); + if (state == null || state.trim().isEmpty() || state.length() > 64) + { + return AjaxResult.error("登录状态参数异常"); + } + session.setAttribute(SESSION_STATE_KEY, state.trim()); + return AjaxResult.success(); + } + + /** + * 用一次性票据换取本地会话。 + */ + @Anonymous + @PostMapping("/verify") + public AjaxResult verify(@RequestBody Map body, HttpSession session) + { + if (!hubProperties.isConfigured()) + { + return AjaxResult.error("统一登录未启用,请使用账号密码登录"); + } + String ticket = body == null ? null : body.get("ticket"); + String state = body == null ? null : body.get("state"); + String expectedState = session.getAttribute(SESSION_STATE_KEY) == null + ? null : String.valueOf(session.getAttribute(SESSION_STATE_KEY)); + // 一次性使用:无论成败都清掉,避免同一个 state 被反复提交 + session.removeAttribute(SESSION_STATE_KEY); + try + { + SysUser user = hubLoginService.loginByTicket(ticket, state, expectedState); + Map data = new HashMap<>(); + data.put("userId", user.getUserId()); + data.put("loginName", user.getLoginName()); + data.put("userName", user.getUserName()); + return AjaxResult.success(data); + } + catch (HubLoginException e) + { + // 只记登录名与结论,不记票据 + log.warn("hub 免登失败: {}", e.getMessage()); + return AjaxResult.error(e.getMessage()); + } + } + + /** + * 门户改密表单的口令要求(长度、字符类别等)。 + * + *

规则归门户的管理端系统参数,本系统不抄一份写死的 {@code 8..20}:抄了就会随管理员 + * 调参漂移(对接指南 2.7、11)。前端拿它渲染提示与前置校验,门户仍是最终裁判。

+ */ + @Anonymous + @GetMapping("/passwordPolicy") + public AjaxResult passwordPolicy() + { + Map data = new HashMap<>(); + data.put("requirements", hubLoginService.passwordRequirements()); + return AjaxResult.success(data); + } + + /** + * 已绑定门户的账号改口令:不跳转门户页面,由本系统收新口令后交给门户写入(对接指南 2.8.1)。 + * + *

两种进入方式共用这一个入口,差别只在「人是谁」怎么证明:

+ *
    + *
  • 已登录(个人中心改密码):身份由本系统会话给出,不需要人机校验。
  • + *
  • 未登录(登录页被 603 拦下):按账号找回已绑定的本地账号,并且必须过本系统 + * 那张验证码——门户的代校验/改密都不要图形码,明确要求人机校验由下游兜, + * 否则这里就成了可以无限次的口令字典(当前口令错一样计入门户的失败锁定)。
  • + *
+ * + *

改密成功不等于门户签发令牌:门户吊销的是它自己的刷新令牌,本系统会话不受影响 + * (对接指南 2.8.1)。未登录那条路改完就地建立本地会话,用户不必再输一次。

+ */ + @Anonymous + @PostMapping("/password") + public AjaxResult changePassword(@RequestBody Map body, HttpSession session) + { + // 只看总闸:改密自带当前口令证明,不该被「是否允许在 OMS 登录页直登」那个开关挡住, + // 否则管理员一关直登,内部人连改密码都改不了 + if (!hubLoginService.isEnabled()) + { + return AjaxResult.error("统一登录未启用,请使用本系统密码修改"); + } + // 两个口令都原样比对与提交,不做 trim:空格可以是口令的一部分(对接指南 2.8.1) + String newPassword = body == null ? null : body.get("newPassword"); + String confirmPassword = body == null ? null : body.get("confirmPassword"); + String currentPassword = body == null ? null : body.get("currentPassword"); + if (StringUtils.isEmpty(newPassword)) + { + return AjaxResult.error("请输入新密码"); + } + if (!newPassword.equals(confirmPassword)) + { + return AjaxResult.error("两次输入的新密码不一致"); + } + // 已登录=个人中心改密;未登录=登录页强制改密 + SysUser sessionUser = getSubjectUser(); + SysUser user = sessionUser; + boolean needSignIn = false; + if (sessionUser == null) + { + String account = trim(body.get("username")); + if (StringUtils.isEmpty(account)) + { + return AjaxResult.error("请输入账号"); + } + if (!verifyCaptcha(body.get("code"), session)) + { + return AjaxResult.error("验证码错误"); + } + user = hubLoginService.resolveBoundUser(account); + if (user == null) + { + // 未绑定门户的账号口令在本地,走原本的登录改密入口,不在这里代改 + return AjaxResult.error("该账号未绑定统一门户,请使用本系统的密码修改功能"); + } + needSignIn = true; + } + if (user.getHubUserId() == null) + { + return AjaxResult.error("该账号未绑定统一门户,请使用本系统的密码修改功能"); + } + + HubPasswordChangeResult result = hubLoginService.changePassword(user, currentPassword, newPassword); + if (result.isUnavailable()) + { + return AjaxResult.error(result.getMessage()); + } + if (!result.isChanged()) + { + // 门户已把「哪一条没过」翻译成中文原因,直接回给用户;规则要变化时前端重新读 /passwordPolicy + return AjaxResult.error(result.getMessage()); + } + if (needSignIn) + { + hubLoginService.signIn(user); + } + Map data = new HashMap<>(); + data.put("signedIn", needSignIn); + AjaxResult ok = AjaxResult.success("密码修改成功"); + ok.put(AjaxResult.DATA_TAG, data); + return ok; + } + + /** 当前会话里的人;未登录返回 null(本接口同时服务登录页与个人中心) */ + private SysUser getSubjectUser() + { + try + { + return getSysUser(); + } + catch (Exception e) + { + return null; + } + } + + /** + * 校验并消费本系统那张验证码,口径与 {@code CaptchaValidateFilter} 一致。 + * + *

本接口对门户是免密的,唯一的人机校验就是这里,漏掉等于让内部账号被无限次试口令。

+ */ + private boolean verifyCaptcha(String code, HttpSession session) + { + if (!captchaEnabled) + { + return true; + } + Object cached = session.getAttribute(Constants.KAPTCHA_SESSION_KEY); + // 一次性使用,防止同一张码反复提交 + session.removeAttribute(Constants.KAPTCHA_SESSION_KEY); + String expected = String.valueOf(cached != null ? cached : ""); + return StringUtils.isNotEmpty(code) && code.equalsIgnoreCase(expected); + } + + private String trim(String value) + { + return value == null ? null : value.trim(); + } +} diff --git a/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/controller/HubUserController.java b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/controller/HubUserController.java new file mode 100644 index 00000000..f7647455 --- /dev/null +++ b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/controller/HubUserController.java @@ -0,0 +1,165 @@ +package com.ruoyi.sip.hub.controller; + +import java.util.List; +import java.util.Map; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.page.TableDataInfo; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.sip.hub.domain.SysHubUser; +import com.ruoyi.sip.hub.service.IHubUserMirrorService; + +/** + * hub 人员目录(Vue 侧管理接口) + * + *

这个页面是自动匹配的兜底:同步按姓名唯一命中自动绑定,其余情况(重名、匹配不上、 + * hub 侧新增但缺登录名)都由管理员在此页人工绑定、新建并绑定、解绑或忽略。 + * 匹配错了也能在这里改,不必动数据库。

+ * + * @author codex + */ +@RestController +@RequestMapping("/system/hubSync/vue") +public class HubUserController extends BaseController +{ + @Autowired + private IHubUserMirrorService mirrorService; + + /** + * hub 人员目录列表 + */ + @RequiresPermissions("system:hubSync:list") + @GetMapping("/list") + public TableDataInfo list(SysHubUser query) + { + startPage(); + List list = mirrorService.selectHubUserList(query); + return getDataTable(list); + } + + /** + * 把 hub 人员绑定到指定本地账号 + */ + @RequiresPermissions("system:hubSync:bind") + @Log(title = "hub人员绑定", businessType = BusinessType.UPDATE) + @PostMapping("/bind") + public AjaxResult bind(@RequestBody Map body) + { + Long hubUserId = toLong(body == null ? null : body.get("hubUserId")); + Long localUserId = toLong(body == null ? null : body.get("localUserId")); + if (hubUserId == null || localUserId == null) + { + return AjaxResult.error("请选择门户人员与本地账号"); + } + return toAjax(mirrorService.bind(hubUserId, localUserId, getLoginName())); + } + + /** + * 为 hub 人员新建本地账号并绑定(初始密码取系统配置的默认密码) + */ + @RequiresPermissions("system:hubSync:create") + @Log(title = "hub人员新建并绑定", businessType = BusinessType.INSERT) + @PostMapping("/createBind") + public AjaxResult createBind(@RequestBody Map body) + { + Long hubUserId = toLong(body == null ? null : body.get("hubUserId")); + if (hubUserId == null) + { + return AjaxResult.error("缺少门户人员标识"); + } + Long userId = mirrorService.createAndBind(hubUserId, asText(body.get("loginName")), + asText(body.get("userName")), asText(body.get("phonenumber")), asText(body.get("email")), + getLoginName()); + return AjaxResult.success("创建成功", userId); + } + + /** + * 解绑:本地账号回到本系统口令登录 + */ + @RequiresPermissions("system:hubSync:unbind") + @Log(title = "hub人员解绑", businessType = BusinessType.UPDATE) + @PostMapping("/unbind") + public AjaxResult unbind(@RequestBody Map body) + { + Long localUserId = toLong(body == null ? null : body.get("localUserId")); + if (localUserId == null) + { + return AjaxResult.error("请选择要解绑的本地账号"); + } + return toAjax(mirrorService.unbind(localUserId, getLoginName())); + } + + /** + * 忽略一个门户人员:同步不再自动处理,也不放行门户密码登录 + */ + @RequiresPermissions("system:hubSync:ignore") + @Log(title = "hub人员忽略", businessType = BusinessType.UPDATE) + @PostMapping("/ignore") + public AjaxResult ignore(@RequestBody Map body) + { + Long hubUserId = toLong(body == null ? null : body.get("hubUserId")); + if (hubUserId == null) + { + return AjaxResult.error("缺少门户人员标识"); + } + return toAjax(mirrorService.ignore(hubUserId, asText(body.get("remark")), getLoginName())); + } + + /** + * 恢复处理一个被忽略的门户人员 + */ + @RequiresPermissions("system:hubSync:ignore") + @Log(title = "hub人员恢复处理", businessType = BusinessType.UPDATE) + @PostMapping("/restore") + public AjaxResult restore(@RequestBody Map body) + { + Long hubUserId = toLong(body == null ? null : body.get("hubUserId")); + if (hubUserId == null) + { + return AjaxResult.error("缺少门户人员标识"); + } + return toAjax(mirrorService.restore(hubUserId, getLoginName())); + } + + private Long toLong(Object value) + { + if (value == null) + { + return null; + } + if (value instanceof Number) + { + return ((Number) value).longValue(); + } + // 前端长整型可能以字符串回传(超出 JS 安全整数范围时会失真,这里只做原样转换) + String text = String.valueOf(value).trim(); + if (StringUtils.isEmpty(text)) + { + return null; + } + try + { + return Long.valueOf(text); + } + catch (NumberFormatException e) + { + return null; + } + } + + private String asText(Object value) + { + return value == null ? null : String.valueOf(value); + } +} diff --git a/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/domain/HubSyncResult.java b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/domain/HubSyncResult.java new file mode 100644 index 00000000..95340241 --- /dev/null +++ b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/domain/HubSyncResult.java @@ -0,0 +1,205 @@ +package com.ruoyi.sip.hub.domain; + +/** + * 一轮目录同步的结果摘要,供定时任务日志与「立即同步」接口回显。 + * + *

口径(ADR-0017):先镜像再决定动不动 {@code sys_user},因此计数分两组—— + * {@link #mirrored} 是「写进镜像表的人数」,{@link #bound} / {@link #created} 才是真正动了 + * {@code sys_user} 的人数。匹配不上又不属于增量新增的人只体现在 {@link #mirrored}, + * 这是设计意图,不是漏同步。

+ * + * @author codex + */ +public class HubSyncResult +{ + /** 本轮拉取到的目录人数 */ + private int fetched; + + /** 写入镜像表的人数(不代表都动了 sys_user) */ + private int mirrored; + + /** 已按 hub_user_id 命中并覆盖的本地账号数 */ + private int updated; + + /** 本轮完成自动绑定的本地存量账号数 */ + private int bound; + + /** 本轮新建的本地账号数(只来自 hub 侧新增的人) */ + private int created; + + /** 本轮停用的本地账号数 */ + private int deactivated; + + /** 进入/留在待确认清单的人数 */ + private int pending; + + /** 因管理员已忽略而跳过的人数 */ + private int skipped; + + /** 应用失败的条数(单条失败不影响同批其它人) */ + private int failed; + + /** 目录是否被 member_limit 截断;为 true 时本轮结果不完整,不能据此停用任何人 */ + private boolean truncated; + + /** 提交后的游标 */ + private long cursor; + + public int getFetched() + { + return fetched; + } + + public void setFetched(int fetched) + { + this.fetched = fetched; + } + + public int getMirrored() + { + return mirrored; + } + + public void increaseMirrored() + { + this.mirrored++; + } + + public int getUpdated() + { + return updated; + } + + public void increaseUpdated() + { + this.updated++; + } + + public int getBound() + { + return bound; + } + + public void increaseBound() + { + this.bound++; + } + + public int getCreated() + { + return created; + } + + public void increaseCreated() + { + this.created++; + } + + public int getDeactivated() + { + return deactivated; + } + + public void increaseDeactivated() + { + this.deactivated++; + } + + public void addDeactivated(int count) + { + this.deactivated += count; + } + + /** 累加一批的结果计数,供分批/分页落库后汇总 */ + public void mergeFrom(HubSyncResult other) + { + if (other == null) + { + return; + } + this.fetched += other.fetched; + this.mirrored += other.mirrored; + this.updated += other.updated; + this.bound += other.bound; + this.created += other.created; + this.deactivated += other.deactivated; + this.pending += other.pending; + this.skipped += other.skipped; + this.failed += other.failed; + if (other.truncated) + { + this.truncated = true; + } + } + + public int getPending() + { + return pending; + } + + public void increasePending() + { + this.pending++; + } + + public int getSkipped() + { + return skipped; + } + + public void increaseSkipped() + { + this.skipped++; + } + + public int getFailed() + { + return failed; + } + + + public void increaseFailed() + { + this.failed++; + } + + public boolean isTruncated() + { + return truncated; + } + + public void setTruncated(boolean truncated) + { + this.truncated = truncated; + } + + public long getCursor() + { + return cursor; + } + + public void setCursor(long cursor) + { + this.cursor = cursor; + } + + /** 一行可读摘要,进定时任务日志,不含个人信息与密钥 */ + public String summary() + { + StringBuilder sb = new StringBuilder(); + sb.append("拉取").append(fetched) + .append(" 镜像").append(mirrored) + .append(" 覆盖").append(updated) + .append(" 绑定").append(bound) + .append(" 新建").append(created) + .append(" 停用").append(deactivated) + .append(" 待确认").append(pending) + .append(" 已忽略跳过").append(skipped) + .append(" 失败").append(failed); + if (truncated) + { + sb.append(" [目录被截断,本轮结果不完整]"); + } + return sb.toString(); + } +} diff --git a/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/domain/SysHubUser.java b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/domain/SysHubUser.java new file mode 100644 index 00000000..d55ca3f8 --- /dev/null +++ b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/domain/SysHubUser.java @@ -0,0 +1,123 @@ +package com.ruoyi.sip.hub.domain; + +import java.util.Date; + +import com.ruoyi.common.core.domain.BaseEntity; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * hub 人员目录镜像对象 sys_hub_user + * + *

hub 通讯录在 OMS 侧的只读投影:同步先写这张表,再决定要不要动 {@code sys_user}。 + * 这样做的好处是「hub 有什么人」在 OMS 里可见可查,管理员人工绑定有依据,自动匹配错了 + * 也能在这里看到并修正,同时 {@code sys_user} 不会被 hub 全员灌入污染(ADR-0017)。

+ * + *

绑定关系只有 {@code sys_user.hub_user_id} 一处真相,本表不冗余存 local_user_id, + * 页面上的「已绑定账号」由 join 推导({@link #boundUserId} 等字段是查询产物,不可写)。

+ * + * @author codex + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class SysHubUser extends BaseEntity +{ + private static final long serialVersionUID = 1L; + + /** 在目录内(最近一次全量出现过) */ + public static final String PRESENT_YES = "1"; + + /** 已不在目录内(hub 删除或移出可见范围) */ + public static final String PRESENT_NO = "0"; + + /** 无需人工处理 */ + public static final String REVIEW_NONE = "0"; + + /** 待人工确认:同步无法自动落号 */ + public static final String REVIEW_PENDING = "1"; + + /** 已忽略:同步不再自动处理这个人 */ + public static final String REVIEW_IGNORED = "2"; + + /** 原因:本地存在同名账号,无法判定是哪一个 */ + public static final String REASON_DUPLICATE_NAME = "DUPLICATE_NAME"; + + /** 原因:hub 侧姓名为空,无法自动匹配 */ + public static final String REASON_NAME_EMPTY = "NAME_EMPTY"; + + /** 原因:建号需要登录名,但 hub 既没给手机号也没给可用账号 */ + public static final String REASON_CREATE_NO_LOGIN_NAME = "CREATE_NO_LOGIN_NAME"; + + /** 原因:推导出的登录名已被占用 */ + public static final String REASON_LOGIN_NAME_TAKEN = "LOGIN_NAME_TAKEN"; + + /** 原因:管理员解绑后待重新指派 */ + public static final String REASON_MANUAL_UNBOUND = "MANUAL_UNBOUND"; + + /** 原因:管理员忽略(与 review_status=2 同时写,便于列表直接展示) */ + public static final String REASON_MANUAL_IGNORED = "MANUAL_IGNORED"; + + /** hub 用户ID(主键,等同票据 sub) */ + private Long hubUserId; + + /** hub 登录账号(会随企业微信改名) */ + private String account; + + /** 企业微信 userid */ + private String wecomUserId; + + /** hub 姓名(自动绑定的唯一匹配键) */ + private String displayName; + + /** hub 邮箱 */ + private String email; + + /** hub 手机号(全量目录通常为空) */ + private String phone; + + /** hub 主组织ID */ + private Long orgId; + + /** hub 状态 0停用 1启用 2待审核 3已驳回 */ + private Integer hubStatus; + + /** 最近一次全量目录内是否存在(0否 1是) */ + private String present; + + /** 人工处理状态(0无需处理 1待人工确认 2已忽略) */ + private String reviewStatus; + + /** 待人工原因 */ + private String reviewReason; + + /** 人工处理备注 */ + private String reviewRemark; + + /** 首次同步到该人的时间 */ + private Date firstSeenTime; + + /** 最近一次在 hub 目录里出现的时间 */ + private Date lastSeenTime; + + /** 查询条件:门户账号/姓名/邮箱 模糊匹配 */ + private String keyword; + + /** 查询条件:1 只看已绑定,0 只看未绑定 */ + private String boundState; + + /** 查询产物:已绑定的本地用户ID */ + private Long boundUserId; + + /** 查询产物:已绑定的本地登录账号 */ + private String boundLoginName; + + /** 查询产物:已绑定的本地姓名 */ + private String boundUserName; + + /** hub 侧是否明确停用(摘要事件不带 status 时不得当作停用) */ + public boolean isKnownDisabled() + { + return hubStatus != null && hubStatus != 1; + } +} diff --git a/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/mapper/HubSyncStateMapper.java b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/mapper/HubSyncStateMapper.java new file mode 100644 index 00000000..9b27e763 --- /dev/null +++ b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/mapper/HubSyncStateMapper.java @@ -0,0 +1,40 @@ +package com.ruoyi.sip.hub.mapper; + +import org.apache.ibatis.annotations.Param; + +/** + * hub 目录同步状态(游标)访问接口 + * + *

游标单独存 sys_hub_sync_state 而不用 sys_config:ISysConfigService 读值走 ehcache, + * 同步任务写完再读会拿到旧缓存,导致游标倒退或重复应用。

+ * + * @author codex + */ +public interface HubSyncStateMapper +{ + /** 状态键:增量变更流游标 */ + public static final String KEY_DIRECTORY_CURSOR = "directory_cursor"; + + /** 状态键:目录 permission_version 快照 */ + public static final String KEY_PERMISSION_VERSION = "permission_version"; + + /** 状态键:1 表示下一轮必须先跑全量 */ + public static final String KEY_NEED_FULL_SYNC = "need_full_sync"; + + /** + * 读取状态值 + * + * @param stateKey 状态键 + * @return 状态值,键不存在时为 null + */ + public String selectStateValue(@Param("stateKey") String stateKey); + + /** + * 写入状态值(键不存在则插入,存在则覆盖) + * + * @param stateKey 状态键 + * @param stateValue 状态值 + * @return 结果 + */ + public int upsertState(@Param("stateKey") String stateKey, @Param("stateValue") String stateValue); +} diff --git a/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/mapper/SysHubUserMapper.java b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/mapper/SysHubUserMapper.java new file mode 100644 index 00000000..b127590a --- /dev/null +++ b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/mapper/SysHubUserMapper.java @@ -0,0 +1,107 @@ +package com.ruoyi.sip.hub.mapper; + +import java.util.List; + +import org.apache.ibatis.annotations.Param; + +import com.ruoyi.sip.hub.domain.SysHubUser; + +/** + * hub 人员目录镜像 Mapper 接口 + * + * @author codex + */ +public interface SysHubUserMapper +{ + /** + * 查询 hub 人员目录(带已绑定本地账号信息) + * + * @param hubUser 查询条件 + * @return 集合 + */ + public List selectHubUserList(SysHubUser hubUser); + + /** + * 按 hub 用户ID 查询单个镜像记录 + * + * @param hubUserId hub 用户ID + * @return 镜像记录,不存在时为 null + */ + public SysHubUser selectHubUserByHubUserId(Long hubUserId); + + /** + * 按统一门户账号或邮箱查镜像记录(可能多行,由调用方判唯一)。 + * + *

列的排序规则本身大小写不敏感,与 hub 的 {@code normalizeAccount}(转小写并去空格) + * 口径一致,因此这里直接等值匹配即可。

+ * + * @param account 门户账号或邮箱 + * @return 命中的镜像记录集合,正常为 0 或 1 行 + */ + public List selectHubUserByAccount(String account); + + /** + * 幂等写入一条镜像:按 hub_user_id 存在则覆盖资料列,不存在则插入 + * + * @param hubUser 镜像记录 + * @return 结果 + */ + public int upsertHubUser(SysHubUser hubUser); + + /** + * 全量开始时把所有人标记为「本目录未出现」,随后每个被 upsert 的人重新置回存在。 + * + *

必须先确认目录完整(未截断且非空)才允许调用,否则会把没返回的人误判为已离开。

+ * + * @return 结果 + */ + public int markAllAbsent(); + + /** + * 增量 delete 事件:把单个人员标记为「已不在目录」,与全量收尾的判定口径一致 + * + * @param hubUserId hub 用户ID + * @return 结果 + */ + public int markAbsent(@Param("hubUserId") Long hubUserId); + + /** + * 更新人工处理状态(忽略 / 恢复 / 待确认原因) + * + * @param hubUserId hub 用户ID + * @param reviewStatus 处理状态 + * @param reviewReason 原因 + * @param reviewRemark 备注 + * @param updateBy 操作人 + * @return 结果 + */ + public int updateReview(@Param("hubUserId") Long hubUserId, @Param("reviewStatus") String reviewStatus, + @Param("reviewReason") String reviewReason, @Param("reviewRemark") String reviewRemark, + @Param("updateBy") String updateBy); + + /** + * 同步置「待人工确认」:已被管理员忽略的人不会被改回去,避免忽略后又冒出来 + * + * @param hubUserId hub 用户ID + * @param reviewReason 原因 + * @return 结果 + */ + public int markReviewIfNotIgnored(@Param("hubUserId") Long hubUserId, @Param("reviewReason") String reviewReason); + + /** + * 同步清理「待人工确认」:这个人已经绑上号(自动或人工)后不再提示,已忽略的保持忽略 + * + * @param hubUserId hub 用户ID + * @return 结果 + */ + public int clearReview(@Param("hubUserId") Long hubUserId); + + /** + * 全量收尾用:本轮目录里没出现(present='0')且仍绑定着本地账号的 hub 用户ID。 + * + *

只取已绑定的,未绑定的人本来就没进 OMS,不需要停用任何账号。

+ * + * @return hub 用户ID列表 + */ + public List selectAbsentBoundHubUserIds(); +} diff --git a/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/IHubDirectorySyncService.java b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/IHubDirectorySyncService.java new file mode 100644 index 00000000..6ad5a0d9 --- /dev/null +++ b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/IHubDirectorySyncService.java @@ -0,0 +1,29 @@ +package com.ruoyi.sip.hub.service; + +import com.ruoyi.sip.hub.domain.HubSyncResult; + +/** + * hub 用户与组织目录同步服务(单向:hub 为权威源,OMS 只读镜像,不回写) + * + * @author codex + */ +public interface IHubDirectorySyncService +{ + /** + * 全量同步:拉取整棵目录并镜像覆盖,收尾停用「hub 已不再返回」的账号, + * 完成后把游标对齐到 hub 当前流水末端。 + * + * @return 结果摘要;hub 未启用时返回空结果 + */ + public HubSyncResult fullSync(); + + /** + * 增量同步:按游标拉取变更流,循环到 {@code has_more=false} 才推进游标。 + * + *

下列情况一律转全量:需要全量标记未清、游标落后于流水 oldest_seq、 + * 收到组织状态或父子变更事件。

+ * + * @return 结果摘要;hub 未启用时返回空结果 + */ + public HubSyncResult incrementalSync(); +} diff --git a/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/IHubUserMirrorService.java b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/IHubUserMirrorService.java new file mode 100644 index 00000000..abcc3525 --- /dev/null +++ b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/IHubUserMirrorService.java @@ -0,0 +1,116 @@ +package com.ruoyi.sip.hub.service; + +import java.util.List; + +import com.alibaba.fastjson.JSONObject; +import com.ruoyi.framework.hub.HubDirectoryUser; +import com.ruoyi.sip.hub.domain.HubSyncResult; +import com.ruoyi.sip.hub.domain.SysHubUser; + +/** + * hub 人员目录镜像与绑定服务(事务边界在这一层,远程调用全部在调用方完成) + * + *

口径(ADR-0017):hub 目录先原样镜像到 {@code sys_hub_user},再按「姓名唯一命中」 + * 尝试把 {@code sys_user.hub_user_id} 绑上。全量匹配不上的人不建号也不打扰, + * 只留在镜像表;只有 hub 侧新增(增量事件)的人才自动建号并绑定。

+ * + * @author codex + */ +public interface IHubUserMirrorService +{ + /** + * 全量开始前复位在场标记:把镜像里所有人置为「本轮未出现」, + * 本轮 upsert 过的人会被重新置回在场,剩下的就是已离开的。 + * + *

只能在确认目录完整(未截断)时调用。

+ * + * @return 影响行数 + */ + public int resetPresence(); + + /** + * 应用一批目录成员。 + * + * @param users 目录成员 + * @param fullPass 是否全量轮次:全量只镜像 + 自动绑定,不建号;增量才建号 + * @return 结果摘要 + */ + public HubSyncResult applyUsers(List users, boolean fullPass); + + /** + * 应用一批增量变更事件。 + * + * @param changes hub 原始事件(payload 字段名随来源变化) + * @return 结果摘要 + */ + public HubSyncResult applyChanges(List changes); + + /** + * 全量收尾:把「hub 已不再返回」且仍绑定的本地账号置为停用,并统计离开人数。 + * + *

目录被截断时不得调用,否则会把「没返回」误判成「人已离开」。

+ * + * @return 停用的本地账号数 + */ + public int deactivateAbsent(); + + /** + * 查询 hub 人员目录(含已绑定的本地账号) + * + * @param query 查询条件 + * @return 集合 + */ + public List selectHubUserList(SysHubUser query); + + /** + * 人工把 hub 人员绑定到指定本地账号 + * + * @param hubUserId hub 用户ID + * @param localUserId 本地账号ID + * @param operName 操作人 + * @return 结果 + */ + public int bind(Long hubUserId, Long localUserId, String operName); + + /** + * 人工为 hub 人员新建本地账号并绑定(初始密码取系统配置的默认密码) + * + * @param hubUserId hub 用户ID + * @param loginName 本地登录账号(OMS 侧一般是手机号) + * @param userName 本地姓名 + * @param phonenumber 手机号,可空 + * @param email 邮箱,可空 + * @param operName 操作人 + * @return 新建的本地账号ID + */ + public Long createAndBind(Long hubUserId, String loginName, String userName, String phonenumber, + String email, String operName); + + /** + * 解除本地账号与 hub 的绑定,该账号回到本地口令登录 + * + * @param localUserId 本地账号ID + * @param operName 操作人 + * @return 结果 + */ + public int unbind(Long localUserId, String operName); + + /** + * 忽略一个 hub 人员:同步不再自动处理这个人,也不放行门户直登 + * + * @param hubUserId hub 用户ID + * @param remark 备注,可空 + * @param operName 操作人 + * @return 结果 + */ + public int ignore(Long hubUserId, String remark, String operName); + + /** + * 恢复处理一个被忽略的 hub 人员 + * + * @param hubUserId hub 用户ID + * @param operName 操作人 + * @return 结果 + */ + public int restore(Long hubUserId, String operName); +} diff --git a/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/impl/HubAccountLookupImpl.java b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/impl/HubAccountLookupImpl.java new file mode 100644 index 00000000..bda52ff5 --- /dev/null +++ b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/impl/HubAccountLookupImpl.java @@ -0,0 +1,69 @@ +package com.ruoyi.sip.hub.service.impl; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.framework.hub.HubAccountLookup; +import com.ruoyi.framework.hub.HubAccountView; +import com.ruoyi.sip.hub.domain.SysHubUser; +import com.ruoyi.sip.hub.mapper.SysHubUserMapper; + +/** + * 从 hub 人员目录镜像取门户账号信息,供 OMS 代理门户密码登录使用。 + * + *

为什么必须走镜像而不是 {@code sys_user}:内部人员在 OMS 登录页输入的是统一门户账号, + * 而 hub 只认它自己的 {@code account}(或邮箱),OMS 的 {@code login_name} 与它不同源 + * (历史数据里存的是手机号或域账号),两个方向的换算都只有目录镜像能提供依据。

+ * + * @author codex + */ +@Service +public class HubAccountLookupImpl implements HubAccountLookup +{ + @Autowired + private SysHubUserMapper hubUserMapper; + + @Override + public HubAccountView findByHubUserId(Long hubUserId) + { + if (hubUserId == null) + { + return null; + } + return toView(hubUserMapper.selectHubUserByHubUserId(hubUserId)); + } + + @Override + public HubAccountView findByAccount(String account) + { + if (StringUtils.isEmpty(account)) + { + return null; + } + List hits = hubUserMapper.selectHubUserByAccount(account.trim()); + if (hits.size() != 1) + { + // 同号多人(例如两个人共用一个邮箱)不猜:认错了人等于把别人的身份给这个人 + return null; + } + return toView(hits.get(0)); + } + + private HubAccountView toView(SysHubUser mirror) + { + if (mirror == null) + { + return null; + } + HubAccountView view = new HubAccountView(); + view.setHubUserId(mirror.getHubUserId()); + view.setAccount(mirror.getAccount()); + view.setEmail(mirror.getEmail()); + view.setDisplayName(mirror.getDisplayName()); + view.setIgnored(SysHubUser.REVIEW_IGNORED.equals(mirror.getReviewStatus())); + return view; + } +} diff --git a/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/impl/HubDirectorySyncServiceImpl.java b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/impl/HubDirectorySyncServiceImpl.java new file mode 100644 index 00000000..f90abe1e --- /dev/null +++ b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/impl/HubDirectorySyncServiceImpl.java @@ -0,0 +1,289 @@ +package com.ruoyi.sip.hub.service.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.ruoyi.framework.hub.HubChangesResult; +import com.ruoyi.framework.hub.HubClient; +import com.ruoyi.framework.hub.HubDirectoryResult; +import com.ruoyi.framework.hub.HubDirectoryUser; +import com.ruoyi.framework.hub.HubException; +import com.ruoyi.framework.hub.HubProperties; +import com.ruoyi.sip.hub.domain.HubSyncResult; +import com.ruoyi.sip.hub.mapper.HubSyncStateMapper; +import com.ruoyi.sip.hub.service.IHubDirectorySyncService; +import com.ruoyi.sip.hub.service.IHubUserMirrorService; + +/** + * hub 目录同步编排实现。 + * + *

分层原则:本类只做「远程调用 + 游标推进」,落库交给 {@link IHubUserMirrorService} 的事务方法, + * 因此事务内不出现 HTTP 调用(后端规范要求事务内不做远程调用)。

+ * + *

全量与增量的职责差别(ADR-0017):全量只镜像 + 按姓名自动绑定,不建号, + * 匹配不上的人留在镜像表由管理员处理;增量里出现的「镜像中没有的人」视为 hub 侧新增, + * 才自动建号并绑定。

+ * + *

对应 hub 对接指南 10.3 推荐流程:首次/每日全量 → {@link #fullSync()};固定周期增量 → + * {@link #incrementalSync()};「差异一律以全量为准」「幂等应用」「组织状态与父子变更触发全量」 + * 「游标落后过多转全量」均在增量分支落地。

+ * + * @author codex + */ +@Service +public class HubDirectorySyncServiceImpl implements IHubDirectorySyncService +{ + private static final Logger log = LoggerFactory.getLogger(HubDirectorySyncServiceImpl.class); + + /** 单次事务落库人数,控制事务时长,避免整棵目录压在一个事务里 */ + private static final int APPLY_BATCH_SIZE = 200; + + /** hub 侧 member_limit 上限 */ + private static final int MEMBER_LIMIT_MAX = 5000; + + /** 单轮增量最多翻页次数,防止流水异常时死循环 */ + private static final int MAX_CHANGE_PAGES = 200; + + @Autowired + private HubClient hubClient; + + @Autowired + private HubProperties properties; + + @Autowired + private HubSyncStateMapper stateMapper; + + @Autowired + private IHubUserMirrorService mirrorService; + + @Override + public HubSyncResult fullSync() + { + HubSyncResult total = new HubSyncResult(); + if (!syncEnabled()) + { + return total; + } + long started = System.currentTimeMillis(); + int limit = properties.getDirectory().getMemberLimit(); + // 必须在拉快照之前取流水水位:快照之后的事件若被对齐掉,本地要等到次日全量才纠正。 + // 先取水位再拉目录,最坏情况是把已包含在快照里的事件重放一遍(落库按 hub_user_id 幂等)。 + long highWater = probeNewestSeq(); + HubDirectoryResult directory; + try + { + directory = hubClient.fetchDirectory(limit); + if (directory.isTruncated() && limit < MEMBER_LIMIT_MAX) + { + log.warn("hub 目录在 member_limit={} 下被截断,按上限 {} 重拉", limit, MEMBER_LIMIT_MAX); + directory = hubClient.fetchDirectory(MEMBER_LIMIT_MAX); + } + } + catch (HubException e) + { + total.increaseFailed(); + log.error("hub 目录全量拉取失败, 原因={}", e.getMessage()); + return total; + } + + List users = directory.getUsers(); + // 先复位在场标记再逐批写回:本轮没被 upsert 到的人自然留在 present='0', + // 这就是「hub 已不再返回这个人」的判定依据,比在内存里攒一份 id 集合更省内存 + boolean presenceReset = false; + if (!directory.isTruncated() && !users.isEmpty()) + { + mirrorService.resetPresence(); + presenceReset = true; + } + for (int from = 0; from < users.size(); from += APPLY_BATCH_SIZE) + { + List batch = + new ArrayList<>(users.subList(from, Math.min(from + APPLY_BATCH_SIZE, users.size()))); + total.mergeFrom(mirrorService.applyUsers(batch, true)); + } + total.setTruncated(directory.isTruncated()); + if (!directory.isTruncated()) + { + // 只有拿到完整目录才允许做「hub 已不再返回」的停用判定,截断时会误停用一大批人。 + // 空目录同样不能启用该判定:hub 异常返回空列表会把全部已绑定账号一次性停用, + // 表现是「所有人突然都进不来」,宁可等下一轮全量再纠正。 + if (users.isEmpty()) + { + log.error("hub 目录返回 0 人,跳过停用判定(疑似 hub 侧异常),请核对门户通讯录"); + } + else + { + total.addDeactivated(mirrorService.deactivateAbsent()); + } + } + else + { + log.error("hub 目录被截断(total={}, returned={}),本轮跳过停用判定," + + "请提高 hub.directory.member-limit", directory.getTotalUsers(), directory.getReturnedUsers()); + } + if (!presenceReset && !directory.isTruncated() && !users.isEmpty()) + { + // 理论上不会走到这里(复位条件与停用条件一致),留一条日志防止将来改动引入漏判 + log.warn("本轮全量未复位在场标记,停用判定已跳过"); + } + stateMapper.upsertState(HubSyncStateMapper.KEY_PERMISSION_VERSION, + String.valueOf(directory.getPermissionVersion())); + saveCursorAfterFullSync(total, highWater); + stateMapper.upsertState(HubSyncStateMapper.KEY_NEED_FULL_SYNC, "0"); + log.info("hub 目录全量同步完成, 目录人数={}, 耗时={}ms, {}", users.size(), + System.currentTimeMillis() - started, total.summary()); + return total; + } + + @Override + public HubSyncResult incrementalSync() + { + HubSyncResult total = new HubSyncResult(); + if (!syncEnabled()) + { + return total; + } + // 标记行缺失时按「需要全量」处理,宁可多跑一次全量 + String needFull = stateMapper.selectStateValue(HubSyncStateMapper.KEY_NEED_FULL_SYNC); + if (needFull == null || "1".equals(needFull)) + { + log.info("hub 同步存在全量标记,本轮改走全量"); + return fullSync(); + } + long cursor = parseLong(stateMapper.selectStateValue(HubSyncStateMapper.KEY_DIRECTORY_CURSOR), 0L); + total.setCursor(cursor); + int pages = 0; + while (pages++ < MAX_CHANGE_PAGES) + { + HubChangesResult changes; + try + { + changes = hubClient.fetchChanges(cursor, properties.getDirectory().getChangeLimit()); + } + catch (HubException e) + { + log.error("hub 增量拉取失败, cursor={}, 原因={}", cursor, e.getMessage()); + return total; + } + // 游标落后于流水保留范围:中间事件已不可靠,必须全量重建 + if (changes.getOldestSeq() > 0 && cursor < changes.getOldestSeq()) + { + log.warn("hub 增量游标落后过多, cursor={}, oldest_seq={},转全量重建", + cursor, changes.getOldestSeq()); + return rerunFullSync(); + } + if (changes.isOrgStructureChanged()) + { + // 组织状态/移动事件不带 path、不级联子树,无法据此推导父子关系 + log.info("hub 增量包含组织状态或父子变更,转全量重建"); + return rerunFullSync(); + } + // 组织事件是否需要全量重建只由上面 changes.isOrgStructureChanged() 判定: + // 它只认「带 parent_id 或 status 的摘要事件」,而普通的组织改名不该触发重建 + // (hub 每轮企业微信同步都会重放组织 upsert,改名很常见)。 + total.mergeFrom(mirrorService.applyChanges(changes.getChanges())); + // 同一批应用成功才推进游标;抛异常的批次留在下一轮重放(落库幂等) + if (changes.getCursor() > cursor) + { + cursor = changes.getCursor(); + stateMapper.upsertState(HubSyncStateMapper.KEY_DIRECTORY_CURSOR, String.valueOf(cursor)); + } + total.setCursor(cursor); + if (!changes.isHasMore()) + { + if (total.getFetched() > 0) + { + log.info("hub 目录增量同步完成, cursor={}, {}", cursor, total.summary()); + } + return total; + } + } + log.warn("hub 增量单轮翻页达到上限 {},剩余变更留待下一轮", MAX_CHANGE_PAGES); + return total; + } + + /** 增量中发现必须全量的信号:置标记后走全量,全量结束会清标记并对齐游标 */ + private HubSyncResult rerunFullSync() + { + stateMapper.upsertState(HubSyncStateMapper.KEY_NEED_FULL_SYNC, "1"); + return fullSync(); + } + + /** + * 全量落库后写入游标。 + * + *

取快照前探到的水位({@code highWater}):它一定不大于快照覆盖的位置, + * 因此其后的事件都会被下一轮增量重放到,不会跳过。

+ * + *

探查失败({@code highWater <= 0})时退回「取快照后再探一次」,此时快照与探查之间 + * 的事件可能被跳过,但每日全量会兜住,属可接受的降级;不保留原游标是因为原游标可能 + * 远落后于流水,会让下一轮增量白翻很多页。

+ */ + private void saveCursorAfterFullSync(HubSyncResult total, long highWater) + { + long cursor = highWater; + if (cursor <= 0) + { + cursor = probeNewestSeq(); + if (cursor > 0) + { + log.warn("全量前未取到流水水位,退回全量后水位 {},其间事件等下次全量纠正", cursor); + } + } + if (cursor > 0) + { + stateMapper.upsertState(HubSyncStateMapper.KEY_DIRECTORY_CURSOR, String.valueOf(cursor)); + total.setCursor(cursor); + } + } + + /** 探查 hub 变更流水当前末端,失败返回 0(不抛异常,避免影响已完成的全量落库) */ + private long probeNewestSeq() + { + try + { + return hubClient.fetchChanges(0L, 1).getNewestSeq(); + } + catch (HubException e) + { + log.warn("探查 hub 流水水位失败, 原因={}", e.getMessage()); + return 0L; + } + } + + private boolean syncEnabled() + { + if (!properties.isConfigured()) + { + log.debug("hub 未启用或配置不完整,跳过目录同步"); + return false; + } + if (!properties.getDirectory().isEnabled()) + { + log.debug("hub.directory.enabled=false,跳过目录同步"); + return false; + } + return true; + } + + private long parseLong(String raw, long fallback) + { + if (raw == null || raw.trim().isEmpty()) + { + return fallback; + } + try + { + return Long.parseLong(raw.trim()); + } + catch (NumberFormatException e) + { + return fallback; + } + } +} diff --git a/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/impl/HubUserMirrorServiceImpl.java b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/impl/HubUserMirrorServiceImpl.java new file mode 100644 index 00000000..555cec74 --- /dev/null +++ b/ruoyi-sip/src/main/java/com/ruoyi/sip/hub/service/impl/HubUserMirrorServiceImpl.java @@ -0,0 +1,666 @@ +package com.ruoyi.sip.hub.service.impl; + +import java.util.Date; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.alibaba.fastjson.JSONObject; +import com.ruoyi.common.constant.UserConstants; +import com.ruoyi.common.core.domain.entity.SysUser; +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.common.utils.ShiroUtils; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.framework.hub.HubDirectoryUser; +import com.ruoyi.framework.hub.HubProperties; +import com.ruoyi.framework.shiro.service.SysPasswordService; +import com.ruoyi.sip.hub.domain.HubSyncResult; +import com.ruoyi.sip.hub.domain.SysHubUser; +import com.ruoyi.sip.hub.mapper.SysHubUserMapper; +import com.ruoyi.sip.hub.service.IHubUserMirrorService; +import com.ruoyi.system.mapper.SysUserMapper; +import com.ruoyi.system.service.ISysConfigService; + +/** + * hub 人员目录镜像与绑定实现。 + * + *

两步走(ADR-0017):① 每个人先原样写进 {@code sys_hub_user} 镜像;② 再决定要不要动 + * {@code sys_user}。第 ② 步的自动动作只有两种——姓名唯一命中就绑定,hub 侧新增的人就建号; + * 全量里既没绑定又不属于新增的人一律不打扰,留在镜像表等管理员处理。

+ * + *

自动匹配只认姓名(OMS 的 {@code login_name} 存手机号,hub 全量目录不下发手机号, + * 姓名是唯一两边都稳定有值的东西)。命中多行等于匹配失败:同名不同人很常见, + * 绑错人的后果是内部人拿到别人的单据可见范围,宁可留给人工。

+ * + *

覆盖范围克制:同步不改 {@code login_name}(业务表 {@code create_by} 存登录名, + * 改名会打断历史单据归属)、不改 {@code dept_id}、不碰角色(ADR-0016 的授权仍由管理员手动完成)。

+ * + * @author codex + */ +@Service +public class HubUserMirrorServiceImpl implements IHubUserMirrorService +{ + private static final Logger log = LoggerFactory.getLogger(HubUserMirrorServiceImpl.class); + + /** 同步写入的操作人标记,便于与人工维护的账号区分 */ + private static final String SYNC_OPERATOR = "hub-sync"; + + /** 人工建号时使用的初始密码配置项,与「系统管理 > 用户管理 > 新增」同源 */ + private static final String CONFIG_INIT_PASSWORD = "sys.user.initPassword"; + + /** sys_user 列长度上限,超出必须裁剪,否则整条同步直接报错 */ + private static final int LOGIN_NAME_MAX = 30; + + private static final int USER_NAME_MAX = 30; + + private static final int EMAIL_MAX = 50; + + private static final int PHONENUMBER_MAX = 11; + + @Autowired + private SysUserMapper userMapper; + + @Autowired + private SysHubUserMapper hubUserMapper; + + @Autowired + private HubProperties properties; + + @Autowired + private SysPasswordService passwordService; + + @Autowired + private ISysConfigService configService; + + @Override + @Transactional(rollbackFor = Exception.class) + public int resetPresence() + { + return hubUserMapper.markAllAbsent(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public HubSyncResult applyUsers(List users, boolean fullPass) + { + HubSyncResult result = new HubSyncResult(); + if (users == null || users.isEmpty()) + { + return result; + } + result.setFetched(users.size()); + for (HubDirectoryUser hubUser : users) + { + try + { + applyOne(hubUser, fullPass, result); + } + catch (Exception e) + { + // 单条失败不影响同批其它人;是否整体回滚由调用方决定 + result.increaseFailed(); + log.error("hub 目录落库失败, hubUserId={}, 原因={}", hubUser.getUserId(), e.getMessage()); + } + } + return result; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public HubSyncResult applyChanges(List changes) + { + HubSyncResult result = new HubSyncResult(); + if (changes == null || changes.isEmpty()) + { + return result; + } + result.setFetched(changes.size()); + for (JSONObject change : changes) + { + try + { + applyChange(change, result); + } + catch (Exception e) + { + result.increaseFailed(); + log.error("hub 增量事件应用失败, seq={}, 原因={}", change.getLong("seq"), e.getMessage()); + } + } + return result; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public int deactivateAbsent() + { + if (!properties.getDirectory().isDisableMissing()) + { + return 0; + } + int count = 0; + List absentIds = hubUserMapper.selectAbsentBoundHubUserIds(); + for (Long hubUserId : absentIds) + { + count += userMapper.deactivateUserByHubUserId(hubUserId); + } + return count; + } + + @Override + public List selectHubUserList(SysHubUser query) + { + return hubUserMapper.selectHubUserList(query == null ? new SysHubUser() : query); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public int bind(Long hubUserId, Long localUserId, String operName) + { + SysHubUser mirror = requireMirror(hubUserId); + if (localUserId == null) + { + throw new ServiceException("请选择要绑定的本地账号"); + } + SysUser local = userMapper.selectUserById(localUserId); + if (local == null) + { + throw new ServiceException("本地账号不存在"); + } + if (local.getHubUserId() != null && !local.getHubUserId().equals(hubUserId)) + { + throw new ServiceException( + "该本地账号已绑定门户ID " + local.getHubUserId() + ",请先解绑"); + } + SysUser occupied = userMapper.selectUserByHubUserId(hubUserId); + if (occupied != null && !occupied.getUserId().equals(localUserId)) + { + throw new ServiceException( + "门户账号已绑定到「" + occupied.getLoginName() + "」,请先解绑"); + } + + SysUser patch = new SysUser(); + patch.setUserId(localUserId); + patch.setHubUserId(hubUserId); + // 人工绑定只建立映射:不改姓名、不改登录名、不碰角色,管理员要改资料另走用户管理 + patch.setUpdateBy(operaNameSafe(operName)); + userMapper.bindUserToHub(patch); + hubUserMapper.clearReview(mirror.getHubUserId()); + return 1; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public Long createAndBind(Long hubUserId, String loginName, String userName, String phonenumber, + String email, String operName) + { + SysHubUser mirror = requireMirror(hubUserId); + String account = trimTo(loginName, LOGIN_NAME_MAX); + if (StringUtils.isEmpty(account)) + { + throw new ServiceException("登录账号不能为空"); + } + if (StringUtils.isEmpty(trimTo(userName, USER_NAME_MAX))) + { + throw new ServiceException("用户姓名不能为空"); + } + SysUser duplicated = userMapper.checkLoginNameUnique(account); + if (duplicated != null) + { + throw new ServiceException("登录账号「" + account + "」已存在"); + } + String phone = normalizePhone(phonenumber); + if (StringUtils.isNotEmpty(phone) && userMapper.checkPhoneUnique(phone) != null) + { + throw new ServiceException("手机号「" + phone + "」已存在"); + } + String mail = trimTo(email, EMAIL_MAX); + if (StringUtils.isNotEmpty(mail) && userMapper.checkEmailUnique(mail) != null) + { + throw new ServiceException("邮箱「" + mail + "」已存在"); + } + + SysUser user = new SysUser(); + user.setLoginName(account); + user.setUserName(trimTo(userName, USER_NAME_MAX)); + user.setUserType(UserConstants.SYSTEM_USER_TYPE); + user.setHubUserId(mirror.getHubUserId()); + user.setHubSyncTime(new Date()); + if (StringUtils.isNotEmpty(mail)) + { + user.setEmail(mail); + } + if (StringUtils.isNotEmpty(phone)) + { + user.setPhonenumber(phone); + } + user.setStatus(UserConstants.NORMAL); + applyInitPassword(user); + user.setCreateBy(operaNameSafe(operName)); + user.setRemark("统一门户人员创建"); + userMapper.insertUser(user); + hubUserMapper.clearReview(mirror.getHubUserId()); + return user.getUserId(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public int unbind(Long localUserId, String operName) + { + if (localUserId == null) + { + throw new ServiceException("请选择要解绑的本地账号"); + } + SysUser local = userMapper.selectUserById(localUserId); + if (local == null) + { + throw new ServiceException("本地账号不存在"); + } + if (local.getHubUserId() == null) + { + throw new ServiceException("该账号未绑定统一门户账号"); + } + Long hubUserId = local.getHubUserId(); + int rows = userMapper.unbindHubByUserId(localUserId); + // 解绑后把这个人退回「待人工确认」,否则下一轮全量会又按姓名把他绑回去 + hubUserMapper.updateReview(hubUserId, SysHubUser.REVIEW_PENDING, SysHubUser.REASON_MANUAL_UNBOUND, + "管理员解绑:" + local.getLoginName(), operaNameSafe(operName)); + return rows; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public int ignore(Long hubUserId, String remark, String operName) + { + requireMirror(hubUserId); + return hubUserMapper.updateReview(hubUserId, SysHubUser.REVIEW_IGNORED, + SysHubUser.REASON_MANUAL_IGNORED, trimTo(remark, 500), operaNameSafe(operName)); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public int restore(Long hubUserId, String operName) + { + requireMirror(hubUserId); + return hubUserMapper.updateReview(hubUserId, SysHubUser.REVIEW_PENDING, null, null, + operaNameSafe(operName)); + } + + /** + * 单个人的一轮处理:先镜像,再决定动不动 sys_user。 + */ + private void applyOne(HubDirectoryUser hubUser, boolean fullPass, HubSyncResult result) + { + if (hubUser.getUserId() == null) + { + result.increaseFailed(); + return; + } + SysHubUser before = hubUserMapper.selectHubUserByHubUserId(hubUser.getUserId()); + boolean known = before != null; + boolean ignored = known && SysHubUser.REVIEW_IGNORED.equals(before.getReviewStatus()); + // 管理员解绑过的人:不再按姓名自动绑回去,否则「解绑 → 下一轮又绑上」会反复拉锯, + // 解绑这个动作等于没生效。留在待人工队列,由管理员显式绑定或忽略来结束。 + boolean manualUnbound = known + && SysHubUser.REASON_MANUAL_UNBOUND.equals(before.getReviewReason()); + + mirror(hubUser, before, result); + if (ignored) + { + // 管理员已决定「这个人不进 OMS」,同步只更新资料,不再自动绑定或建号 + result.increaseSkipped(); + return; + } + if (manualUnbound) + { + result.increaseSkipped(); + return; + } + + // 增量摘要事件只带被改的那一两个字段,其余是空值。这里用镜像里的现值补齐本次处理, + // 否则「姓名没在事件里」会被误判成 NAME_EMPTY,建号时也拿不到姓名与手机号。 + enrichFromMirror(hubUser, before); + + SysUser bound = userMapper.selectUserByHubUserId(hubUser.getUserId()); + if (bound != null) + { + // 已绑定:只覆盖同步字段,认人键不再变化,hub 改名也不影响(ADR-0015) + userMapper.bindUserToHub(buildPatch(bound.getUserId(), hubUser)); + hubUserMapper.clearReview(hubUser.getUserId()); + result.increaseUpdated(); + return; + } + + String name = trimTo(hubUser.getDisplayName(), USER_NAME_MAX); + if (StringUtils.isEmpty(name)) + { + // 没有姓名就没有匹配键,也无法建号后让人认出是谁,必须人工补 + hubUserMapper.markReviewIfNotIgnored(hubUser.getUserId(), SysHubUser.REASON_NAME_EMPTY); + result.increasePending(); + return; + } + if (properties.getDirectory().isAutoBindByName()) + { + List hits = userMapper.selectUnboundByUserName(name); + if (hits.size() == 1) + { + userMapper.bindUserToHub(buildPatch(hits.get(0).getUserId(), hubUser)); + hubUserMapper.clearReview(hubUser.getUserId()); + result.increaseBound(); + return; + } + if (hits.size() > 1) + { + // 重名:绑错人比不绑更糟,留给人工在目录页挑 + hubUserMapper.markReviewIfNotIgnored(hubUser.getUserId(), SysHubUser.REASON_DUPLICATE_NAME); + result.increasePending(); + return; + } + } + + // 到这里就是「镜像里有、sys_user 里没有对应账号」 + if (fullPass || !properties.getDirectory().isAutoCreateNew()) + { + // 全量不建号(ADR-0017):匹配不上只说明「这个人不在 OMS 用」,不是异常, + // 因此不置待处理标记(否则几百号人全冒出来),管理员用「未绑定」筛选即可全捞。 + // 真正需要盯的只有重名(上面已置 DUPLICATE_NAME)与增量建号失败两种。 + return; + } + String createFailure = createUserFromHub(hubUser); + if (createFailure == null) + { + hubUserMapper.clearReview(hubUser.getUserId()); + result.increaseCreated(); + return; + } + // 建号条件不足(没有可用登录名、登录名已被占用)交人工,不静默丢弃 + hubUserMapper.markReviewIfNotIgnored(hubUser.getUserId(), createFailure); + result.increasePending(); + } + + /** + * 处理一条增量事件。 + * + *

hub 侧已知坑:同一含义两个键名——{@code source=wecom} 带完整用户对象({@code id}), + * {@code source=hub} 的摘要事件只带被改的那一两个字段,因此缺字段一律不覆盖本地值, + * 也不允许把「没带 status」当成「人已停用」(见 {@link HubDirectoryUser#isKnownDisabled()})。

+ */ + private void applyChange(JSONObject change, HubSyncResult result) + { + String entity = change.getString("entity"); + String op = change.getString("op"); + + if ("organization".equals(entity)) + { + // 一期不同步组织,人员落库也不依赖组织事件,直接跳过。 + // 「要不要转全量重建」由编排层按 HubChangesResult.isOrgStructureChanged() 判定, + // 它只认带 parent_id / status 的摘要事件;在这里对每个组织事件都置标记会让 + // 普通的组织改名(hub 每轮企业微信同步都会重放组织 upsert)也触发重建。 + return; + } + if (!"user".equals(entity)) + { + return; + } + if ("delete".equals(op)) + { + Long hubUserId = change.getLong("entity_id"); + if (hubUserId == null) + { + return; + } + if (hubUserMapper.selectHubUserByHubUserId(hubUserId) == null) + { + // 镜像里都没有这个人,说明本来就不归 OMS 管 + return; + } + if (properties.getDirectory().isDisableMissing()) + { + userMapper.deactivateUserByHubUserId(hubUserId); + } + // 与全量收尾同一口径:置 present='0',页面显示「已移除」,不占用待人工队列 + hubUserMapper.markAbsent(hubUserId); + return; + } + HubDirectoryUser user = parseChangePayload(change); + if (user == null || user.getUserId() == null) + { + return; + } + // 增量事件里出现「镜像中没有的人」= hub 侧新增,这才允许自动建号 + boolean isNew = hubUserMapper.selectHubUserByHubUserId(user.getUserId()) == null; + applyOne(user, !isNew, result); + } + + /** + * 写镜像。全量目录不下发手机号,因此 upsert 里手机号用 ifnull 保留旧值(见 Mapper XML)。 + */ + private void mirror(HubDirectoryUser hubUser, SysHubUser before, HubSyncResult result) + { + SysHubUser mirror = new SysHubUser(); + mirror.setHubUserId(hubUser.getUserId()); + mirror.setAccount(trimTo(hubUser.getAccount(), 190)); + mirror.setWecomUserId(trimTo(hubUser.getWecomUserId(), 190)); + mirror.setDisplayName(trimTo(hubUser.getDisplayName(), 100)); + mirror.setEmail(trimTo(hubUser.getEmail(), 190)); + mirror.setPhone(trimTo(normalizePhone(hubUser.getPhone()), 20)); + mirror.setOrgId(hubUser.getOrganizationId()); + mirror.setHubStatus(hubUser.getStatus()); + mirror.setPresent(SysHubUser.PRESENT_YES); + // 处理态一律不在这里改:新人先按「无需处理」入库,命中不了也不算异常; + // 只有重名、增量建号失败两种情况会显式置待处理,避免首次全量几百人一起冒红点 + mirror.setReviewStatus(before == null ? SysHubUser.REVIEW_NONE : before.getReviewStatus()); + mirror.setCreateBy(SYNC_OPERATOR); + hubUserMapper.upsertHubUser(mirror); + result.increaseMirrored(); + } + + /** + * 用镜像里的现值补齐本次处理要用的字段。 + * + *

只补「事件里没有」的空值,绝不覆盖事件带来的新值。补的是文本字段; + * {@code status} 故意不补——增量摘要事件不带 status 时必须按「状态未知」处理, + * 用镜像旧值冒充已知状态会绕开 {@link HubDirectoryUser#isKnownDisabled()} 那条防线, + * 让「事件没说停用」变成「沿用上次结论」,正是当初误停在职人员的成因。

+ */ + private void enrichFromMirror(HubDirectoryUser hubUser, SysHubUser before) + { + if (before == null) + { + return; + } + if (StringUtils.isEmpty(hubUser.getAccount())) + { + hubUser.setAccount(before.getAccount()); + } + if (StringUtils.isEmpty(hubUser.getWecomUserId())) + { + hubUser.setWecomUserId(before.getWecomUserId()); + } + if (StringUtils.isEmpty(hubUser.getDisplayName())) + { + hubUser.setDisplayName(before.getDisplayName()); + } + if (StringUtils.isEmpty(hubUser.getEmail())) + { + hubUser.setEmail(before.getEmail()); + } + if (StringUtils.isEmpty(hubUser.getPhone())) + { + hubUser.setPhone(before.getPhone()); + } + } + + /** + * 由增量事件自动建号(hub 侧新增的人)。 + * + *

登录名优先用手机号(OMS 的 {@code login_name} 现状就是手机号),退回 hub 账号; + * 两者都不可用或撞名就不建,交人工。邮箱被他人占用时只放弃邮箱、建号照常成功, + * 与 hub 自身即时建号的口径一致(hub 文档 9.6)——邮箱只是找回密码的辅助手段, + * 不值得为它让一个人建不出号。

+ * + * @return 失败原因;建号成功返回 null + */ + private String createUserFromHub(HubDirectoryUser hubUser) + { + String phone = normalizePhone(hubUser.getPhone()); + String account = StringUtils.isNotEmpty(phone) ? phone : trimTo(hubUser.getAccount(), LOGIN_NAME_MAX); + if (StringUtils.isEmpty(account) || account.length() > LOGIN_NAME_MAX) + { + return SysHubUser.REASON_CREATE_NO_LOGIN_NAME; + } + if (userMapper.checkLoginNameUnique(account) != null) + { + return SysHubUser.REASON_LOGIN_NAME_TAKEN; + } + + SysUser user = new SysUser(); + user.setLoginName(account); + user.setUserName(defaultIfEmpty(trimTo(hubUser.getDisplayName(), USER_NAME_MAX), account)); + user.setUserType(UserConstants.SYSTEM_USER_TYPE); + user.setHubUserId(hubUser.getUserId()); + user.setHubSyncTime(new Date()); + String email = trimTo(hubUser.getEmail(), EMAIL_MAX); + if (StringUtils.isNotEmpty(email) && userMapper.checkEmailUnique(email) == null) + { + user.setEmail(email); + } + if (StringUtils.isNotEmpty(phone)) + { + user.setPhonenumber(phone); + } + // 建号时只有 hub 明确停用才落停用状态:全量目录本应带 status,缺字段时按启用建、 + // 由后续轮次纠正,比一进来就被停用更容易被察觉 + user.setStatus(hubUser.isKnownDisabled() ? UserConstants.USER_DISABLE : UserConstants.NORMAL); + applyInitPassword(user); + user.setCreateBy(SYNC_OPERATOR); + user.setRemark("统一门户同步自动创建"); + userMapper.insertUser(user); + return null; + } + + /** + * 用系统配置的默认密码建号(用户已定口径)。 + * + *

统一登录开启时这份口令不参与登录(已绑定账号的口令由 hub 校验),它的用途是: + * 管理员解绑后该账号还能用本地口令登录,以及 hub 故障期间的应急入口。 + * 必须写 {@code pwdUpdateDate}:{@code /getInfo} 把「从未修改过密码」判为需要改密, + * 不写就会每次登录都弹提醒框。

+ */ + private void applyInitPassword(SysUser user) + { + String initPassword = configService.selectConfigByKey(CONFIG_INIT_PASSWORD); + if (StringUtils.isEmpty(initPassword)) + { + initPassword = "123456"; + } + user.setSalt(ShiroUtils.randomSalt()); + user.setPassword(passwordService.encryptPassword(user.getLoginName(), initPassword, user.getSalt())); + user.setPwdUpdateDate(new Date()); + } + + private SysUser buildPatch(Long localUserId, HubDirectoryUser hubUser) + { + SysUser patch = new SysUser(); + patch.setUserId(localUserId); + patch.setHubUserId(hubUser.getUserId()); + // 摘要事件不带姓名/邮箱/手机号时这些字段为空,对应 分支不写该列 + patch.setUserName(trimTo(hubUser.getDisplayName(), USER_NAME_MAX)); + patch.setEmail(trimTo(hubUser.getEmail(), EMAIL_MAX)); + patch.setPhonenumber(normalizePhone(hubUser.getPhone())); + // 与 hub 自身的人员同步同口径:只停用、从不启用。hub 重新启用不自动放回本地账号, + // 否则会把管理员手工停用的账号悄悄放回。 + if (hubUser.isKnownDisabled() && properties.getDirectory().isDisableMissing()) + { + patch.setStatus(UserConstants.USER_DISABLE); + } + patch.setUpdateBy(SYNC_OPERATOR); + return patch; + } + + private SysHubUser requireMirror(Long hubUserId) + { + if (hubUserId == null) + { + throw new ServiceException("缺少门户人员标识"); + } + SysHubUser mirror = hubUserMapper.selectHubUserByHubUserId(hubUserId); + if (mirror == null) + { + throw new ServiceException("门户人员不存在,请先同步人员目录"); + } + return mirror; + } + + private HubDirectoryUser parseChangePayload(JSONObject change) + { + JSONObject data = change.getJSONObject("data"); + if (data == null) + { + return null; + } + Long id = data.getLong("id"); + if (id == null) + { + id = data.getLong("user_id"); + } + if (id == null) + { + id = change.getLong("entity_id"); + } + HubDirectoryUser user = new HubDirectoryUser(); + user.setUserId(id); + user.setAccount(data.getString("account")); + user.setWecomUserId(data.getString("wecom_userid")); + user.setDisplayName(data.getString("display_name")); + user.setEmail(data.getString("email")); + user.setPhone(data.getString("phone")); + user.setOrganizationId(data.getLong("organization_id")); + user.setStatus(data.getInteger("status")); + return user; + } + + /** + * 手机号归一化:只保留数字并去掉国家码前缀,本地列只有 11 位。 + * 非 11 位一律视为不可用(宁可少匹配一次,也不把脏数据写进列里)。 + */ + private String normalizePhone(String raw) + { + if (StringUtils.isEmpty(raw)) + { + return ""; + } + String digits = raw.replaceAll("[^0-9]", ""); + if (digits.startsWith("86") && digits.length() == 13) + { + digits = digits.substring(2); + } + return digits.length() == PHONENUMBER_MAX ? digits : ""; + } + + private String trimTo(String value, int max) + { + if (value == null) + { + return ""; + } + String trimmed = value.trim(); + return trimmed.length() <= max ? trimmed : trimmed.substring(0, max); + } + + private String defaultIfEmpty(String value, String fallback) + { + return StringUtils.isEmpty(value) ? fallback : value; + } + + /** 人工操作人兜底:定时任务等无会话场景写 hub-sync,避免 update_by 为空 */ + private String operaNameSafe(String operName) + { + return StringUtils.isEmpty(operName) ? SYNC_OPERATOR : operName; + } +} diff --git a/ruoyi-sip/src/main/resources/mapper/sip/ExternalApiCallLogItemMapper.xml b/ruoyi-sip/src/main/resources/mapper/sip/ExternalApiCallLogItemMapper.xml new file mode 100644 index 00000000..8faab8b6 --- /dev/null +++ b/ruoyi-sip/src/main/resources/mapper/sip/ExternalApiCallLogItemMapper.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + select id, log_id, api_code, order_code, order_version_code, version_code, + serial_number, product_code, product_description, + service_level, service_describe, service_start_time, service_end_time, + segment_index, del_flag, create_time + from oms_external_api_log_item + + + + insert into oms_external_api_log_item + (log_id, api_code, order_code, order_version_code, version_code, + serial_number, product_code, product_description, + service_level, service_describe, service_start_time, service_end_time, + segment_index, del_flag, create_time) + values + + (#{item.logId}, #{item.apiCode}, #{item.orderCode}, #{item.orderVersionCode}, #{item.versionCode}, + #{item.serialNumber}, #{item.productCode}, #{item.productDescription}, + #{item.serviceLevel}, #{item.serviceDescribe}, #{item.serviceStartTime}, #{item.serviceEndTime}, + #{item.segmentIndex}, #{item.delFlag}, #{item.createTime}) + + + + + + diff --git a/ruoyi-sip/src/main/resources/mapper/sip/ExternalApiCallLogMapper.xml b/ruoyi-sip/src/main/resources/mapper/sip/ExternalApiCallLogMapper.xml new file mode 100644 index 00000000..280704c8 --- /dev/null +++ b/ruoyi-sip/src/main/resources/mapper/sip/ExternalApiCallLogMapper.xml @@ -0,0 +1,105 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + select id, trace_id, api_code, request_time, response_time, cost_ms, + query_start_time, query_end_time, request_ip, api_key_masked, user_agent, + request_params, http_status, business_code, success, order_count, sn_count, + response_size, response_hash, response_body, response_file, error_msg, + del_flag, create_time + from oms_external_api_log + + + + insert into oms_external_api_log + + trace_id, + api_code, + request_time, + response_time, + cost_ms, + query_start_time, + query_end_time, + request_ip, + api_key_masked, + user_agent, + request_params, + http_status, + business_code, + success, + order_count, + sn_count, + response_size, + response_hash, + response_body, + response_file, + error_msg, + del_flag, + create_time, + + + #{traceId}, + #{apiCode}, + #{requestTime}, + #{responseTime}, + #{costMs}, + #{queryStartTime}, + #{queryEndTime}, + #{requestIp}, + #{apiKeyMasked}, + #{userAgent}, + #{requestParams}, + #{httpStatus}, + #{businessCode}, + #{success}, + #{orderCount}, + #{snCount}, + #{responseSize}, + #{responseHash}, + #{responseBody}, + #{responseFile}, + #{errorMsg}, + #{delFlag}, + #{createTime}, + + + + + + diff --git a/ruoyi-sip/src/main/resources/mapper/system/HubSyncStateMapper.xml b/ruoyi-sip/src/main/resources/mapper/system/HubSyncStateMapper.xml new file mode 100644 index 00000000..5efb0f69 --- /dev/null +++ b/ruoyi-sip/src/main/resources/mapper/system/HubSyncStateMapper.xml @@ -0,0 +1,17 @@ + + + + + + + + insert into sys_hub_sync_state (state_key, state_value, update_time) + values (#{stateKey}, #{stateValue}, sysdate()) + on duplicate key update state_value = #{stateValue}, update_time = sysdate() + + + diff --git a/ruoyi-sip/src/main/resources/mapper/system/SysHubUserMapper.xml b/ruoyi-sip/src/main/resources/mapper/system/SysHubUserMapper.xml new file mode 100644 index 00000000..34395f33 --- /dev/null +++ b/ruoyi-sip/src/main/resources/mapper/system/SysHubUserMapper.xml @@ -0,0 +1,159 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + select h.hub_user_id, h.account, h.wecom_userid, h.display_name, h.email, h.phone, h.org_id, + h.hub_status, h.`present`, h.review_status, h.review_reason, h.review_remark, + h.first_seen_time, h.last_seen_time, h.create_by, h.create_time, h.update_by, h.update_time, + u.user_id as bound_user_id, u.login_name as bound_login_name, u.user_name as bound_user_name + from sys_hub_user h + left join sys_user u on u.hub_user_id = h.hub_user_id and u.del_flag = '0' + + + + + + + + + + + + insert into sys_hub_user( + hub_user_id, account, wecom_userid, display_name, email, phone, org_id, hub_status, + `present`, review_status, first_seen_time, last_seen_time, + create_by, create_time, update_by, update_time + ) values ( + #{hubUserId}, #{account}, #{wecomUserId}, #{displayName}, #{email}, #{phone}, #{orgId}, #{hubStatus}, + #{present}, #{reviewStatus}, sysdate(), sysdate(), + #{createBy}, sysdate(), #{createBy}, sysdate() + ) + on duplicate key update + + account = ifnull(nullif(values(account), ''), account), + wecom_userid = ifnull(nullif(values(wecom_userid), ''), wecom_userid), + display_name = ifnull(nullif(values(display_name), ''), display_name), + email = ifnull(nullif(values(email), ''), email), + phone = ifnull(nullif(values(phone), ''), phone), + org_id = ifnull(values(org_id), org_id), + hub_status = ifnull(values(hub_status), hub_status), + `present` = values(`present`), + last_seen_time = sysdate(), + update_by = values(update_by), + update_time = sysdate() + + + + + update sys_hub_user set `present` = '0', update_time = sysdate() where `present` <> '0' + + + + + update sys_hub_user set `present` = '0', update_time = sysdate() + where hub_user_id = #{hubUserId} + + + + + update sys_hub_user + set review_status = #{reviewStatus}, + review_reason = #{reviewReason}, + review_remark = #{reviewRemark}, + update_by = #{updateBy}, + update_time = sysdate() + where hub_user_id = #{hubUserId} + + + + + update sys_hub_user + set review_status = #{reviewStatus}, + review_reason = #{reviewReason}, + update_time = sysdate() + where hub_user_id = #{hubUserId} and review_status <> '2' + + + + + update sys_hub_user + set review_status = '0', review_reason = null, update_time = sysdate() + where hub_user_id = #{hubUserId} and review_status = '1' + + + + + + diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserMapper.java index 6889c341..4a59b9da 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysUserMapper.java @@ -43,6 +43,50 @@ public interface SysUserMapper */ public SysUser selectUserByLoginName(String userName); + /** + * 通过 hub 用户ID查询用户(统一登录免登认人,唯一映射键) + * + * @param hubUserId hub 用户ID,即票据校验返回的 sub + * @return 用户对象信息,未绑定该 hub 账号时为 null + */ + public SysUser selectUserByHubUserId(Long hubUserId); + + /** + * 按姓名查询**尚未绑定 hub** 的未删除账号列表(可能多行,供同步判定唯一性) + * + *

hub 目录与 OMS 之间唯一可用的自动匹配键是姓名:OMS 的 login_name 存的是手机号, + * hub 全量目录又不下发手机号。只取未绑定的行,已绑给别人的账号不参与匹配, + * 避免同名的两行抢绑同一个人。

+ * + * @param userName 姓名(sys_user.user_name) + * @return 用户列表 + */ + public List selectUnboundByUserName(String userName); + + /** + * 解除本地账号与 hub 的绑定(该账号回到本地口令登录) + * + * @param userId 本地用户ID + * @return 结果 + */ + public int unbindHubByUserId(Long userId); + + /** + * 把本地账号绑定到 hub 账号并覆盖同步字段(不改 login_name、不改角色) + * + * @param user 需包含 userId、hubUserId,其余字段按需覆盖 + * @return 结果 + */ + public int bindUserToHub(SysUser user); + + /** + * hub 侧停用后停用本地账号(只置 status,不物理删除) + * + * @param hubUserId hub 用户ID + * @return 结果 + */ + public int deactivateUserByHubUserId(Long hubUserId); + /** * 通过手机号码查询用户 * diff --git a/ruoyi-system/src/main/resources/mapper/system/SysUserMapper.xml b/ruoyi-system/src/main/resources/mapper/system/SysUserMapper.xml index 515165f7..af393126 100644 --- a/ruoyi-system/src/main/resources/mapper/system/SysUserMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/system/SysUserMapper.xml @@ -10,6 +10,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" + + @@ -50,7 +52,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" - select u.user_id, u.dept_id, u.login_name, u.user_name, u.user_type, u.email, u.avatar, u.phonenumber, u.sex, u.password, u.salt, u.status, u.del_flag, u.login_ip, u.login_date, u.pwd_update_date, u.create_by, u.create_time, u.update_by, u.update_time, u.remark, + select u.user_id, u.dept_id, u.login_name, u.user_name, u.user_type, u.hub_user_id, u.hub_sync_time, u.email, u.avatar, u.phonenumber, u.sex, u.password, u.salt, u.status, u.del_flag, u.login_ip, u.login_date, u.pwd_update_date, u.create_by, u.create_time, u.update_by, u.update_time, u.remark, d.dept_id, d.parent_id, d.ancestors, d.dept_name, d.order_num, d.leader, d.status as dept_status, r.role_id, r.role_name, r.role_key, r.role_sort, r.data_scope, r.status as role_status from sys_user u @@ -60,7 +62,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" - + + + + + + + + + + update sys_user + + hub_user_id = #{hubUserId}, + hub_sync_time = sysdate(), + user_name = #{userName}, + email = #{email}, + phonenumber = #{phonenumber}, + status = #{status}, + update_by = #{updateBy}, + update_time = sysdate() + + where user_id = #{userId} + + + + + update sys_user set status = '1', hub_sync_time = sysdate(), update_time = sysdate() + where hub_user_id = #{hubUserId} and status <> '1' + + + + + update sys_user + set hub_user_id = null, hub_sync_time = null, update_time = sysdate() + where user_id = #{userId} and hub_user_id is not null + +