feat(hub): 接入统一门户 dsh-hub 实现免登登录与人员目录同步
- 新增 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.htmlcp_1.0.0
parent
042588a49d
commit
076fdfaffb
|
|
@ -52,6 +52,7 @@
|
|||
|
||||
<script>
|
||||
import { mapGetters } from 'vuex'
|
||||
import { getHubStatus } from '@/api/system/hub'
|
||||
import Breadcrumb from '@/components/Breadcrumb'
|
||||
import TopNav from '@/components/TopNav'
|
||||
import Hamburger from '@/components/Hamburger'
|
||||
|
|
@ -108,8 +109,24 @@ export default {
|
|||
cancelButtonText: '取消',
|
||||
type: 'warning'
|
||||
}).then(() => {
|
||||
// 必须在 LogOut 清空状态前取值:已绑定统一门户的账号退出后回门户首页
|
||||
const isHubUser = !!this.$store.getters.hubUserId
|
||||
this.$store.dispatch('LogOut').then(() => {
|
||||
location.href = '/index'
|
||||
if (!isHubUser) {
|
||||
location.href = '/index'
|
||||
return
|
||||
}
|
||||
// 状态接口是匿名的,会话已销毁仍可调用
|
||||
getHubStatus().then(res => {
|
||||
const hub = (res && res.data) || {}
|
||||
if (hub.logoutRedirectHub && hub.hubHomeUrl) {
|
||||
location.href = hub.hubHomeUrl
|
||||
} else {
|
||||
location.href = '/index'
|
||||
}
|
||||
}).catch(() => {
|
||||
location.href = '/index'
|
||||
})
|
||||
})
|
||||
}).catch(() => {})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,8 @@ import { isServiceHost } from '@/utils/serviceHost'
|
|||
|
||||
NProgress.configure({ showSpinner: false })
|
||||
|
||||
const whiteList = ['/login', '/register', '/manage/service','/system/vendor/query','/system/partner/query']
|
||||
// /sso/hub 是统一门户免登落地页:进入时必须还没有本地会话,因此不能走登录态校验
|
||||
const whiteList = ['/login', '/register', '/manage/service','/system/vendor/query','/system/partner/query', '/sso/hub']
|
||||
|
||||
const isWhiteList = (path) => {
|
||||
if (path === '/' && isServiceHost()) {
|
||||
|
|
|
|||
|
|
@ -52,6 +52,12 @@ export const constantRoutes = [
|
|||
component: () => import('@/views/register'),
|
||||
hidden: true
|
||||
},
|
||||
{
|
||||
// 统一门户(dsh-hub)票据免登落地页:静态路由、不进菜单,票据只在此页消费一次
|
||||
path: '/sso/hub',
|
||||
component: () => import('@/views/sso/hub'),
|
||||
hidden: true
|
||||
},
|
||||
{
|
||||
// sub2api 设计体系的组件预览页,登录后按 URL 访问,不进菜单
|
||||
path: '/ui-preview',
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ const getters = {
|
|||
introduction: state => state.user.introduction,
|
||||
roles: state => state.user.roles,
|
||||
permissions: state => state.user.permissions,
|
||||
hubUserId: state => state.user.hubUserId,
|
||||
permission_routes: state => state.permission.routes,
|
||||
topbarRouters: state => state.permission.topbarRouters,
|
||||
defaultRoutes: state => state.permission.defaultRoutes,
|
||||
|
|
|
|||
|
|
@ -13,7 +13,9 @@ const user = {
|
|||
email:'',
|
||||
phonenumber:'',
|
||||
roles: [],
|
||||
permissions: []
|
||||
permissions: [],
|
||||
// 统一门户(dsh-hub)用户ID:非空即内部人员,退出后回统一门户
|
||||
hubUserId: ''
|
||||
},
|
||||
|
||||
mutations: {
|
||||
|
|
@ -40,6 +42,9 @@ const user = {
|
|||
},
|
||||
SET_PHONENUMBER: (state, phonenumber) => {
|
||||
state.phonenumber = phonenumber
|
||||
},
|
||||
SET_HUB_USER_ID: (state, hubUserId) => {
|
||||
state.hubUserId = hubUserId || ''
|
||||
}
|
||||
},
|
||||
|
||||
|
|
@ -81,6 +86,8 @@ const user = {
|
|||
commit('SET_NAME', user.loginName)
|
||||
commit('SET_NICK_NAME', user.userName)
|
||||
commit('SET_AVATAR', avatar)
|
||||
// hubUserId 由 /getInfo 一并下发:非空说明该账号已绑定统一门户
|
||||
commit('SET_HUB_USER_ID', user.hubUserId)
|
||||
if (data.isDefaultModifyPwd) {
|
||||
MessageBox.confirm('您的密码还是初始密码,请修改密码!', '安全提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
|
||||
router.push({ name: 'Profile', params: { activeTab: 'resetPwd' } })
|
||||
|
|
|
|||
|
|
@ -110,7 +110,7 @@ service.interceptors.response.use(res => {
|
|||
} else if (code === 601) {
|
||||
Message({ message: msg, type: 'warning' })
|
||||
return Promise.reject('error')
|
||||
} else if (code === 301 && res.config.headers && res.config.headers.allowWarning) {
|
||||
} else if ((code === 301 || code === 603) && res.config.headers && res.config.headers.allowWarning) {
|
||||
return res.data
|
||||
} else if (code !== 200) {
|
||||
Notification.error({ title: msg })
|
||||
|
|
|
|||
|
|
@ -6,6 +6,8 @@
|
|||
</span>
|
||||
<h1 class="login-brand-title">{{ title }}</h1>
|
||||
<p class="login-brand-sub">一体化订单与供应链管理台</p>
|
||||
<!-- 统一门户账号提示:内部员工的口令由门户校验,前端无需区分登录链路 -->
|
||||
<p class="login-tip login-account-tip">内部员工请使用统一门户的账号密码登录</p>
|
||||
</div>
|
||||
|
||||
<el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
|
||||
|
|
@ -102,6 +104,43 @@
|
|||
<el-button type="primary" :loading="resetPwdLoading" @click="submitResetPwd">提 交</el-button>
|
||||
</div>
|
||||
</el-dialog>
|
||||
<!-- 统一门户强制改密:口令归门户管,这里收新口令后由后端调门户的服务端改密接口,不跳转门户页面 -->
|
||||
<el-dialog
|
||||
title="修改统一门户密码"
|
||||
:visible.sync="hubPwdOpen"
|
||||
width="420px"
|
||||
:close-on-click-modal="false"
|
||||
:close-on-press-escape="false"
|
||||
append-to-body
|
||||
>
|
||||
<el-form ref="hubPwdForm" :model="hubPwdForm" :rules="hubPwdRules" label-width="100px">
|
||||
<el-form-item label="账号">
|
||||
<el-input v-model="hubPwdForm.username" disabled />
|
||||
</el-form-item>
|
||||
<el-form-item label="当前密码" prop="currentPassword">
|
||||
<el-input v-model="hubPwdForm.currentPassword" type="password" placeholder="请输入统一门户当前密码" show-password />
|
||||
</el-form-item>
|
||||
<el-form-item label="新密码" prop="newPassword">
|
||||
<el-input v-model="hubPwdForm.newPassword" type="password" placeholder="请输入新密码" show-password />
|
||||
</el-form-item>
|
||||
<el-form-item label="确认新密码" prop="confirmPassword">
|
||||
<el-input v-model="hubPwdForm.confirmPassword" type="password" placeholder="请确认新密码" show-password />
|
||||
</el-form-item>
|
||||
<el-form-item label="验证码" prop="code" v-if="captchaEnabled">
|
||||
<el-input v-model="hubPwdForm.code" placeholder="请输入验证码" maxlength="20" style="width: 190px" />
|
||||
<div class="login-code hub-pwd-code">
|
||||
<img :src="codeUrl" @click="getCode" class="login-code-img"/>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<div class="password-tip">
|
||||
<div>{{ hubPwdTip }}</div>
|
||||
</div>
|
||||
</el-form>
|
||||
<div slot="footer" class="dialog-footer">
|
||||
<el-button @click="hubPwdOpen = false">取 消</el-button>
|
||||
<el-button type="primary" :loading="hubPwdLoading" @click="submitHubPwd">确 定</el-button>
|
||||
</div>
|
||||
</el-dialog>
|
||||
<!-- 底部 -->
|
||||
<div class="el-login-footer">
|
||||
<span>Copyright © 2018-2025 unissense All Rights Reserved.</span>
|
||||
|
|
@ -113,6 +152,7 @@
|
|||
import Cookies from "js-cookie"
|
||||
import { encrypt, decrypt } from '@/utils/jsencrypt'
|
||||
import { resetLoginPwd, sendResetPwdEmailCode } from '@/api/login'
|
||||
import { getHubPasswordPolicy, changeHubPassword } from '@/api/system/hub'
|
||||
|
||||
export default {
|
||||
name: "Login",
|
||||
|
|
@ -134,6 +174,32 @@ export default {
|
|||
},
|
||||
resetPwdOpen: false,
|
||||
resetPwdLoading: false,
|
||||
// 统一门户强制改密(登录返回 603):在本页改完直接进系统,不跳门户空白页
|
||||
hubPwdOpen: false,
|
||||
hubPwdLoading: false,
|
||||
hubPwdForm: {
|
||||
username: "",
|
||||
currentPassword: "",
|
||||
newPassword: "",
|
||||
confirmPassword: "",
|
||||
code: ""
|
||||
},
|
||||
// 门户口令要求,缺失时按「只校验长度非空」降级,规则最终以门户判定为准
|
||||
hubPolicy: null,
|
||||
hubPwdRules: {
|
||||
currentPassword: [
|
||||
{ required: true, trigger: "blur", message: "请输入统一门户当前密码" }
|
||||
],
|
||||
newPassword: [
|
||||
{ required: true, trigger: "blur", message: "请输入新密码" },
|
||||
{ validator: (rule, value, callback) => this.validateHubPassword(rule, value, callback), trigger: "blur" }
|
||||
],
|
||||
confirmPassword: [
|
||||
{ required: true, trigger: "blur", message: "请确认新密码" },
|
||||
{ validator: (rule, value, callback) => this.equalToHubPassword(rule, value, callback), trigger: "blur" }
|
||||
],
|
||||
code: [{ required: true, trigger: "change", message: "请输入验证码" }]
|
||||
},
|
||||
emailCodeLoading: false,
|
||||
emailCodeCountdown: 0,
|
||||
emailCodeTimer: null,
|
||||
|
|
@ -172,6 +238,24 @@ export default {
|
|||
redirect: undefined
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
// 口令要求来自门户管理端参数,管理员调参后这里跟着变,不在前端写死
|
||||
hubPwdTip() {
|
||||
const policy = this.hubPolicy
|
||||
if (!policy) {
|
||||
return "新密码需通过统一门户的口令规则校验,具体要求以统一门户判定为准。"
|
||||
}
|
||||
const parts = [`密码长度需在 ${policy.min_length} 到 ${policy.max_length} 位之间`]
|
||||
if (policy.strength_enabled && policy.required_classes > 0) {
|
||||
parts.push(`至少包含大写字母、小写字母、数字、符号中的 ${policy.required_classes} 类`)
|
||||
}
|
||||
if (policy.reject_common_password) {
|
||||
parts.push("不能使用常见弱口令")
|
||||
}
|
||||
parts.push("不能包含统一门户账号")
|
||||
return parts.join(",") + "。"
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
$route: {
|
||||
handler: function(route) {
|
||||
|
|
@ -212,6 +296,82 @@ export default {
|
|||
callback()
|
||||
}
|
||||
},
|
||||
equalToHubPassword(rule, value, callback) {
|
||||
if (this.hubPwdForm.newPassword !== value) {
|
||||
callback(new Error("两次输入的密码不一致"))
|
||||
} else {
|
||||
callback()
|
||||
}
|
||||
},
|
||||
// 前置校验只做门户规则里能本地判断的部分,最终仍由门户判定,避免两边规则漂移时误拦人
|
||||
validateHubPassword(rule, value, callback) {
|
||||
const policy = this.hubPolicy
|
||||
if (!value) {
|
||||
return callback(new Error("请输入新密码"))
|
||||
}
|
||||
if (!policy) {
|
||||
return callback()
|
||||
}
|
||||
if (value.length < policy.min_length || value.length > policy.max_length) {
|
||||
return callback(new Error(`密码长度需在 ${policy.min_length} 到 ${policy.max_length} 位之间`))
|
||||
}
|
||||
if (policy.strength_enabled && policy.required_classes > 0
|
||||
&& this.countCharacterClasses(value) < policy.required_classes) {
|
||||
return callback(new Error(`需包含大写字母、数字、符号中的 ${policy.required_classes} 类`))
|
||||
}
|
||||
return callback()
|
||||
},
|
||||
// 字符类别口径与门户一致:大小写字母、数字、ASCII 符号各算一类
|
||||
countCharacterClasses(value) {
|
||||
const patterns = [/[a-z]/, /[A-Z]/, /[0-9]/, /[!-/:-@[-`{-~]/]
|
||||
return patterns.filter(pattern => pattern.test(value)).length
|
||||
},
|
||||
openHubPwdDialog(username, currentPassword, message) {
|
||||
this.hubPwdForm = { username, currentPassword: currentPassword || "", newPassword: "", confirmPassword: "", code: "" }
|
||||
this.hubPwdOpen = true
|
||||
if (message) {
|
||||
this.$modal.msgWarning(message)
|
||||
}
|
||||
// 刚才那次登录已经消费掉会话里的验证码,弹窗必须换一张新码,否则提交必判「验证码错误」
|
||||
if (this.captchaEnabled) {
|
||||
this.loginForm.code = ""
|
||||
this.getCode()
|
||||
}
|
||||
if (!this.hubPolicy) {
|
||||
getHubPasswordPolicy().then(res => {
|
||||
// 门户不可达时后端回空对象:读不到规则就退回「只校验两次一致」,不写死数字去拦人
|
||||
const requirements = res.data && res.data.requirements
|
||||
this.hubPolicy = requirements && requirements.min_length ? requirements : null
|
||||
}).catch(() => {})
|
||||
}
|
||||
this.$nextTick(() => {
|
||||
if (this.$refs.hubPwdForm) {
|
||||
this.$refs.hubPwdForm.clearValidate()
|
||||
}
|
||||
})
|
||||
},
|
||||
submitHubPwd() {
|
||||
this.$refs.hubPwdForm.validate(valid => {
|
||||
if (!valid) {
|
||||
return
|
||||
}
|
||||
this.hubPwdLoading = true
|
||||
changeHubPassword(this.hubPwdForm).then(() => {
|
||||
this.hubPwdOpen = false
|
||||
this.$modal.msgSuccess("密码修改成功")
|
||||
// 后端改密成功已就地建立本地会话,直接进系统,不必再输一次新密码
|
||||
this.goRedirect()
|
||||
}).catch(() => {
|
||||
// 门户拒绝的原因(当前密码不正确、口令不合规等)已由拦截器提示,换一张码再试
|
||||
if (this.captchaEnabled) {
|
||||
this.hubPwdForm.code = ""
|
||||
this.getCode()
|
||||
}
|
||||
}).finally(() => {
|
||||
this.hubPwdLoading = false
|
||||
})
|
||||
})
|
||||
},
|
||||
openResetPwdDialog() {
|
||||
this.resetPwdOpen = true
|
||||
this.clearEmailCodeTimer()
|
||||
|
|
@ -281,37 +441,50 @@ export default {
|
|||
},
|
||||
handleLogin() {
|
||||
this.$refs.loginForm.validate(valid => {
|
||||
if (valid) {
|
||||
this.loading = true
|
||||
if (this.loginForm.rememberMe) {
|
||||
Cookies.set("username", this.loginForm.username, { expires: 30 })
|
||||
Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 })
|
||||
Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 })
|
||||
} else {
|
||||
Cookies.remove("username")
|
||||
Cookies.remove("password")
|
||||
Cookies.remove('rememberMe')
|
||||
}
|
||||
this.$store.dispatch("Login", this.loginForm).then((res) => {
|
||||
if (res && res.code === 301) {
|
||||
this.resetPwdForm.username = this.loginForm.username
|
||||
this.resetPwdForm.newPassword = ""
|
||||
this.resetPwdForm.confirmPassword = ""
|
||||
this.resetPwdForm.emailCode = ""
|
||||
this.clearEmailCodeTimer()
|
||||
this.resetPwdOpen = true
|
||||
this.loading = false
|
||||
return
|
||||
}
|
||||
this.$router.push({ path: this.redirect || "/" }).catch(()=>{})
|
||||
}).catch(() => {
|
||||
this.loading = false
|
||||
if (this.captchaEnabled) {
|
||||
this.getCode()
|
||||
}
|
||||
})
|
||||
if (!valid) {
|
||||
return
|
||||
}
|
||||
this.loading = true
|
||||
if (this.loginForm.rememberMe) {
|
||||
Cookies.set("username", this.loginForm.username, { expires: 30 })
|
||||
Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 })
|
||||
Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 })
|
||||
} else {
|
||||
Cookies.remove("username")
|
||||
Cookies.remove("password")
|
||||
Cookies.remove('rememberMe')
|
||||
}
|
||||
// 统一走 /login:已绑定门户的账号由后端拿该密码去门户校验,未绑定时校验本地口令,前端无需分支
|
||||
this.$store.dispatch("Login", this.loginForm).then((res) => {
|
||||
if (res && res.code === 301) {
|
||||
this.resetPwdForm.username = this.loginForm.username
|
||||
this.resetPwdForm.newPassword = ""
|
||||
this.resetPwdForm.confirmPassword = ""
|
||||
this.resetPwdForm.emailCode = ""
|
||||
this.clearEmailCodeTimer()
|
||||
this.resetPwdOpen = true
|
||||
this.loading = false
|
||||
return
|
||||
}
|
||||
if (res && res.code === 603) {
|
||||
// 统一门户要求先改密:口令是对的,只是按门户策略该换新的;留在本页改完直接进系统
|
||||
// 刚输入的密码已被门户判对,直接带进弹窗,不必让人再输一遍
|
||||
this.openHubPwdDialog(this.loginForm.username, this.loginForm.password, res.msg)
|
||||
this.loading = false
|
||||
return
|
||||
}
|
||||
this.goRedirect()
|
||||
}).catch(() => {
|
||||
// 登录失败(口令错误、账号锁定、门户不可用等)已由拦截器提示,刷新验证码后重试
|
||||
this.loading = false
|
||||
if (this.captchaEnabled) {
|
||||
this.getCode()
|
||||
}
|
||||
})
|
||||
})
|
||||
},
|
||||
goRedirect() {
|
||||
this.$router.push({ path: this.redirect || "/" }).catch(() => {})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -446,6 +619,10 @@ export default {
|
|||
color: $s2-gray-400;
|
||||
}
|
||||
|
||||
.login-account-tip {
|
||||
margin: 10px 0 0;
|
||||
}
|
||||
|
||||
.login-code {
|
||||
width: 33%;
|
||||
height: 42px;
|
||||
|
|
@ -456,6 +633,15 @@ export default {
|
|||
}
|
||||
}
|
||||
|
||||
/* 弹窗里的验证码沿用图片样式,但不参与登录表单的浮动布局 */
|
||||
.hub-pwd-code {
|
||||
width: auto;
|
||||
float: none;
|
||||
display: inline-block;
|
||||
vertical-align: top;
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
.login-code-img {
|
||||
height: 42px;
|
||||
border-radius: 10px;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
<template>
|
||||
<el-form ref="form" :model="user" :rules="rules" label-width="80px">
|
||||
<el-form ref="form" :model="user" :rules="formRules" label-width="80px">
|
||||
<el-form-item label="旧密码" prop="oldPassword">
|
||||
<el-input v-model="user.oldPassword" placeholder="请输入旧密码" type="password" show-password/>
|
||||
<el-input v-model="user.oldPassword" :placeholder="hubManaged ? '请输入统一门户当前密码' : '请输入旧密码'" type="password" show-password/>
|
||||
</el-form-item>
|
||||
<el-form-item label="新密码" prop="newPassword">
|
||||
<el-input v-model="user.newPassword" placeholder="请输入新密码" type="password" show-password/>
|
||||
|
|
@ -10,6 +10,8 @@
|
|||
<el-input v-model="user.confirmPassword" placeholder="请确认新密码" type="password" show-password/>
|
||||
</el-form-item>
|
||||
<div class="password-tip">
|
||||
<div v-if="hubManaged">{{ hubTip }}</div>
|
||||
<template v-else>
|
||||
<div>密码长度8-20位,以下规则中至少满足 3 种:</div>
|
||||
<ul>
|
||||
<li>大写字母</li>
|
||||
|
|
@ -17,6 +19,7 @@
|
|||
<li>数字</li>
|
||||
<li>特殊字符</li>
|
||||
</ul>
|
||||
</template>
|
||||
</div>
|
||||
<el-form-item>
|
||||
<el-button type="primary" size="mini" @click="submit">保存</el-button>
|
||||
|
|
@ -27,6 +30,7 @@
|
|||
|
||||
<script>
|
||||
import { updateUserPwd } from "@/api/system/user"
|
||||
import { getHubPasswordPolicy, changeHubPassword } from "@/api/system/hub"
|
||||
|
||||
export default {
|
||||
data() {
|
||||
|
|
@ -43,6 +47,8 @@ export default {
|
|||
newPassword: undefined,
|
||||
confirmPassword: undefined
|
||||
},
|
||||
// 统一门户的口令要求;读不到时按「不额外限制」降级,最终以门户判定为准
|
||||
hubPolicy: null,
|
||||
// 表单校验
|
||||
rules: {
|
||||
oldPassword: [
|
||||
|
|
@ -57,13 +63,76 @@ export default {
|
|||
{ required: true, message: "确认密码不能为空", trigger: "blur" },
|
||||
{ required: true, validator: equalToPassword, trigger: "blur" }
|
||||
]
|
||||
},
|
||||
// 已绑定统一门户:口令规则归门户的管理端参数,本系统不复刻一份去拦人,
|
||||
// 只校验必填与两次一致,不合规由门户当场拒绝并回原因
|
||||
hubRules: {
|
||||
oldPassword: [
|
||||
{ required: true, message: "当前密码不能为空", trigger: "blur" }
|
||||
],
|
||||
newPassword: [
|
||||
{ required: true, trigger: "blur", message: "请输入新密码" }
|
||||
],
|
||||
confirmPassword: [
|
||||
{ required: true, message: "确认密码不能为空", trigger: "blur" },
|
||||
{ required: true, validator: equalToPassword, trigger: "blur" }
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
// hubUserId 由 /getInfo 下发,非空说明口令归统一门户管
|
||||
hubManaged() {
|
||||
return !!this.$store.getters.hubUserId
|
||||
},
|
||||
formRules() {
|
||||
return this.hubManaged ? this.hubRules : this.rules
|
||||
},
|
||||
hubTip() {
|
||||
const policy = this.hubPolicy
|
||||
if (!policy) {
|
||||
return "该账号已绑定统一门户,新密码需通过统一门户的口令规则校验,具体要求以统一门户判定为准。"
|
||||
}
|
||||
const parts = [`该账号已绑定统一门户,密码长度需在 ${policy.min_length} 到 ${policy.max_length} 位之间`]
|
||||
if (policy.strength_enabled && policy.required_classes > 0) {
|
||||
parts.push(`至少包含大写字母、小写字母、数字、符号中的 ${policy.required_classes} 类`)
|
||||
}
|
||||
if (policy.reject_common_password) {
|
||||
parts.push("不能使用常见弱口令")
|
||||
}
|
||||
return parts.join(",") + "。"
|
||||
}
|
||||
},
|
||||
created() {
|
||||
if (this.hubManaged) {
|
||||
getHubPasswordPolicy().then(res => {
|
||||
// 门户不可达时后端回空对象:读不到规则就不显示具体数字,避免按错的规则提示人
|
||||
const requirements = res.data && res.data.requirements
|
||||
this.hubPolicy = requirements && requirements.min_length ? requirements : null
|
||||
}).catch(() => {})
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
submit() {
|
||||
this.$refs["form"].validate(valid => {
|
||||
if (valid) {
|
||||
if (this.hubManaged) {
|
||||
// 内部人员的口令在统一门户,改本地密码等于改一条没人再用的历史口令
|
||||
changeHubPassword({
|
||||
currentPassword: this.user.oldPassword,
|
||||
newPassword: this.user.newPassword,
|
||||
confirmPassword: this.user.confirmPassword
|
||||
}).then(() => {
|
||||
this.$modal.msgSuccess("修改成功")
|
||||
this.user.oldPassword = undefined
|
||||
this.user.newPassword = undefined
|
||||
this.user.confirmPassword = undefined
|
||||
this.$refs["form"].clearValidate()
|
||||
}).catch(() => {
|
||||
// 门户拒绝的原因(当前密码不正确、口令不合规等)已由拦截器提示
|
||||
})
|
||||
return
|
||||
}
|
||||
let data={
|
||||
userId:this.user.userId,
|
||||
loginName:this.user.loginName,
|
||||
|
|
|
|||
|
|
@ -203,8 +203,11 @@ public class SysIndexController extends BaseController
|
|||
data.put("user", user);
|
||||
data.put("roles", roles);
|
||||
data.put("permissions", permissions);
|
||||
data.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
|
||||
data.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));
|
||||
// 已绑定统一门户的账号:口令由门户管理(含强制改密与有效期),OMS 不再弹自己的改密提醒,
|
||||
// 否则内部人每次免登进来都会被一个用不上的本系统口令提示打扰(ADR-0014 双通道口径)
|
||||
boolean hubManaged = user.getHubUserId() != null;
|
||||
data.put("isDefaultModifyPwd", !hubManaged && initPasswordIsModify(user.getPwdUpdateDate()));
|
||||
data.put("isPasswordExpired", !hubManaged && passwordIsExpiration(user.getPwdUpdateDate()));
|
||||
|
||||
return AjaxResult.success(data);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,12 +1,17 @@
|
|||
package com.ruoyi.web.controller.system;
|
||||
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import cn.hutool.extra.mail.Mail;
|
||||
import com.ruoyi.common.constant.ShiroConstants;
|
||||
import com.ruoyi.common.core.domain.entity.SysUser;
|
||||
import com.ruoyi.common.utils.ShiroUtils;
|
||||
import com.ruoyi.framework.hub.HubLoginResult;
|
||||
import com.ruoyi.framework.hub.HubLoginService;
|
||||
import com.ruoyi.framework.shiro.service.SysPasswordService;
|
||||
import com.ruoyi.system.service.ISysUserService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
|
@ -45,6 +50,9 @@ public class SysLoginController extends BaseController
|
|||
|
||||
private static final long RESET_PWD_EMAIL_CODE_EXPIRE_TIME = 10 * 60 * 1000L;
|
||||
|
||||
/** 统一门户要求先改密时回给前端的业务码(前端据此跳 hub 改密页,本次不建本地会话) */
|
||||
private static final int CODE_HUB_PASSWORD_CHANGE = 603;
|
||||
|
||||
/**
|
||||
* 是否开启记住我功能
|
||||
*/
|
||||
|
|
@ -60,6 +68,9 @@ public class SysLoginController extends BaseController
|
|||
@Autowired
|
||||
private SysPasswordService passwordService;
|
||||
|
||||
@Autowired
|
||||
private HubLoginService hubLoginService;
|
||||
|
||||
@GetMapping("/login")
|
||||
public String login(HttpServletRequest request, HttpServletResponse response, ModelMap mmap)
|
||||
{
|
||||
|
|
@ -87,6 +98,33 @@ public class SysLoginController extends BaseController
|
|||
@ResponseBody
|
||||
public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe)
|
||||
{
|
||||
// 同一个入口按绑定关系分流:已绑定统一门户的账号,口令交给 hub 判(对接指南 2.8
|
||||
// 的口令代校验),本系统不保存也不比对它;未绑定的外部用户继续走本地口令。
|
||||
// 前端始终只有一张本系统验证码——hub 侧新加的代校验接口不要它自己的图形码,
|
||||
// hub 文档也明确要求「人机校验由下游自己做」,所以这张码就是那条防线。
|
||||
SysUser login = userService.selectUserByLoginName(username);
|
||||
if (login == null || login.getHubUserId() == null)
|
||||
{
|
||||
// 内部员工输入的是统一门户账号,而本系统的 login_name 是历史数据(手机号 / 域账号),
|
||||
// 两者不同源,所以本地账号查不到或未绑定时再按门户账号反查一次。
|
||||
// 顺序不能反:本地已有同名账号(哪怕未绑定)一律先按本地账号处理,
|
||||
// 否则外部用户的账号名恰好撞上某个门户账号时,他的本地登录会被抢走。
|
||||
SysUser byHubAccount = hubLoginService.resolveUserByHubAccount(username);
|
||||
if (byHubAccount != null)
|
||||
{
|
||||
login = byHubAccount;
|
||||
}
|
||||
}
|
||||
if (hubLoginService.usesHubPassword(login))
|
||||
{
|
||||
return loginByHubPassword(login, password);
|
||||
}
|
||||
// 已绑定但门户直登被关掉(hub.login.password-login-enabled=false):
|
||||
// 这种账号的口令已经不由本系统管,放回本地口令等于放行建号时的默认密码
|
||||
if (login != null && login.getHubUserId() != null && hubLoginService.isRejectBoundLocalLogin())
|
||||
{
|
||||
return error("该账号已绑定统一门户,请从统一门户进入本系统");
|
||||
}
|
||||
UsernamePasswordToken token = new UsernamePasswordToken(username, password, Boolean.TRUE.equals(rememberMe));
|
||||
Subject subject = SecurityUtils.getSubject();
|
||||
try
|
||||
|
|
@ -114,6 +152,47 @@ public class SysLoginController extends BaseController
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 已绑定统一门户的账号:把口令交给 hub 判(对接指南 2.8 的口令代校验),判对就地建立本地会话。
|
||||
*
|
||||
* <p>本方法不经过 {@code UserRealm} → {@code SysLoginService#login},所以那条链路上的验证码
|
||||
* 判定要在这里补做:{@code captchaValidate} 过滤器只把失败结论写成请求属性、不拦请求,
|
||||
* 漏掉这一步等于让内部员工的登录绕过人机校验。</p>
|
||||
*
|
||||
* <p>{@code rememberMe} 在这一支不生效:门户口令不该长期留在浏览器里,且门户侧已有自己的
|
||||
* 会话;勾不勾都不影响登录结果。</p>
|
||||
*/
|
||||
private AjaxResult loginByHubPassword(SysUser account, String password)
|
||||
{
|
||||
Object captchaFlag = ServletUtils.getRequest().getAttribute(ShiroConstants.CURRENT_CAPTCHA);
|
||||
if (ShiroConstants.CAPTCHA_ERROR.equals(captchaFlag))
|
||||
{
|
||||
return error("验证码错误");
|
||||
}
|
||||
HubLoginResult result = hubLoginService.loginByPassword(account, password);
|
||||
if (result.isSuccess())
|
||||
{
|
||||
return success();
|
||||
}
|
||||
if (HubLoginResult.STATUS_PASSWORD_CHANGE_REQUIRED.equals(result.getStatus()))
|
||||
{
|
||||
// 603:口令是对的,但统一门户的策略要求先改密。hub 的改密闸门只管它自己签发的会话,
|
||||
// 管不到本系统会话,所以必须在这里把人挡住并给出 hub 的改密页地址。
|
||||
String message = StringUtils.isNotEmpty(result.getMessage()) ? result.getMessage()
|
||||
: "统一门户要求先修改密码";
|
||||
Map<String, Object> payload = new HashMap<>();
|
||||
payload.put("url", result.getPasswordChangeUrl());
|
||||
AjaxResult data = new AjaxResult();
|
||||
data.put(AjaxResult.CODE_TAG, CODE_HUB_PASSWORD_CHANGE);
|
||||
data.put(AjaxResult.MSG_TAG, message);
|
||||
data.put(AjaxResult.DATA_TAG, payload);
|
||||
return data;
|
||||
}
|
||||
// 只记结论,不记口令
|
||||
log.warn("统一门户口令登录未通过, loginName={}, status={}", account.getLoginName(), result.getStatus());
|
||||
return error(StringUtils.isNotEmpty(result.getMessage()) ? result.getMessage() : "统一门户登录失败,请稍后重试");
|
||||
}
|
||||
|
||||
@PostMapping("/login/sendResetPwdEmailCode")
|
||||
@ResponseBody
|
||||
public AjaxResult sendResetPwdEmailCode(String username)
|
||||
|
|
|
|||
|
|
@ -73,4 +73,54 @@ opportunity:
|
|||
external-api-log:
|
||||
# 大报文 gzip 存放目录;相对路径基于应用工作目录,也可配置绝对路径
|
||||
# 例如 Windows: D:/ruoyi/external-api-log Linux: /home/oms/external-api-log
|
||||
response-file-dir: /logs/external-api
|
||||
response-file-dir: /logs/external-api
|
||||
# dsh-hub 统一登录与人员同步
|
||||
# enabled=false 时登录、同步、退出行为与接入 hub 之前完全一致(一键退回的逃生开关)
|
||||
hub:
|
||||
enabled: true
|
||||
# hub 站点基地址,生产必须 https,结尾不带 /
|
||||
base-url: 'https://hub.oa.unissense.tech'
|
||||
# 本系统在 hub 注册的应用编码;验票响应会回显该值用于防串号
|
||||
app-code: oms
|
||||
# 应用密钥明文,同时用于票据校验与目录导出。只从环境变量注入,不落仓库
|
||||
integration-key: ${HUB_INTEGRATION_KEY:820c8ed5c7b04b7778c84dadce03ce860451f1e0a27e01292c8a03e8941075f7}
|
||||
connect-timeout-ms: 3000
|
||||
read-timeout-ms: 10000
|
||||
login:
|
||||
# 已绑定 hub 的内部账号提交本地 /login 时是否拒绝(外部用户不受影响)。
|
||||
# 关掉它等于允许内部人继续用本系统口令登录,统一登录形同虚设,只作应急手段。
|
||||
reject-bound-local-login: true
|
||||
# 是否允许在 OMS 登录页用统一门户账号密码直接登录(后端代理调 hub 登录接口,
|
||||
# 需要 hub 侧为该账号开启密码通道或配置初始密码)。关掉后内部人只能从门户卡片免登进入。
|
||||
password-login-enabled: true
|
||||
# 统一门户不可达时是否允许绑定账号回退本系统口令。默认关:门户挂了内部人登不进来,
|
||||
# 需要应急时用 admin 改这里或直接把 hub.enabled 置 false。
|
||||
allow-local-fallback: false
|
||||
# 内部用户退出后是否跳转 hub 站点首页
|
||||
logout-redirect-hub: true
|
||||
directory:
|
||||
# 目录同步开关,与登录开关解耦,可先只镜像不接管登录做灰度
|
||||
enabled: true
|
||||
# 花名册条数,hub 取值 1-5000;返回被截断时会自动按上限重拉
|
||||
member-limit: 2000
|
||||
# 是否按「姓名唯一命中」自动绑定存量 OMS 账号。首次上线建议先置 false 跑一轮全量,
|
||||
# 在「hub人员目录」页核对结果后再打开;重名一律不自动绑,交人工。
|
||||
auto-bind-by-name: true
|
||||
# hub 侧新增的人(增量事件里出现、镜像中没有)是否自动建号并绑定。
|
||||
# 注意:全量同步不建号,首次全量匹配不上的人只留在镜像表,由管理员人工处理。
|
||||
auto-create-new: true
|
||||
# hub 停用是否同步停用本地账号(只停用,从不自动启用)
|
||||
disable-missing: true
|
||||
# 单批增量条数,hub 上限 500
|
||||
change-limit: 200
|
||||
# H5 审批系统在 hub 注册的第二个应用。
|
||||
# hub 的票据按应用隔离(验票会比对票据所属应用与调用方密钥),所以 H5 不能用上面那把
|
||||
# 管理端密钥验自己的票,必须在 hub 管理端单独注册一个应用并单独下发密钥。
|
||||
h5:
|
||||
# H5 免登开关(与 hub.enabled 是与关系)。密钥未注入时自动关闭:
|
||||
# H5 的免登只服务已绑定门户的内部人员,关闭后他们仍可用账号密码登录。
|
||||
enabled: true
|
||||
# H5 在 hub 注册的应用编码,用于校验验票回显防串号
|
||||
app-code: oms-wb
|
||||
# H5 的应用密钥明文,只从环境变量注入,不落仓库
|
||||
integration-key: ${HUB_H5_INTEGRATION_KEY:}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,866 @@
|
|||
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>订单审批</title>
|
||||
<style> * {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
|
||||
background-color: #ffffff;
|
||||
color: #333;
|
||||
line-height: 1.6;
|
||||
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 100%;
|
||||
margin: 0 auto;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.header {
|
||||
background: #fff;
|
||||
padding: 15px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.search-form {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
margin-bottom: 5px;
|
||||
font-size: 14px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.form-group input, .form-group select {
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.search-btn {
|
||||
background: #007AFF;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 12px;
|
||||
border-radius: 6px;
|
||||
font-size: 16px;
|
||||
cursor: pointer;
|
||||
width: 100%;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.order-list {
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.order-item {
|
||||
padding: 15px;
|
||||
border-bottom: 1px solid #eee;
|
||||
}
|
||||
|
||||
.order-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.order-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.order-title {
|
||||
font-weight: bold;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.order-status {
|
||||
background: #ff9500;
|
||||
color: white;
|
||||
padding: 3px 8px;
|
||||
border-radius: 10px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.order-info {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.order-info div {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.order-info span:first-child {
|
||||
color: #999;
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
.approve-btn {
|
||||
background: #34C759;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 8px 15px;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
margin-top: 10px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.detail-header {
|
||||
background: #fff;
|
||||
padding: 15px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
|
||||
margin-bottom: 15px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.detail-title {
|
||||
font-size: 20px;
|
||||
font-weight: bold;
|
||||
color: #007AFF;
|
||||
}
|
||||
|
||||
.detail-section {
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
|
||||
margin-bottom: 15px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
background: #f0f0f0;
|
||||
padding: 12px 15px;
|
||||
font-weight: bold;
|
||||
font-size: 16px;
|
||||
border-bottom: 1px solid #eee;
|
||||
}
|
||||
|
||||
.detail-content {
|
||||
padding: 15px;
|
||||
}
|
||||
|
||||
.detail-row {
|
||||
display: flex;
|
||||
margin-bottom: 12px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.detail-label {
|
||||
width: 30%;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.detail-value {
|
||||
width: 70%;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.product-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.product-table th, .product-table td {
|
||||
border: 1px solid #ddd;
|
||||
padding: 8px;
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.product-table th {
|
||||
background: #f8f8f8;
|
||||
}
|
||||
|
||||
.approval-history {
|
||||
padding: 10px;
|
||||
border-left: 3px solid #007AFF;
|
||||
background: #f8f8f8;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.history-item {
|
||||
margin-bottom: 10px;
|
||||
padding-bottom: 10px;
|
||||
border-bottom: 1px dashed #ddd;
|
||||
}
|
||||
|
||||
.history-item:last-child {
|
||||
border-bottom: none;
|
||||
margin-bottom: 0;
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
.history-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.history-user {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.history-status {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.history-content {
|
||||
font-size: 14px;
|
||||
margin: 5px 0;
|
||||
}
|
||||
|
||||
.history-time {
|
||||
font-size: 12px;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.action-buttons {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
padding: 15px;
|
||||
}
|
||||
|
||||
.btn {
|
||||
flex: 1;
|
||||
padding: 15px;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 16px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.btn-reject {
|
||||
background: #FF3B30;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-approve {
|
||||
background: #34C759;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.back-btn {
|
||||
background: #fff;
|
||||
color: #007AFF;
|
||||
border: 1px solid #007AFF;
|
||||
padding: 12px;
|
||||
border-radius: 6px;
|
||||
font-size: 16px;
|
||||
cursor: pointer;
|
||||
width: 100%;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
padding: 40px 20px;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.empty-state img {
|
||||
width: 100px;
|
||||
height: 100px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.nav-tabs {
|
||||
display: flex;
|
||||
border-bottom: 1px solid #e0e0e0;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.nav-tabs li {
|
||||
list-style: none;
|
||||
padding: 10px 10px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
color: #666;
|
||||
border-bottom: 2px solid transparent;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.nav-tabs li.active {
|
||||
color: #007AFF;
|
||||
border-bottom: 2px solid #007AFF;
|
||||
}
|
||||
|
||||
.nav-tabs li:hover {
|
||||
color: #007AFF;
|
||||
}
|
||||
|
||||
.tab-content {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.product-background{
|
||||
background: #fafafa;
|
||||
}
|
||||
.product-code{
|
||||
font-size: 20px;
|
||||
font-weight: bold;
|
||||
}
|
||||
.tab-content.active {
|
||||
display: block;
|
||||
}
|
||||
@media (max-width: 768px) {
|
||||
.search-form {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.order-info {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.detail-row {
|
||||
flex-direction: column;
|
||||
}
|
||||
.product-code{
|
||||
display: flex;
|
||||
font-size: 20px;
|
||||
font-weight: bold ;
|
||||
}
|
||||
.detail-label, .detail-value {
|
||||
width: 100%;
|
||||
}
|
||||
/* 手机屏幕下基本信息字段一排显示 */
|
||||
.basic-info-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
/* 修改手机屏幕下基本信息字段的显示方式 */
|
||||
.basic-info-item {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
margin-bottom: 12px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.basic-info-item .detail-label {
|
||||
width: 30%;
|
||||
color: #666;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.basic-info-item .detail-value {
|
||||
width: 70%;
|
||||
font-weight: 500;
|
||||
text-align: right;
|
||||
}
|
||||
.index-badge {
|
||||
top: 0;
|
||||
right: 0;
|
||||
background-color: #007AFF;
|
||||
color: white;
|
||||
font-size: 12px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border-radius: 2px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container" id="todoPage">
|
||||
<div class="header">
|
||||
<h2>我的审批</h2>
|
||||
<div class="search-form">
|
||||
<div class="form-group">
|
||||
<label></label>
|
||||
<input type="text" id="searchInfo" placeholder="请输入合同编号,项目名称,客户名称搜索">
|
||||
</div>
|
||||
<button class="search-btn" onclick="searchOrders()">搜索</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="order-list" id="orderList">
|
||||
<!-- 订单列表将通过JS动态生成 -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="container" id="approvePage" style="display: none;">
|
||||
<button class="back-btn" onclick="backToTodo()">← 返回待审批列表</button>
|
||||
|
||||
<div class="detail-header">
|
||||
<div class="detail-title">南宁市教育局智慧教育项目订单 Rev.1 • 待审批</div>
|
||||
</div>
|
||||
|
||||
<!-- 增加标签页 -->
|
||||
<ul class="nav-tabs">
|
||||
<li class="active" onclick="changeTab(this)"><span href="#basic-info">基本信息</span></li>
|
||||
<li onclick="changeTab(this)"><span href="#config-info">配置信息</span></li>
|
||||
<li onclick="changeTab(this)"><span href="#attachments">附件</span></li>
|
||||
<li onclick="changeTab(this)"><span href="#approval-process">审批流程</span></li>
|
||||
</ul>
|
||||
|
||||
<!-- 基本信息 -->
|
||||
<div id="basic-info" class="tab-content active">
|
||||
<div class="section-title">基本信息</div>
|
||||
<div class="detail-content">
|
||||
<!-- 在手机屏幕下一排显示 -->
|
||||
<div class="basic-info-row">
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">项目名称:</div>
|
||||
<div class="detail-value" id="detailProjectName">南宁市教育局智慧教育项目</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="basic-info-row">
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">项目编号:</div>
|
||||
<div class="detail-value" id="detailProjectCode">-</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="basic-info-row">
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">最终客户:</div>
|
||||
<div class="detail-value" id="detailCustomerName">-</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="basic-info-row">
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">BG:</div>
|
||||
<div class="detail-value" id="detailBgProperty">-</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="basic-info-row">
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">行业:</div>
|
||||
<div class="detail-value" id="detailIndustryType">-</div>
|
||||
</div>
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">代表处:</div>
|
||||
<div class="detail-value" id="detailAgentName">-</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="basic-info-row">
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">合同编号:</div>
|
||||
<div class="detail-value" id="detailOrderCode">-</div>
|
||||
</div>
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">执行单截止时间:</div>
|
||||
<div class="detail-value" id="detailOrderEndTime">-</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="basic-info-row">
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">币种:</div>
|
||||
<div class="detail-value" id="detailCurrencyType">-</div>
|
||||
</div>
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">总代进货金额:</div>
|
||||
<div class="detail-value" id="detailActualPurchaseAmount">-</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="basic-info-row">
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">总代出货金额:</div>
|
||||
<div class="detail-value" id="detailShipmentAmount">-</div>
|
||||
</div>
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">要求到货时间:</div>
|
||||
<div class="detail-value" id="detailDeliveryTime">-</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="basic-info-row">
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">公司直发:</div>
|
||||
<div class="detail-value" id="detailCompanyDelivery">-</div>
|
||||
</div>
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">下单通路:</div>
|
||||
<div class="detail-value" id="detailOrderChannel">-</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="basic-info-row">
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">供货商:</div>
|
||||
<div class="detail-value" id="detailSupplier">-</div>
|
||||
</div>
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">汇智责任人:</div>
|
||||
<div class="detail-value" id="detailDutyName">-</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="basic-info-row">
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">进货商:</div>
|
||||
<div class="detail-value" id="detailPartnerName">-</div>
|
||||
</div>
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">进货商类型:</div>
|
||||
<div class="detail-value" id="detailLevel">-</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="basic-info-row">
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">其他特别说明:</div>
|
||||
<div class="detail-value" id="detailRemark">-</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 配置信息 -->
|
||||
<div id="config-info" class="tab-content">
|
||||
<div class="section-title">配置信息</div>
|
||||
<div class="detail-content">
|
||||
<div class="config-group" id="productList">
|
||||
<div class="section-title">配置组 1</div>
|
||||
<div class="product-item">
|
||||
<div class="product-name">3130A6LC</div>
|
||||
<div class="product-price">¥16,830.00</div>
|
||||
<div class="product-description">H3C C1100 挂架云终端...</div>
|
||||
<div class="product-quantity">数量: 20</div>
|
||||
<div class="product-unit-price">单价: ¥20</div>
|
||||
</div>
|
||||
<!-- 其他产品项 -->
|
||||
</div>
|
||||
<!-- 其他配置组 -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 附件 -->
|
||||
<div id="attachments" class="tab-content">
|
||||
<div class="section-title">附件</div>
|
||||
<div class="attachment-list" id="attachment-list">
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 审批流程 -->
|
||||
<div id="approval-process" class="tab-content">
|
||||
<div class="section-title">审批流程</div>
|
||||
<div class="approval-history">
|
||||
<div class="history-item">
|
||||
<div class="history-user">成一鸣</div>
|
||||
<div class="history-time">2022-10-10 14:00:00</div>
|
||||
</div>
|
||||
<!-- 其他历史项 -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="action-buttons">
|
||||
<button class="btn btn-reject" onclick="rejectOrder()">驳回</button>
|
||||
<button class="btn btn-approve" onclick="approveOrder()">通过</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
|
||||
|
||||
// 页面初始化
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
searchOrders()
|
||||
});
|
||||
|
||||
function changeTab(that){
|
||||
document.querySelectorAll('.tab-content').forEach(content => {
|
||||
content.classList.remove('active');
|
||||
});
|
||||
document.querySelectorAll('.nav-tabs li').forEach(content => {
|
||||
content.classList.remove('active');
|
||||
});
|
||||
that.classList.add('active');
|
||||
const target = that.querySelector('span').getAttribute('href');
|
||||
document.querySelector(target).classList.add('active');
|
||||
}
|
||||
// 搜索订单
|
||||
async function searchOrders() {
|
||||
// 在实际应用中,这里会调用后端API
|
||||
const formData = new FormData();
|
||||
formData.append('pageSize', '99999');
|
||||
formData.append('pageNum', '1');
|
||||
formData.append('approve', 'approve');
|
||||
const response = await fetch(`http://localhost:28080/project/order/list`, {
|
||||
method: 'POST',
|
||||
mode: 'cors',
|
||||
credentials: 'include',
|
||||
body: formData
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
renderOrderList(data.rows);
|
||||
}
|
||||
|
||||
// 渲染订单列表
|
||||
function renderOrderList(orders) {
|
||||
const orderListElement = document.getElementById('orderList');
|
||||
|
||||
if (orders.length === 0) {
|
||||
orderListElement.innerHTML = ` <div class="empty-state">
|
||||
<div>暂无待审批订单</div>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
let orderItemsHtml = '';
|
||||
orders.forEach(order => {
|
||||
const statusText = getOrderStatusText(order.orderStatus);
|
||||
const statusClass = getOrderStatusClass(order.orderStatus);
|
||||
|
||||
orderItemsHtml += ` <div class="order-item">
|
||||
<div class="order-header">
|
||||
<div class="order-title">${order.orderCode}</div>
|
||||
<div class="order-status ${statusClass}">${statusText}</div>
|
||||
</div>
|
||||
<div class="order-info">
|
||||
<div><span>版本号:</span> ${order.versionCode}</div>
|
||||
<div><span>项目名称:</span> ${order.projectName}</div>
|
||||
<div><span>客户名称:</span> ${order.customerName}</div>
|
||||
<div><span>订单金额:</span> ¥${formatAmount(order.shipmentAmount)}</div>
|
||||
</div>
|
||||
<button class="approve-btn" onclick="showApproveDetail(${order.id})">审批</button>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
orderItemsHtml+=`<div style="text-align: center;color: #bbbbbb;">-------已经到底了-------</div>`
|
||||
orderListElement.innerHTML = orderItemsHtml;
|
||||
}
|
||||
|
||||
// 获取订单状态文本
|
||||
function getOrderStatusText(status) {
|
||||
// switch(status) {
|
||||
// case '0': return '待审批';
|
||||
// case '1': return '已通过';
|
||||
// case '2': return '已驳回';
|
||||
// default: return '未知';
|
||||
// }
|
||||
return '待审批'
|
||||
}
|
||||
|
||||
// 获取订单状态样式类
|
||||
function getOrderStatusClass(status) {
|
||||
// switch(status) {
|
||||
// case '0': return 'status-pending';
|
||||
// case '1': return 'status-approved';
|
||||
// case '2': return 'status-rejected';
|
||||
// default: return '';
|
||||
// }
|
||||
return 'status-pending';
|
||||
}
|
||||
|
||||
// 格式化金额
|
||||
function formatAmount(amount) {
|
||||
if (!amount) return '0.00';
|
||||
return parseFloat(amount).toLocaleString('zh-CN', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2
|
||||
});
|
||||
}
|
||||
|
||||
// 显示审批详情
|
||||
async function showApproveDetail(orderId) {
|
||||
// 在实际应用中,这里会调用后端API
|
||||
|
||||
const response = await fetch(`http://localhost:28080/project/order/h5/approve/${orderId}`, {
|
||||
method: 'GET',
|
||||
mode: 'cors',
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
// 在实际应用中,这里会根据orderId获取详细信息
|
||||
document.getElementById('todoPage').style.display = 'none';
|
||||
document.getElementById('approvePage').style.display = 'block';
|
||||
let projectOrderInfo = data.data.projectOrderInfo;
|
||||
// 填充订单详情
|
||||
document.getElementById('detailProjectName').textContent = projectOrderInfo.projectName;
|
||||
document.getElementById('detailProjectCode').textContent = projectOrderInfo.projectCode;
|
||||
document.getElementById('detailCustomerName').textContent = projectOrderInfo.customerName;
|
||||
document.getElementById('detailOrderCode').textContent = projectOrderInfo.orderCode;
|
||||
document.getElementById('detailAgentName').textContent = projectOrderInfo.agentName;
|
||||
document.getElementById('detailDutyName').textContent = projectOrderInfo.dutyName;
|
||||
document.getElementById('detailPartnerName').textContent = projectOrderInfo.partnerName;
|
||||
document.getElementById('detailDeliveryTime').textContent = projectOrderInfo.deliveryTime;
|
||||
document.getElementById('detailOrderEndTime').textContent = projectOrderInfo.orderEndTime;
|
||||
document.getElementById('detailBgProperty').textContent = getDictLabel('bg_type', projectOrderInfo.bgProperty);
|
||||
document.getElementById('detailIndustryType').textContent = projectOrderInfo.industryType;
|
||||
document.getElementById('detailCurrencyType').textContent = getDictLabel('currency_type', projectOrderInfo.currencyType);
|
||||
document.getElementById('detailCompanyDelivery').textContent = getDictLabel('company_delivery', projectOrderInfo.companyDelivery);
|
||||
document.getElementById('detailOrderChannel').textContent = projectOrderInfo.orderChannel === '1' ? '总代' : '直签';
|
||||
document.getElementById('detailSupplier').textContent = projectOrderInfo.supplier;
|
||||
document.getElementById('detailLevel').textContent = getDictLabel('identify_level', projectOrderInfo.level);
|
||||
document.getElementById('detailRemark').textContent = projectOrderInfo.remark || '-';
|
||||
document.getElementById('detailActualPurchaseAmount').textContent = projectOrderInfo.actualPurchaseAmount ? `¥${formatAmount(projectOrderInfo.actualPurchaseAmount)}` : '-';
|
||||
document.getElementById('detailShipmentAmount').textContent = projectOrderInfo.shipmentAmount ? `¥${formatAmount(projectOrderInfo.shipmentAmount)}` : '-';
|
||||
// let projectOrderInfo = data.data.p;
|
||||
|
||||
// 填充产品信息
|
||||
const productListElement = document.getElementById('productList');
|
||||
let productHtml = '';
|
||||
if((projectOrderInfo.softwareProjectProductInfoList||[]).length>0){
|
||||
productHtml+=generateProductColumn('软件产品', projectOrderInfo.softwareProjectProductInfoList)
|
||||
}
|
||||
if((projectOrderInfo.hardwareProjectProductInfoList||[]).length>0){
|
||||
productHtml+=generateProductColumn('终端产品', projectOrderInfo.hardwareProjectProductInfoList)
|
||||
}
|
||||
|
||||
if((projectOrderInfo.maintenanceProjectProductInfoList||[]).length>0){
|
||||
productHtml+=generateProductColumn('服务产品', projectOrderInfo.maintenanceProjectProductInfoList)
|
||||
}
|
||||
|
||||
productListElement.innerHTML = productHtml;
|
||||
//填充附件
|
||||
let contractFileData = projectOrderInfo.contractTableData[projectOrderInfo.versionCode];
|
||||
let attachmentHtml = ``;
|
||||
if (contractFileData){
|
||||
contractFileData.forEach(file => {
|
||||
if (file.id!=-1){
|
||||
attachmentHtml += `
|
||||
<div class="attachment-item">
|
||||
<span onclick="preview('${file.filePath}','${file.fileName}')">${file.fileName}</a>
|
||||
</div>`
|
||||
}
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
document.getElementById('attachment-list').innerHTML=attachmentHtml
|
||||
let approveLog = data.data.approveLog;
|
||||
|
||||
// 填充审批历史
|
||||
const approvalHistoryElement = document.getElementById('approvalHistory');
|
||||
let historyHtml = '';
|
||||
approveLog.forEach(history => {
|
||||
const statusText = history.approveStatus === 3 ? '批准' : history.approveStatus === 2 ? '驳回' : '提交审批';
|
||||
historyHtml += ` <div class="history-item">
|
||||
<div class="history-header">
|
||||
<div class="history-user">${history.approveUserName} (${history.roleName})</div>
|
||||
<div class="history-status">${statusText}</div>
|
||||
</div>
|
||||
<div class="history-content">${history.approveOpinion}</div>
|
||||
<div class="history-time">${history.approveTime}</div>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
approvalHistoryElement.innerHTML = historyHtml || '<div>暂无审批记录</div>';
|
||||
}
|
||||
|
||||
function preview(filePath, fileName) {
|
||||
if (filePath.endsWith(".png") || filePath.endsWith(".jpg") || filePath.endsWith(".jpeg") || filePath.endsWith(".pdf")) {
|
||||
let url = `/project/order/file/view?filePath=` + encodeURI(filePath) + '&fileName=' + encodeURI(fileName)
|
||||
window.open(url)
|
||||
} else {
|
||||
downFile(filePath, fileName)
|
||||
}
|
||||
}
|
||||
function downFile(filePath, fileName) {
|
||||
window.location.href = `/project/order/file/download?filePath=` + encodeURI(filePath) + '&fileName=' + encodeURI(fileName);
|
||||
}
|
||||
// 获取字典标签文本
|
||||
function getDictLabel(dictType, value) {
|
||||
// 在实际应用中,这里会从后端获取字典数据
|
||||
const dictMap = {
|
||||
'bg_type': { 'YYS': '运营商', 'JY': '教育', 'ZF': '政府' },
|
||||
'currency_type': { 'CNY': '人民币', 'USD': '美元' },
|
||||
'company_delivery': { '0': '否', '1': '是' },
|
||||
'identify_level': { '1': '一级代理', '2': '二级代理' }
|
||||
};
|
||||
|
||||
return dictMap[dictType] && dictMap[dictType][value] ? dictMap[dictType][value] : value;
|
||||
}
|
||||
|
||||
// 返回待审批列表
|
||||
function backToTodo() {
|
||||
document.getElementById('approvePage').style.display = 'none';
|
||||
document.getElementById('todoPage').style.display = 'block';
|
||||
}
|
||||
|
||||
// 驳回订单
|
||||
function rejectOrder() {
|
||||
const reason = prompt('请输入驳回意见:');
|
||||
if (reason) {
|
||||
alert(`订单已驳回,驳回意见: ${reason}`);
|
||||
// 在实际应用中,这里会调用后端API提交驳回意见
|
||||
backToTodo();
|
||||
}
|
||||
}
|
||||
|
||||
function generateProductColumn(title,dataList){
|
||||
let productHtml = `
|
||||
<div class="section-title">${title}</div>
|
||||
`;
|
||||
dataList.forEach((product,index) => {
|
||||
productHtml += `<div class="product-background">
|
||||
<div class="index-badge">${index + 1}</div>
|
||||
<div class="product-code "> <div style="width: 50%">${product.productBomCode}</div>
|
||||
<div style=" text-align: right; width: 50%;" >¥${product.allPrice}</div></div>
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">产品型号:</div>
|
||||
<div class="detail-value" >${product.model}</div>
|
||||
</div>
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">描述:</div>
|
||||
<div class="detail-value" >${product.productDesc}</div>
|
||||
</div>
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">数量:</div>
|
||||
<div class="detail-value" >${product.quantity}</div>
|
||||
</div>
|
||||
<div class="basic-info-item">
|
||||
<div class="detail-label">单价:</div>
|
||||
<div class="detail-value" >¥${product.price}</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
})
|
||||
return productHtml;
|
||||
}
|
||||
|
||||
// 通过订单
|
||||
function approveOrder() {
|
||||
const reason = prompt('请输入通过意见:');
|
||||
if (reason) {
|
||||
alert(`订单已通过,通过意见: ${reason}`);
|
||||
// 在实际应用中,这里会调用后端API提交通过意见
|
||||
backToTodo();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,34 @@
|
|||
package com.ruoyi.framework.hub;
|
||||
|
||||
/**
|
||||
* hub 侧账号信息查询入口。
|
||||
*
|
||||
* <p>实现放在 {@code ruoyi-sip} 的 hub 人员目录镜像({@code sys_hub_user})上:
|
||||
* framework 只依赖 {@code ruoyi-system},看不到本项目的业务表,因此这里只声明契约、
|
||||
* 由业务侧注入实现。没有实现(模块未加载)时门户直登自动降级为「不可用」,
|
||||
* 门户票据免登不受影响。</p>
|
||||
*
|
||||
* @author codex
|
||||
*/
|
||||
public interface HubAccountLookup
|
||||
{
|
||||
/**
|
||||
* 按 hub 用户ID取门户账号信息。
|
||||
*
|
||||
* @param hubUserId {@code sys_user.hub_user_id}
|
||||
* @return 账号视图;镜像里没有这个人(比如从未跑过全量同步)时返回 null
|
||||
*/
|
||||
public HubAccountView findByHubUserId(Long hubUserId);
|
||||
|
||||
/**
|
||||
* 按统一门户账号(或邮箱)反查这个人,用于「登录页输入的是门户账号」的场景。
|
||||
*
|
||||
* <p>hub 侧账号匹配是<b>大小写不敏感并去首尾空格</b>的({@code normalizeAccount}),
|
||||
* 实现方要保持同样口径,否则会出现「hub 能登录、OMS 找不到人」。同时命中多人时
|
||||
* 返回 null——宁可不认,也不要把口令判给了另一个人。</p>
|
||||
*
|
||||
* @param account 用户输入的统一门户账号或邮箱
|
||||
* @return 账号视图(含 {@code hubUserId});查不到或不唯一时返回 null
|
||||
*/
|
||||
public HubAccountView findByAccount(String account);
|
||||
}
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
package com.ruoyi.framework.hub;
|
||||
|
||||
/**
|
||||
* hub 侧账号信息(供 OMS 代理门户口令登录时使用)。
|
||||
*
|
||||
* <p>内部人员在 OMS 登录页输入的是<b>统一门户的账号</b>,而 hub 校验口令只认它自己的
|
||||
* {@code account}(或邮箱),所以两个方向都需要这份来自人员目录镜像的视图:
|
||||
* 用门户账号找到本地账号({@link #hubUserId}),再用门户账号去 hub 判口令。</p>
|
||||
*
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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)。
|
||||
*
|
||||
* <p>游标语义:{@code cursor} 是本批最后一条的 seq,本批无变更时等于传入的 since;
|
||||
* {@code hasMore=true} 时必须用同一个 cursor 继续拉取直到 false 才能提交游标;
|
||||
* {@code since < oldestSeq} 说明中间流水已不可靠,必须回到全量。</p>
|
||||
*
|
||||
* <p>变更写入是尽力而为,写失败只记日志不影响业务请求,因此增量流不能作为唯一可信来源,
|
||||
* 必须配合每日全量校对。</p>
|
||||
*
|
||||
* @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<JSONObject> 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<JSONObject> 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<JSONObject> getChanges()
|
||||
{
|
||||
return changes;
|
||||
}
|
||||
}
|
||||
|
|
@ -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 开放接口客户端。
|
||||
*
|
||||
* <p>覆盖下游需要的四件事:校验门户票据、导出全量目录、拉取增量变更、代理门户账号密码登录。
|
||||
* 四类调用都用同一把应用密钥({@code X-Integration-Key}),不额外配目录密钥,也都走
|
||||
* {@code /api/v1/**} 的统一信封({@code {code,msg,data}}),因此共用 {@link #exchange}。</p>
|
||||
*
|
||||
* <p>刻意不调门户站点自用的 {@code /auth/login}:那个接口强制要求它自己的图形验证码,
|
||||
* 会让用户在本系统那张码之外再多填一张。hub 为「下游自己管人机校验、只要 hub 判口令对错」
|
||||
* 专门开了口令代校验(对接指南 2.8),见 {@link #verifyPassword}。</p>
|
||||
*
|
||||
* <p>硬性约束(来自 hub 对接指南 8.4):<b>禁止对票据校验自动重试</b>。hub 对票据是
|
||||
* 「先查询、立即删除」,超时后无法判断 hub 是否已消费,重试只会让第二次必然
|
||||
* {@code ticket_invalid},正确做法是丢弃当前票据让用户重新发起跳转。</p>
|
||||
*
|
||||
* <p>本类不抛业务异常给调用方之外的一致性保证:网络与响应体异常统一转成
|
||||
* {@link HubException},由调用方决定是「拒绝登录」还是「本轮同步跳过」。</p>
|
||||
*
|
||||
* @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} 而<b>不是</b>「口令错误」,所以本地先拦掉,
|
||||
* 免得把用户输错的长口令报成「统一门户暂时不可用」。
|
||||
*/
|
||||
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})。
|
||||
*
|
||||
* <p>这条链路是 hub 特意为「下游自己管人机校验、只把口令判对判错交给 hub」开的:
|
||||
* 用同一把 {@code X-Integration-Key},走统一信封,<b>不要求门户图形验证码</b>,
|
||||
* 也不签发任何 hub 令牌。判定与 hub 登录页同一套(账号是否启用、密码通道、
|
||||
* 连续失败锁定、bcrypt 比对),所以在 OMS 这边输错 5 次同样会把这个人的门户账号锁 15 分钟。</p>
|
||||
*
|
||||
* <p>OMS 的 {@code login_name} 存的是手机号,与 hub 的 {@code account} 不是一回事,
|
||||
* 因此调用方必须传镜像表里的 hub 账号;账号缺失时退回邮箱(hub 的 account 字段
|
||||
* 同时接受邮箱,见 {@code MySQLUserRepository#FindByAccount})。邮箱也长到超过
|
||||
* account 的 190 位上限时不猜,直接判不可用。</p>
|
||||
*
|
||||
* <p>口令不记日志;hub 侧审计也只记账号。</p>
|
||||
*
|
||||
* @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}。
|
||||
*
|
||||
* <p>hub 的口径与票据校验一致:口令层面的不通过也是 HTTP 200 + {@code active:false} +
|
||||
* {@code reason}(三种 reason 见对接指南 2.8 的表),只有调用方自己的凭据有问题才是
|
||||
* 401/403,那种情况已被 {@code exchange} 转成 HubException 归为不可达。</p>
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读统一门户当前生效的口令要求(长度、字符类别、是否禁常见口令)。
|
||||
*
|
||||
* <p>改密表单的校验规则属于 hub,本系统不要抄一份写死的规则(对接指南 2.7、2.8
|
||||
* 都强调了这一点),因此直接把它读回来给前端用。这个接口免登录,返回裸 JSON。</p>
|
||||
*
|
||||
* @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})。
|
||||
*
|
||||
* <p>与口令代校验同一把集成密钥、同一个统一信封、同一条判定链:账号是否启用、密码通道是否
|
||||
* 开通、失败锁定、当前口令比对全部由 hub 判,本系统不复刻口令规则。当前口令必填——hub 用它
|
||||
* 证明「改的是谁的口令」,应用密钥只证明「谁在调」。</p>
|
||||
*
|
||||
* <p>口令不合规时 hub 会把当时生效的 requirements 一起回出来,前端按它重新渲染表单,
|
||||
* 不要在本系统写死长度与字符类别(对接指南 2.7、11)。</p>
|
||||
*
|
||||
* @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}。
|
||||
*
|
||||
* <p>hub 的口径与代校验一致:口令层面的不通过也是 HTTP 200 + {@code changed:false} +
|
||||
* {@code reason}(五种取值见对接指南 2.8.1 的表),调用方凭据有问题才是 401/403,
|
||||
* 那种情况已被 {@code exchange} 转成 HubException 归为不可达。</p>
|
||||
*/
|
||||
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 也原样带回状态码与已解析响应体。
|
||||
*
|
||||
* <p>门户的 {@code /auth/**} 是裸 JSON(如免登录的口令要求),不带统一信封,
|
||||
* 所以这里不抛业务异常,由调用方按状态码自行判定。</p>
|
||||
*/
|
||||
private RawResponse rawCall(String path, HttpMethod method, HttpEntity<?> entity, String action)
|
||||
{
|
||||
String url = properties.getNormalizedBaseUrl() + path;
|
||||
ResponseEntity<String> 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<HubDirectoryUser> parseUsers(JSONArray array)
|
||||
{
|
||||
if (array == null || array.isEmpty())
|
||||
{
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<HubDirectoryUser> 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 信封。
|
||||
*
|
||||
* <p>日志只记路径、HTTP 状态与 hub 业务码,不记票据与密钥,也不记完整响应体
|
||||
* (票据不能进日志,响应体里含个人信息)。</p>
|
||||
*/
|
||||
private JSONObject exchange(String path, HttpMethod method, HttpEntity<?> entity, String action)
|
||||
{
|
||||
String url = properties.getNormalizedBaseUrl() + path;
|
||||
ResponseEntity<String> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
package com.ruoyi.framework.hub;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* hub 全量目录导出结果(只取同步需要的用户维度)。
|
||||
*
|
||||
* <p>{@link #isTruncated()} 为 true 说明被 member_limit 截断,必须提高上限重拉,
|
||||
* 不能把这一份当完整目录用,否则会把没返回的人误判成「hub 已没有这个人」。</p>
|
||||
*
|
||||
* @author codex
|
||||
*/
|
||||
public class HubDirectoryResult
|
||||
{
|
||||
private List<HubDirectoryUser> users = new ArrayList<>();
|
||||
|
||||
private long totalUsers;
|
||||
|
||||
private long returnedUsers;
|
||||
|
||||
private int memberLimit;
|
||||
|
||||
private boolean truncated;
|
||||
|
||||
private long permissionVersion;
|
||||
|
||||
public List<HubDirectoryUser> getUsers()
|
||||
{
|
||||
return users;
|
||||
}
|
||||
|
||||
public void setUsers(List<HubDirectoryUser> 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,132 @@
|
|||
package com.ruoyi.framework.hub;
|
||||
|
||||
/**
|
||||
* hub 全量目录成员项(GET /api/v1/auth/directory 的 users 元素)。
|
||||
*
|
||||
* <p>注意 hub 侧的已知限制:全量目录的成员项<b>不含 phone</b>,只有
|
||||
* {@code source=wecom} 的增量事件才携带手机号,因此 {@link #getPhone()} 在全量场景恒为空,
|
||||
* 手机号为空一律跳过匹配(方案已定口径)。</p>
|
||||
*
|
||||
* @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 侧是否「明确处于停用」。
|
||||
*
|
||||
* <p>必须与 {@link #isEnabled()} 分开:增量流的摘要事件(如调整组织只带
|
||||
* {@code {id, organization_id}})不带 status,此时 status 为 null,
|
||||
* 若按「非启用即停用」处理,一次调整组织就会把在职人员停用。</p>
|
||||
*/
|
||||
public boolean isKnownDisabled()
|
||||
{
|
||||
return status != null && status != 1;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
package com.ruoyi.framework.hub;
|
||||
|
||||
/**
|
||||
* hub 调用异常:网络不可达、信封异常、密钥无效等「无法得出结论」的情况。
|
||||
*
|
||||
* <p>与「hub 明确回答这个人不行」(票据 active=false)区分开:后者是正常业务结果,
|
||||
* 走 {@link HubTicketResult#getReason()},不走异常。</p>
|
||||
*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
package com.ruoyi.framework.hub;
|
||||
|
||||
/**
|
||||
* hub 免登失败:票据无效、账号未绑定、账号已停用等「本次登录不成立」的情况。
|
||||
*
|
||||
* <p>调用方一律把用户送回统一门户,不得回落到本地口令登录。</p>
|
||||
*
|
||||
* @author codex
|
||||
*/
|
||||
public class HubLoginException extends RuntimeException
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public HubLoginException(String message)
|
||||
{
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,138 @@
|
|||
package com.ruoyi.framework.hub;
|
||||
|
||||
/**
|
||||
* hub 账号密码登录结果(POST /auth/login,裸 JSON,不走统一信封)。
|
||||
*
|
||||
* <p>本系统不保存内部人员的口令,OMS 登录页对已绑定账号只做「代理校验」:把用户在
|
||||
* OMS 输入的门户口令转交 hub 校验,hub 说了算。因此这里必须把 hub 的每一种失败
|
||||
* 都区分开,让上层能给出可行动的提示,不能统统压成「账号或密码错误」。</p>
|
||||
*
|
||||
* <p>hub 侧状态码语义(对接指南 2.3、2.3.1、9.3):
|
||||
* 200 成功(含「口令正确但需强制改密」);400 验证码错/参数无效;
|
||||
* 401 账号或密码错误;403 账号锁定 / 该账号已关闭密码登录。</p>
|
||||
*
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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 会话。
|
||||
*
|
||||
* <p>认证走 {@link HubPortalToken} + 既有 {@code UserRealm},从而与账号密码登录共用同一条
|
||||
* 会话与在线用户登记链路(kickout、onlineSession、sys_user_online 全部照常生效),
|
||||
* 不另起一套 WebSubject。参照 {@code McpBotAuthFilter} 的先例,但那里是请求级临时主体,
|
||||
* 免登需要可复用的持久会话,因此必须走 {@code subject.login}。</p>
|
||||
*
|
||||
* <p>本类还负责「在 OMS 登录页用统一门户账号密码直接登录」:已绑定账号的口令由 hub 校验,
|
||||
* OMS 只是代理。走的是 hub 的「口令代校验」(对接指南 2.8):用集成密钥只问「这个账号配这个
|
||||
* 口令对不对」,hub 不签发令牌、也不要它自己的图形验证码,因此前端始终只有一张本系统验证码,
|
||||
* 人机校验由本系统承担({@link #usesHubPassword} 供 {@code /login} 分流,
|
||||
* {@link #loginByPassword} 完成校验与会话建立)。OMS 不保存也不比对内部人员的口令。</p>
|
||||
*
|
||||
* <p>硬性约束:票据缺失、过期或 {@code active:false} 时一律拒绝并结束本次登录,
|
||||
* <b>不得</b>回落到本地口令校验,也不得复用旧会话。门户直登同样不得在「门户判定口令错误」时
|
||||
* 回退本地口令,只有门户<b>不可达</b>且显式开启 {@code hub.login.allow-local-fallback} 才回退。</p>
|
||||
*
|
||||
* @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<HubAccountLookup> accountLookupProvider;
|
||||
|
||||
public HubLoginService(HubProperties properties, HubClient hubClient, SysUserMapper userMapper,
|
||||
SysLoginService loginService, ObjectProvider<HubAccountLookup> 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} 的分流依据)。
|
||||
*
|
||||
* <p>统一登录未启用、账号未绑定,一律走本地口令,外部用户与 {@code admin} 不受影响。
|
||||
* 已绑定但目录镜像里查不到门户账号、或该人员被管理员忽略,仍然按「走门户」处理,
|
||||
* 由 {@link #loginByPassword} 给出可行动的原因;这种时候放回本地口令等于悄悄放行了一份
|
||||
* 建号时的默认密码,是统一登录的漏洞,不能图省事放行。</p>
|
||||
*/
|
||||
public boolean usesHubPassword(SysUser user)
|
||||
{
|
||||
return isPasswordLoginEnabled() && user != null && user.getHubUserId() != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户在登录页输入的是<b>统一门户账号</b>时,反查它对应的本地账号。
|
||||
*
|
||||
* <p>内部人员的身份与口令都在门户那边,账号自然也应该是门户账号;但本系统的
|
||||
* {@code sys_user.login_name} 是历史数据(手机号 / 域账号),两者不同源,所以只能靠
|
||||
* 人员目录镜像把门户账号换算成 {@code hub_user_id},再找回绑定的本地账号。</p>
|
||||
*
|
||||
* <p>查不到、不唯一、该人被管理员忽略,都返回 {@code null} 让调用方继续按本地账号处理,
|
||||
* 绝不因为「像是门户账号」就把外部用户的本地登录抢走。</p>
|
||||
*
|
||||
* @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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用统一门户的账号密码完成登录并建立本地会话。
|
||||
*
|
||||
* <p>hub 侧走「口令代校验」(对接指南 2.8):用集成密钥只判口令,不签发 hub 令牌,
|
||||
* 也<b>不要求门户图形验证码</b>——人机校验由本系统自己那张验证码承担。注意调用方必须自己
|
||||
* 检查 {@code ShiroConstants.CURRENT_CAPTCHA}:{@code captchaValidate} 过滤器只把失败结论
|
||||
* 写成请求属性、不拦请求,而本方法不经过 {@code SysLoginService#login},漏检等于免验证码。</p>
|
||||
*
|
||||
* @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)。
|
||||
*
|
||||
* <p>内部人员的口令不在本系统,所以「个人中心改密码」必须改走门户:留在本地改,改的是
|
||||
* 一条没人再用的历史口令,本人下次用门户密码进来还是旧的。</p>
|
||||
*
|
||||
* <p>门户要求<b>当前口令必填</b>:应用密钥只证明「哪个系统在调」,当前口令才证明「改的是
|
||||
* 谁的口令」,这一条也挡住了密钥泄露后静默改写全员口令。判定链与登录、代校验共用,
|
||||
* 当前口令错一样计入失败锁定(5 次锁 15 分钟),所以本系统不要拿它当免费的口令字典。</p>
|
||||
*
|
||||
* <p>「需要强制改密」不影响这里:门户的认证链只比对口令,口令过期照样证明得了身份
|
||||
* ({@code authenticate} 的口径),所以登录被 603 拦下的人也能用这台接口当场改完。</p>
|
||||
*
|
||||
* @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();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录页改密用:按用户输入的账号找回<b>已绑定门户</b>的本地账号。
|
||||
*
|
||||
* <p>查找顺序与 {@code /login} 完全一致(先本地登录名、再按门户账号反查),两处顺序不同
|
||||
* 会让「在登录页改密码」和「在登录页登录」认成不同的人。</p>
|
||||
*
|
||||
* @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})。
|
||||
*
|
||||
* <p>只在「门户不可达」这一种情况下走到这里:门户明确判定口令错误 / 账号锁定时绝不允许回退,
|
||||
* 否则等于给统一登录开了个本地后门。改密不走这条兜底(见 {@link #changePassword})。</p>
|
||||
*/
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,113 @@
|
|||
package com.ruoyi.framework.hub;
|
||||
|
||||
/**
|
||||
* 统一门户服务端改密结果(对接指南 2.8.1:{@code POST /api/v1/auth/password-change})。
|
||||
*
|
||||
* <p>hub 的口令类不通过也是 HTTP 200 + {@code changed:false} + {@code reason},只有调用方凭据
|
||||
* 有问题才是 401/403,网络与门户故障另归「不可达」——三者必须分开:把人误报成「当前密码不正确」
|
||||
* 会让人反复重试直到账号被锁。</p>
|
||||
*
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
package com.ruoyi.framework.hub;
|
||||
|
||||
import org.apache.shiro.authc.UsernamePasswordToken;
|
||||
|
||||
import com.ruoyi.common.core.domain.entity.SysUser;
|
||||
|
||||
/**
|
||||
* hub 门户票据免登所用的认证令牌。
|
||||
*
|
||||
* <p>继承 {@link UsernamePasswordToken} 是为了复用 {@code UserRealm} 与既有的会话、
|
||||
* 在线用户登记链路,同时用 {@link #getHubUser()} 让 Realm 识别「身份已由 hub 确认、
|
||||
* 不再校验本地口令」。密码位填一个恒不匹配的占位值,避免 null 进入 Realm。</p>
|
||||
*
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,372 @@
|
|||
package com.ruoyi.framework.hub;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* dsh-hub 统一登录与人员同步配置。
|
||||
*
|
||||
* <p>密钥只从环境变量或配置中心注入,不落仓库;{@link #enabled} 为 false 时
|
||||
* 登录、同步、退出行为必须与接入 hub 之前完全一致(一键退回的逃生开关)。</p>
|
||||
*
|
||||
* @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} 时是否拒绝。
|
||||
*
|
||||
* <p>true(默认):绑定账号的口令由 hub 校验,本地 {@code /login} 直接拒绝并提示走门户,
|
||||
* 避免有人用旧的 OMS 口令绕过统一登录。false:绑定账号也能用本地口令登录。</p>
|
||||
*/
|
||||
private boolean rejectBoundLocalLogin = true;
|
||||
|
||||
/**
|
||||
* 是否允许「在 OMS 登录页用统一门户账号密码直接登录」。
|
||||
*
|
||||
* <p>true(默认):已绑定账号在 OMS 登录页输入的口令转发 hub 校验,门户挂了就是登不进来;
|
||||
* false:登录页只服务外部用户,内部人员一律从门户卡片免登进入。</p>
|
||||
*/
|
||||
private boolean passwordLoginEnabled = true;
|
||||
|
||||
/**
|
||||
* hub 不可达时是否允许绑定账号回退本地口令登录。
|
||||
*
|
||||
* <p>默认 false,即「统一登录开启时本地口令不参与登录」,与 OMS 口令只作为
|
||||
* 建号初始密码的口径一致。设为 true 时,只有在 hub 网络异常/5xx(不是口令错)
|
||||
* 的情况下才会用本地口令兜底,口令错与锁定一律不回退。</p>
|
||||
*/
|
||||
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 账号。
|
||||
*
|
||||
* <p>关掉它等于全部交人工:镜像照做,但一个都不自动绑,管理员在「hub 人员目录」页
|
||||
* 逐个确认。首次上线建议先关掉跑一轮全量、核对绑定结果,再打开。</p>
|
||||
*/
|
||||
private boolean autoBindByName = true;
|
||||
|
||||
/**
|
||||
* hub 侧新增的人(增量事件里本地镜像没有这个人)是否自动建号并绑定。
|
||||
*
|
||||
* <p>只作用于新增;首次全量里匹配不上的人不建号,留在镜像表由管理员处理(ADR-0017)。</p>
|
||||
*/
|
||||
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 注册的第二个应用。
|
||||
*
|
||||
* <p>hub 的票据按应用隔离(验票会比对票据所属应用与调用方密钥),所以 H5 不能用管理端那把
|
||||
* 密钥验自己的票,必须单独注册应用、单独下发密钥,混用必然 {@code ticket_audience_mismatch}。</p>
|
||||
*/
|
||||
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 自己的开关与密钥齐备。
|
||||
*
|
||||
* <p>这里刻意与管理端调用同口径:否则 {@code /status} 会报 enabled:true 而验票时再失败,
|
||||
* 前端只能看到一个更晚、更难解释的错误。</p>
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,122 @@
|
|||
package com.ruoyi.framework.hub;
|
||||
|
||||
/**
|
||||
* hub 票据校验结果(POST /api/v1/auth/tickets/verify 的 data)。
|
||||
*
|
||||
* <p>票据类失败一律 HTTP 200 且 code 为 "200",由 {@code active=false} 与 {@code reason}
|
||||
* 表达,因此判定成功必须看 active,不能只看 HTTP 状态码。</p>
|
||||
*
|
||||
* @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 "登录票据无效或已被使用,请回到统一门户重新进入";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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());
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理指定用户授权信息缓存
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -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 目录同步定时任务。
|
||||
*
|
||||
* <p>放在 {@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()}。</p>
|
||||
*
|
||||
* <p>两个入口都必须能在 hub 未启用时空转返回,不能抛异常,否则定时任务页会持续报红。</p>
|
||||
*
|
||||
* @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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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 审批系统的门户票据免登入口。
|
||||
*
|
||||
* <p>H5({@code D:\java\workspace\ai\oms_vue},Vue3 + Vant)与本系统同域部署在同一台机器上,
|
||||
* 认证同样依赖 Shiro 会话 Cookie,所以免登只需要「验票 + 建会话」,不需要另外签发令牌。</p>
|
||||
*
|
||||
* <p>落地链路:门户点 H5 卡片 → hub 302 到 {@code https://<H5域名>/sso?ticket=..} →
|
||||
* H5 落地页把 ticket POST 给本接口 → 后端用 <b>H5 自己的应用密钥</b>验票 → 建立本地会话。
|
||||
* hub 的票据按应用隔离(对接指南 8.1),管理端密钥验不了 H5 的票,因此配置段是
|
||||
* {@code hub.h5.*},密钥必须在 hub 管理端单独注册应用后单独下发。</p>
|
||||
*
|
||||
* <p>安全约定与管理端一致(对接指南 8.4、11):ticket 不入库、不写日志、不重试;
|
||||
* 票据无效一律回门户,不回落本地口令。</p>
|
||||
*
|
||||
* @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 免登是否可用与门户地址,供前端决定提示文案与退出后跳去哪里。
|
||||
*
|
||||
* <p>只暴露非敏感信息,绝不下发密钥。</p>
|
||||
*/
|
||||
@Anonymous
|
||||
@GetMapping("/status")
|
||||
public AjaxResult status()
|
||||
{
|
||||
Map<String, Object> 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「忘记密码」页决定改密走门户还是走原本的邮箱验证码。
|
||||
*
|
||||
* <p>已绑定账号的口令归门户管,用本系统的邮箱重置只会改掉一份没人再用的本地口令,
|
||||
* 所以前端必须先问一句。未绑定(外部用户)返回 {@code bound:false},原流程不变。</p>
|
||||
*/
|
||||
@Anonymous
|
||||
@GetMapping("/bound")
|
||||
public AjaxResult bound(String account)
|
||||
{
|
||||
Map<String, Object> 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<String, String> 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<String, String> 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<String, Object> 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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 侧)。
|
||||
*
|
||||
* <p>落地链路:门户点卡片 → hub 302 到前端 {@code /sso/hub?ticket=..&state=..} →
|
||||
* 前端把 ticket POST 给本接口 → 后端带 {@code X-Integration-Key} 服务端验票 →
|
||||
* 建立本地会话。票据只在后端与 hub 之间出现,浏览器不参与校验。</p>
|
||||
*
|
||||
* <p>「不常上门户的人直接在 OMS 登录页登录」不在本类:那条路复用本系统的
|
||||
* {@code POST /login},由它按绑定关系决定口令归谁判(见 {@code SysLoginController}
|
||||
* 与 {@code HubLoginService#loginByPassword}),前端始终只有一张本系统验证码。</p>
|
||||
*
|
||||
* <p>安全约定(对接指南 8.4、11):ticket 不入库、不写日志、不重试;
|
||||
* state 尽力校验(门户跳转不生成 state);票据无效一律回 hub,不回落本地口令。</p>
|
||||
*
|
||||
* @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 基地址,供前端决定是否显示门户入口、退出后跳去哪里。
|
||||
*
|
||||
* <p>只暴露非敏感信息,绝不下发密钥。</p>
|
||||
*/
|
||||
@Anonymous
|
||||
@GetMapping("/status")
|
||||
public AjaxResult status()
|
||||
{
|
||||
Map<String, Object> 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<String, String> 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<String, String> 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<String, Object> 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());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 门户改密表单的口令要求(长度、字符类别等)。
|
||||
*
|
||||
* <p>规则归门户的管理端系统参数,本系统不抄一份写死的 {@code 8..20}:抄了就会随管理员
|
||||
* 调参漂移(对接指南 2.7、11)。前端拿它渲染提示与前置校验,门户仍是最终裁判。</p>
|
||||
*/
|
||||
@Anonymous
|
||||
@GetMapping("/passwordPolicy")
|
||||
public AjaxResult passwordPolicy()
|
||||
{
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("requirements", hubLoginService.passwordRequirements());
|
||||
return AjaxResult.success(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 已绑定门户的账号改口令:不跳转门户页面,由本系统收新口令后交给门户写入(对接指南 2.8.1)。
|
||||
*
|
||||
* <p>两种进入方式共用这一个入口,差别只在「人是谁」怎么证明:</p>
|
||||
* <ul>
|
||||
* <li><b>已登录</b>(个人中心改密码):身份由本系统会话给出,不需要人机校验。</li>
|
||||
* <li><b>未登录</b>(登录页被 603 拦下):按账号找回<b>已绑定</b>的本地账号,并且必须过本系统
|
||||
* 那张验证码——门户的代校验/改密都不要图形码,明确要求人机校验由下游兜,
|
||||
* 否则这里就成了可以无限次的口令字典(当前口令错一样计入门户的失败锁定)。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>改密成功不等于门户签发令牌:门户吊销的是<b>它自己的</b>刷新令牌,本系统会话不受影响
|
||||
* (对接指南 2.8.1)。未登录那条路改完就地建立本地会话,用户不必再输一次。</p>
|
||||
*/
|
||||
@Anonymous
|
||||
@PostMapping("/password")
|
||||
public AjaxResult changePassword(@RequestBody Map<String, String> 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<String, Object> 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} 一致。
|
||||
*
|
||||
* <p>本接口对门户是免密的,唯一的人机校验就是这里,漏掉等于让内部账号被无限次试口令。</p>
|
||||
*/
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
|
@ -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 侧管理接口)
|
||||
*
|
||||
* <p>这个页面是自动匹配的兜底:同步按姓名唯一命中自动绑定,其余情况(重名、匹配不上、
|
||||
* hub 侧新增但缺登录名)都由管理员在此页人工绑定、新建并绑定、解绑或忽略。
|
||||
* 匹配错了也能在这里改,不必动数据库。</p>
|
||||
*
|
||||
* @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<SysHubUser> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,205 @@
|
|||
package com.ruoyi.sip.hub.domain;
|
||||
|
||||
/**
|
||||
* 一轮目录同步的结果摘要,供定时任务日志与「立即同步」接口回显。
|
||||
*
|
||||
* <p>口径(ADR-0017):先镜像再决定动不动 {@code sys_user},因此计数分两组——
|
||||
* {@link #mirrored} 是「写进镜像表的人数」,{@link #bound} / {@link #created} 才是真正动了
|
||||
* {@code sys_user} 的人数。匹配不上又不属于增量新增的人只体现在 {@link #mirrored},
|
||||
* 这是设计意图,不是漏同步。</p>
|
||||
*
|
||||
* @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();
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
*
|
||||
* <p>hub 通讯录在 OMS 侧的只读投影:同步先写这张表,再决定要不要动 {@code sys_user}。
|
||||
* 这样做的好处是「hub 有什么人」在 OMS 里可见可查,管理员人工绑定有依据,自动匹配错了
|
||||
* 也能在这里看到并修正,同时 {@code sys_user} 不会被 hub 全员灌入污染(ADR-0017)。</p>
|
||||
*
|
||||
* <p>绑定关系只有 {@code sys_user.hub_user_id} 一处真相,本表不冗余存 local_user_id,
|
||||
* 页面上的「已绑定账号」由 join 推导({@link #boundUserId} 等字段是查询产物,不可写)。</p>
|
||||
*
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
package com.ruoyi.sip.hub.mapper;
|
||||
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
/**
|
||||
* hub 目录同步状态(游标)访问接口
|
||||
*
|
||||
* <p>游标单独存 sys_hub_sync_state 而不用 sys_config:ISysConfigService 读值走 ehcache,
|
||||
* 同步任务写完再读会拿到旧缓存,导致游标倒退或重复应用。</p>
|
||||
*
|
||||
* @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);
|
||||
}
|
||||
|
|
@ -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<SysHubUser> selectHubUserList(SysHubUser hubUser);
|
||||
|
||||
/**
|
||||
* 按 hub 用户ID 查询单个镜像记录
|
||||
*
|
||||
* @param hubUserId hub 用户ID
|
||||
* @return 镜像记录,不存在时为 null
|
||||
*/
|
||||
public SysHubUser selectHubUserByHubUserId(Long hubUserId);
|
||||
|
||||
/**
|
||||
* 按统一门户账号或邮箱查镜像记录(可能多行,由调用方判唯一)。
|
||||
*
|
||||
* <p>列的排序规则本身大小写不敏感,与 hub 的 {@code normalizeAccount}(转小写并去空格)
|
||||
* 口径一致,因此这里直接等值匹配即可。</p>
|
||||
*
|
||||
* @param account 门户账号或邮箱
|
||||
* @return 命中的镜像记录集合,正常为 0 或 1 行
|
||||
*/
|
||||
public List<SysHubUser> selectHubUserByAccount(String account);
|
||||
|
||||
/**
|
||||
* 幂等写入一条镜像:按 hub_user_id 存在则覆盖资料列,不存在则插入
|
||||
*
|
||||
* @param hubUser 镜像记录
|
||||
* @return 结果
|
||||
*/
|
||||
public int upsertHubUser(SysHubUser hubUser);
|
||||
|
||||
/**
|
||||
* 全量开始时把所有人标记为「本目录未出现」,随后每个被 upsert 的人重新置回存在。
|
||||
*
|
||||
* <p>必须先确认目录完整(未截断且非空)才允许调用,否则会把没返回的人误判为已离开。</p>
|
||||
*
|
||||
* @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。
|
||||
*
|
||||
* <p>只取已绑定的,未绑定的人本来就没进 OMS,不需要停用任何账号。</p>
|
||||
*
|
||||
* @return hub 用户ID列表
|
||||
*/
|
||||
public List<Long> selectAbsentBoundHubUserIds();
|
||||
}
|
||||
|
|
@ -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} 才推进游标。
|
||||
*
|
||||
* <p>下列情况一律转全量:需要全量标记未清、游标落后于流水 oldest_seq、
|
||||
* 收到组织状态或父子变更事件。</p>
|
||||
*
|
||||
* @return 结果摘要;hub 未启用时返回空结果
|
||||
*/
|
||||
public HubSyncResult incrementalSync();
|
||||
}
|
||||
|
|
@ -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 人员目录镜像与绑定服务(事务边界在这一层,远程调用全部在调用方完成)
|
||||
*
|
||||
* <p>口径(ADR-0017):hub 目录先原样镜像到 {@code sys_hub_user},再按「姓名唯一命中」
|
||||
* 尝试把 {@code sys_user.hub_user_id} 绑上。全量匹配不上的人<b>不建号也不打扰</b>,
|
||||
* 只留在镜像表;只有 hub 侧新增(增量事件)的人才自动建号并绑定。</p>
|
||||
*
|
||||
* @author codex
|
||||
*/
|
||||
public interface IHubUserMirrorService
|
||||
{
|
||||
/**
|
||||
* 全量开始前复位在场标记:把镜像里所有人置为「本轮未出现」,
|
||||
* 本轮 upsert 过的人会被重新置回在场,剩下的就是已离开的。
|
||||
*
|
||||
* <p>只能在确认目录完整(未截断)时调用。</p>
|
||||
*
|
||||
* @return 影响行数
|
||||
*/
|
||||
public int resetPresence();
|
||||
|
||||
/**
|
||||
* 应用一批目录成员。
|
||||
*
|
||||
* @param users 目录成员
|
||||
* @param fullPass 是否全量轮次:全量只镜像 + 自动绑定,<b>不建号</b>;增量才建号
|
||||
* @return 结果摘要
|
||||
*/
|
||||
public HubSyncResult applyUsers(List<HubDirectoryUser> users, boolean fullPass);
|
||||
|
||||
/**
|
||||
* 应用一批增量变更事件。
|
||||
*
|
||||
* @param changes hub 原始事件(payload 字段名随来源变化)
|
||||
* @return 结果摘要
|
||||
*/
|
||||
public HubSyncResult applyChanges(List<JSONObject> changes);
|
||||
|
||||
/**
|
||||
* 全量收尾:把「hub 已不再返回」且仍绑定的本地账号置为停用,并统计离开人数。
|
||||
*
|
||||
* <p>目录被截断时不得调用,否则会把「没返回」误判成「人已离开」。</p>
|
||||
*
|
||||
* @return 停用的本地账号数
|
||||
*/
|
||||
public int deactivateAbsent();
|
||||
|
||||
/**
|
||||
* 查询 hub 人员目录(含已绑定的本地账号)
|
||||
*
|
||||
* @param query 查询条件
|
||||
* @return 集合
|
||||
*/
|
||||
public List<SysHubUser> 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);
|
||||
}
|
||||
|
|
@ -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 代理门户密码登录使用。
|
||||
*
|
||||
* <p>为什么必须走镜像而不是 {@code sys_user}:内部人员在 OMS 登录页输入的是统一门户账号,
|
||||
* 而 hub 只认它自己的 {@code account}(或邮箱),OMS 的 {@code login_name} 与它不同源
|
||||
* (历史数据里存的是手机号或域账号),两个方向的换算都只有目录镜像能提供依据。</p>
|
||||
*
|
||||
* @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<SysHubUser> 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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 目录同步编排实现。
|
||||
*
|
||||
* <p>分层原则:本类只做「远程调用 + 游标推进」,落库交给 {@link IHubUserMirrorService} 的事务方法,
|
||||
* 因此事务内不出现 HTTP 调用(后端规范要求事务内不做远程调用)。</p>
|
||||
*
|
||||
* <p>全量与增量的职责差别(ADR-0017):全量只镜像 + 按姓名自动绑定,<b>不建号</b>,
|
||||
* 匹配不上的人留在镜像表由管理员处理;增量里出现的「镜像中没有的人」视为 hub 侧新增,
|
||||
* 才自动建号并绑定。</p>
|
||||
*
|
||||
* <p>对应 hub 对接指南 10.3 推荐流程:首次/每日全量 → {@link #fullSync()};固定周期增量 →
|
||||
* {@link #incrementalSync()};「差异一律以全量为准」「幂等应用」「组织状态与父子变更触发全量」
|
||||
* 「游标落后过多转全量」均在增量分支落地。</p>
|
||||
*
|
||||
* @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<HubDirectoryUser> 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<HubDirectoryUser> 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();
|
||||
}
|
||||
|
||||
/**
|
||||
* 全量落库后写入游标。
|
||||
*
|
||||
* <p>取快照前探到的水位({@code highWater}):它一定不大于快照覆盖的位置,
|
||||
* 因此其后的事件都会被下一轮增量重放到,不会跳过。</p>
|
||||
*
|
||||
* <p>探查失败({@code highWater <= 0})时退回「取快照后再探一次」,此时快照与探查之间
|
||||
* 的事件可能被跳过,但每日全量会兜住,属可接受的降级;不保留原游标是因为原游标可能
|
||||
* 远落后于流水,会让下一轮增量白翻很多页。</p>
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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 人员目录镜像与绑定实现。
|
||||
*
|
||||
* <p>两步走(ADR-0017):① 每个人先原样写进 {@code sys_hub_user} 镜像;② 再决定要不要动
|
||||
* {@code sys_user}。第 ② 步的自动动作只有两种——姓名唯一命中就绑定,hub 侧新增的人就建号;
|
||||
* 全量里既没绑定又不属于新增的人一律不打扰,留在镜像表等管理员处理。</p>
|
||||
*
|
||||
* <p>自动匹配只认姓名(OMS 的 {@code login_name} 存手机号,hub 全量目录不下发手机号,
|
||||
* 姓名是唯一两边都稳定有值的东西)。<b>命中多行等于匹配失败</b>:同名不同人很常见,
|
||||
* 绑错人的后果是内部人拿到别人的单据可见范围,宁可留给人工。</p>
|
||||
*
|
||||
* <p>覆盖范围克制:同步不改 {@code login_name}(业务表 {@code create_by} 存登录名,
|
||||
* 改名会打断历史单据归属)、不改 {@code dept_id}、不碰角色(ADR-0016 的授权仍由管理员手动完成)。</p>
|
||||
*
|
||||
* @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<HubDirectoryUser> 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<JSONObject> 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<Long> absentIds = hubUserMapper.selectAbsentBoundHubUserIds();
|
||||
for (Long hubUserId : absentIds)
|
||||
{
|
||||
count += userMapper.deactivateUserByHubUserId(hubUserId);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<SysHubUser> 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<SysUser> 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();
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理一条增量事件。
|
||||
*
|
||||
* <p>hub 侧已知坑:同一含义两个键名——{@code source=wecom} 带完整用户对象({@code id}),
|
||||
* {@code source=hub} 的摘要事件只带被改的那一两个字段,因此缺字段一律不覆盖本地值,
|
||||
* 也不允许把「没带 status」当成「人已停用」(见 {@link HubDirectoryUser#isKnownDisabled()})。</p>
|
||||
*/
|
||||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
* 用镜像里的现值补齐本次处理要用的字段。
|
||||
*
|
||||
* <p>只补「事件里没有」的空值,绝不覆盖事件带来的新值。补的是文本字段;
|
||||
* {@code status} 故意不补——增量摘要事件不带 status 时必须按「状态未知」处理,
|
||||
* 用镜像旧值冒充已知状态会绕开 {@link HubDirectoryUser#isKnownDisabled()} 那条防线,
|
||||
* 让「事件没说停用」变成「沿用上次结论」,正是当初误停在职人员的成因。</p>
|
||||
*/
|
||||
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 侧新增的人)。
|
||||
*
|
||||
* <p>登录名优先用手机号(OMS 的 {@code login_name} 现状就是手机号),退回 hub 账号;
|
||||
* 两者都不可用或撞名就不建,交人工。邮箱被他人占用时<b>只放弃邮箱、建号照常成功</b>,
|
||||
* 与 hub 自身即时建号的口径一致(hub 文档 9.6)——邮箱只是找回密码的辅助手段,
|
||||
* 不值得为它让一个人建不出号。</p>
|
||||
*
|
||||
* @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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用系统配置的默认密码建号(用户已定口径)。
|
||||
*
|
||||
* <p>统一登录开启时这份口令不参与登录(已绑定账号的口令由 hub 校验),它的用途是:
|
||||
* 管理员解绑后该账号还能用本地口令登录,以及 hub 故障期间的应急入口。
|
||||
* 必须写 {@code pwdUpdateDate}:{@code /getInfo} 把「从未修改过密码」判为需要改密,
|
||||
* 不写就会每次登录都弹提醒框。</p>
|
||||
*/
|
||||
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());
|
||||
// 摘要事件不带姓名/邮箱/手机号时这些字段为空,对应 <if> 分支不写该列
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.ruoyi.sip.mapper.ExternalApiCallLogItemMapper">
|
||||
|
||||
<resultMap type="ExternalApiCallLogItem" id="ExternalApiCallLogItemResult">
|
||||
<result property="id" column="id" />
|
||||
<result property="logId" column="log_id" />
|
||||
<result property="apiCode" column="api_code" />
|
||||
<result property="orderCode" column="order_code" />
|
||||
<result property="orderVersionCode" column="order_version_code" />
|
||||
<result property="versionCode" column="version_code" />
|
||||
<result property="serialNumber" column="serial_number" />
|
||||
<result property="productCode" column="product_code" />
|
||||
<result property="productDescription" column="product_description" />
|
||||
<result property="serviceLevel" column="service_level" />
|
||||
<result property="serviceDescribe" column="service_describe" />
|
||||
<result property="serviceStartTime" column="service_start_time" />
|
||||
<result property="serviceEndTime" column="service_end_time" />
|
||||
<result property="segmentIndex" column="segment_index" />
|
||||
<result property="delFlag" column="del_flag" />
|
||||
<result property="createTime" column="create_time" />
|
||||
</resultMap>
|
||||
|
||||
<sql id="selectExternalApiCallLogItemVo">
|
||||
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
|
||||
</sql>
|
||||
|
||||
<insert id="batchInsertExternalApiCallLogItem">
|
||||
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
|
||||
<foreach collection="list" item="item" separator=",">
|
||||
(#{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})
|
||||
</foreach>
|
||||
</insert>
|
||||
|
||||
<select id="selectExternalApiCallLogItemByLogId" parameterType="Long" resultMap="ExternalApiCallLogItemResult">
|
||||
<include refid="selectExternalApiCallLogItemVo"/>
|
||||
where log_id = #{logId}
|
||||
and del_flag = '0'
|
||||
order by id
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
|
|
@ -0,0 +1,105 @@
|
|||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.ruoyi.sip.mapper.ExternalApiCallLogMapper">
|
||||
|
||||
<resultMap type="ExternalApiCallLog" id="ExternalApiCallLogResult">
|
||||
<result property="id" column="id" />
|
||||
<result property="traceId" column="trace_id" />
|
||||
<result property="apiCode" column="api_code" />
|
||||
<result property="requestTime" column="request_time" />
|
||||
<result property="responseTime" column="response_time" />
|
||||
<result property="costMs" column="cost_ms" />
|
||||
<result property="queryStartTime" column="query_start_time"/>
|
||||
<result property="queryEndTime" column="query_end_time" />
|
||||
<result property="requestIp" column="request_ip" />
|
||||
<result property="apiKeyMasked" column="api_key_masked" />
|
||||
<result property="userAgent" column="user_agent" />
|
||||
<result property="requestParams" column="request_params" />
|
||||
<result property="httpStatus" column="http_status" />
|
||||
<result property="businessCode" column="business_code" />
|
||||
<result property="success" column="success" />
|
||||
<result property="orderCount" column="order_count" />
|
||||
<result property="snCount" column="sn_count" />
|
||||
<result property="responseSize" column="response_size" />
|
||||
<result property="responseHash" column="response_hash" />
|
||||
<result property="responseBody" column="response_body" />
|
||||
<result property="responseFile" column="response_file" />
|
||||
<result property="errorMsg" column="error_msg" />
|
||||
<result property="delFlag" column="del_flag" />
|
||||
<result property="createTime" column="create_time" />
|
||||
</resultMap>
|
||||
|
||||
<sql id="selectExternalApiCallLogVo">
|
||||
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
|
||||
</sql>
|
||||
|
||||
<insert id="insertExternalApiCallLog" parameterType="ExternalApiCallLog" useGeneratedKeys="true" keyProperty="id">
|
||||
insert into oms_external_api_log
|
||||
<trim prefix="(" suffix=")" suffixOverrides=",">
|
||||
<if test="traceId != null and traceId != ''">trace_id,</if>
|
||||
<if test="apiCode != null and apiCode != ''">api_code,</if>
|
||||
<if test="requestTime != null">request_time,</if>
|
||||
<if test="responseTime != null">response_time,</if>
|
||||
<if test="costMs != null">cost_ms,</if>
|
||||
<if test="queryStartTime != null">query_start_time,</if>
|
||||
<if test="queryEndTime != null">query_end_time,</if>
|
||||
<if test="requestIp != null">request_ip,</if>
|
||||
<if test="apiKeyMasked != null">api_key_masked,</if>
|
||||
<if test="userAgent != null">user_agent,</if>
|
||||
<if test="requestParams != null">request_params,</if>
|
||||
<if test="httpStatus != null">http_status,</if>
|
||||
<if test="businessCode != null">business_code,</if>
|
||||
<if test="success != null">success,</if>
|
||||
<if test="orderCount != null">order_count,</if>
|
||||
<if test="snCount != null">sn_count,</if>
|
||||
<if test="responseSize != null">response_size,</if>
|
||||
<if test="responseHash != null">response_hash,</if>
|
||||
<if test="responseBody != null">response_body,</if>
|
||||
<if test="responseFile != null">response_file,</if>
|
||||
<if test="errorMsg != null">error_msg,</if>
|
||||
<if test="delFlag != null">del_flag,</if>
|
||||
<if test="createTime != null">create_time,</if>
|
||||
</trim>
|
||||
<trim prefix="values (" suffix=")" suffixOverrides=",">
|
||||
<if test="traceId != null and traceId != ''">#{traceId},</if>
|
||||
<if test="apiCode != null and apiCode != ''">#{apiCode},</if>
|
||||
<if test="requestTime != null">#{requestTime},</if>
|
||||
<if test="responseTime != null">#{responseTime},</if>
|
||||
<if test="costMs != null">#{costMs},</if>
|
||||
<if test="queryStartTime != null">#{queryStartTime},</if>
|
||||
<if test="queryEndTime != null">#{queryEndTime},</if>
|
||||
<if test="requestIp != null">#{requestIp},</if>
|
||||
<if test="apiKeyMasked != null">#{apiKeyMasked},</if>
|
||||
<if test="userAgent != null">#{userAgent},</if>
|
||||
<if test="requestParams != null">#{requestParams},</if>
|
||||
<if test="httpStatus != null">#{httpStatus},</if>
|
||||
<if test="businessCode != null">#{businessCode},</if>
|
||||
<if test="success != null">#{success},</if>
|
||||
<if test="orderCount != null">#{orderCount},</if>
|
||||
<if test="snCount != null">#{snCount},</if>
|
||||
<if test="responseSize != null">#{responseSize},</if>
|
||||
<if test="responseHash != null">#{responseHash},</if>
|
||||
<if test="responseBody != null">#{responseBody},</if>
|
||||
<if test="responseFile != null">#{responseFile},</if>
|
||||
<if test="errorMsg != null">#{errorMsg},</if>
|
||||
<if test="delFlag != null">#{delFlag},</if>
|
||||
<if test="createTime != null">#{createTime},</if>
|
||||
</trim>
|
||||
</insert>
|
||||
|
||||
<select id="selectExternalApiCallLogByTraceId" parameterType="String" resultMap="ExternalApiCallLogResult">
|
||||
<include refid="selectExternalApiCallLogVo"/>
|
||||
where trace_id = #{traceId}
|
||||
and del_flag = '0'
|
||||
order by id desc
|
||||
limit 1
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.ruoyi.sip.hub.mapper.HubSyncStateMapper">
|
||||
|
||||
<select id="selectStateValue" parameterType="String" resultType="String">
|
||||
select state_value from sys_hub_sync_state where state_key = #{stateKey}
|
||||
</select>
|
||||
|
||||
<insert id="upsertState">
|
||||
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()
|
||||
</insert>
|
||||
|
||||
</mapper>
|
||||
|
|
@ -0,0 +1,159 @@
|
|||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.ruoyi.sip.hub.mapper.SysHubUserMapper">
|
||||
|
||||
<resultMap type="SysHubUser" id="SysHubUserResult">
|
||||
<id property="hubUserId" column="hub_user_id" />
|
||||
<result property="account" column="account" />
|
||||
<result property="wecomUserId" column="wecom_userid" />
|
||||
<result property="displayName" column="display_name" />
|
||||
<result property="email" column="email" />
|
||||
<result property="phone" column="phone" />
|
||||
<result property="orgId" column="org_id" />
|
||||
<result property="hubStatus" column="hub_status" />
|
||||
<result property="present" column="present" />
|
||||
<result property="reviewStatus" column="review_status" />
|
||||
<result property="reviewReason" column="review_reason" />
|
||||
<result property="reviewRemark" column="review_remark" />
|
||||
<result property="firstSeenTime" column="first_seen_time" />
|
||||
<result property="lastSeenTime" column="last_seen_time" />
|
||||
<result property="createBy" column="create_by" />
|
||||
<result property="createTime" column="create_time" />
|
||||
<result property="updateBy" column="update_by" />
|
||||
<result property="updateTime" column="update_time" />
|
||||
<result property="boundUserId" column="bound_user_id" />
|
||||
<result property="boundLoginName" column="bound_login_name" />
|
||||
<result property="boundUserName" column="bound_user_name" />
|
||||
</resultMap>
|
||||
|
||||
<!-- 绑定关系只有 sys_user.hub_user_id 一处真相:镜像表不存 local_user_id,
|
||||
页面的「已绑定账号」由这条 left join 现算,不会出现两边不一致。 -->
|
||||
<sql id="selectHubUserVo">
|
||||
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'
|
||||
</sql>
|
||||
|
||||
<select id="selectHubUserList" parameterType="SysHubUser" resultMap="SysHubUserResult">
|
||||
<include refid="selectHubUserVo"/>
|
||||
<where>
|
||||
<if test="keyword != null and keyword != ''">
|
||||
and (h.account like concat('%', #{keyword}, '%')
|
||||
or h.display_name like concat('%', #{keyword}, '%')
|
||||
or h.email like concat('%', #{keyword}, '%'))
|
||||
</if>
|
||||
<if test="reviewStatus != null and reviewStatus != ''">and h.review_status = #{reviewStatus}</if>
|
||||
<if test="present != null and present != ''">and h.`present` = #{present}</if>
|
||||
<if test="hubStatus != null">and h.hub_status = #{hubStatus}</if>
|
||||
<choose>
|
||||
<when test='boundState == "1"'>and u.user_id is not null</when>
|
||||
<when test='boundState == "0"'>and u.user_id is null</when>
|
||||
<otherwise/>
|
||||
</choose>
|
||||
</where>
|
||||
<!-- 待人工的排前面,其次已离开目录的,管理员一进页面就先看到要处理的人 -->
|
||||
order by (h.review_status = '1') desc, h.`present` asc, h.hub_user_id asc
|
||||
</select>
|
||||
|
||||
<select id="selectHubUserByHubUserId" parameterType="Long" resultMap="SysHubUserResult">
|
||||
<include refid="selectHubUserVo"/>
|
||||
where h.hub_user_id = #{hubUserId}
|
||||
</select>
|
||||
|
||||
<!-- 登录页输入的是统一门户账号,用它反查这个人。account 列与 hub 一样大小写不敏感
|
||||
(utf8mb4 排序规则不区分大小写),所以不必自己 LOWER;邮箱也一并匹配,
|
||||
因为 hub 的账号位同时接受邮箱。可能出现的重复行由调用方按「不唯一就不认」处理。 -->
|
||||
<select id="selectHubUserByAccount" parameterType="String" resultMap="SysHubUserResult">
|
||||
<include refid="selectHubUserVo"/>
|
||||
where h.account = #{account} or (h.email is not null and h.email <> '' and h.email = #{account})
|
||||
order by h.`present` desc, h.hub_user_id asc
|
||||
</select>
|
||||
|
||||
<!-- 同步写镜像:资料列一律覆盖(hub 是权威源)。人工处理态三列不在这里动,
|
||||
由 updateReview / markReviewIfNotIgnored / clearReview 单独维护,
|
||||
否则管理员的「忽略」会被下一轮同步悄悄改回去。
|
||||
first_seen_time 只在插入时写,重跑不会把首次同步时间冲掉。 -->
|
||||
<insert id="upsertHubUser" parameterType="SysHubUser">
|
||||
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
|
||||
<!-- 资料列一律「新值非空才覆盖」:全量目录字段齐全,等于全覆盖;
|
||||
而 source=hub 的增量摘要事件只带被改的那一两个字段,其余是空值,
|
||||
直接覆盖会把姓名/邮箱/状态清成空白(phone 更是全量目录根本不下发,
|
||||
只有企业微信来源的增量事件带)。hub 侧「真的把某字段清空」只能等全量,
|
||||
代价远小于每轮增量把资料刷没。 -->
|
||||
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()
|
||||
</insert>
|
||||
|
||||
<!-- 全量开始前的水位复位:先全部置为「本轮未出现」,本轮 upsert 过的人再被置回 '1'。
|
||||
只有确认目录完整(未截断且非空)才允许调用,否则会把没返回的人误判为已离开。 -->
|
||||
<update id="markAllAbsent">
|
||||
update sys_hub_user set `present` = '0', update_time = sysdate() where `present` <> '0'
|
||||
</update>
|
||||
|
||||
<!-- 增量 delete 事件:与全量收尾同一口径(present='0'),下一轮全量会自然对齐。
|
||||
人工处理态不动:人已离开目录时,忽略/待处理的标记没有意义,也不该被误当成可绑定对象。 -->
|
||||
<update id="markAbsent">
|
||||
update sys_hub_user set `present` = '0', update_time = sysdate()
|
||||
where hub_user_id = #{hubUserId}
|
||||
</update>
|
||||
|
||||
<!-- 管理员显式操作:无条件改处理态(忽略 / 恢复 / 手工置待处理) -->
|
||||
<update id="updateReview">
|
||||
update sys_hub_user
|
||||
set review_status = #{reviewStatus},
|
||||
review_reason = #{reviewReason},
|
||||
review_remark = #{reviewRemark},
|
||||
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
|
||||
update_time = sysdate()
|
||||
where hub_user_id = #{hubUserId}
|
||||
</update>
|
||||
|
||||
<!-- 同步置待处理:已被管理员忽略的人不再被同步改回去,避免「忽略后又冒出来」 -->
|
||||
<update id="markReviewIfNotIgnored">
|
||||
update sys_hub_user
|
||||
set review_status = #{reviewStatus},
|
||||
review_reason = #{reviewReason},
|
||||
update_time = sysdate()
|
||||
where hub_user_id = #{hubUserId} and review_status <> '2'
|
||||
</update>
|
||||
|
||||
<!-- 同步清理待处理:这个人已被绑定(自动或人工)后不再提示;已忽略的保持忽略 -->
|
||||
<update id="clearReview">
|
||||
update sys_hub_user
|
||||
set review_status = '0', review_reason = null, update_time = sysdate()
|
||||
where hub_user_id = #{hubUserId} and review_status = '1'
|
||||
</update>
|
||||
|
||||
<!-- 全量收尾用:本轮目录没出现但仍占着本地账号的人。
|
||||
未绑定的人本来就没进 OMS,不需要停用任何账号,所以必须 join 已绑定的行。 -->
|
||||
<select id="selectAbsentBoundHubUserIds" resultType="java.lang.Long">
|
||||
select h.hub_user_id
|
||||
from sys_hub_user h
|
||||
inner join sys_user u on u.hub_user_id = h.hub_user_id and u.del_flag = '0'
|
||||
where h.`present` = '0'
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
|
|
@ -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** 的未删除账号列表(可能多行,供同步判定唯一性)
|
||||
*
|
||||
* <p>hub 目录与 OMS 之间唯一可用的自动匹配键是姓名:OMS 的 login_name 存的是手机号,
|
||||
* hub 全量目录又不下发手机号。只取未绑定的行,已绑给别人的账号不参与匹配,
|
||||
* 避免同名的两行抢绑同一个人。</p>
|
||||
*
|
||||
* @param userName 姓名(sys_user.user_name)
|
||||
* @return 用户列表
|
||||
*/
|
||||
public List<SysUser> 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);
|
||||
|
||||
/**
|
||||
* 通过手机号码查询用户
|
||||
*
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
<result property="loginName" column="login_name" />
|
||||
<result property="userName" column="user_name" />
|
||||
<result property="userType" column="user_type" />
|
||||
<result property="hubUserId" column="hub_user_id" />
|
||||
<result property="hubSyncTime" column="hub_sync_time" />
|
||||
<result property="email" column="email" />
|
||||
<result property="phonenumber" column="phonenumber" />
|
||||
<result property="sex" column="sex" />
|
||||
|
|
@ -50,7 +52,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
</resultMap>
|
||||
|
||||
<sql id="selectUserVo">
|
||||
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"
|
|||
</sql>
|
||||
|
||||
<select id="selectUserList" parameterType="SysUser" resultMap="SysUserResult">
|
||||
select u.user_id, u.dept_id, u.login_name, u.user_name, u.user_type, u.email, u.avatar, u.phonenumber, u.password, u.sex, u.salt, u.status, u.del_flag, u.login_ip, u.login_date, u.create_by, u.create_time, u.remark, d.dept_name, d.leader from sys_user u
|
||||
select u.user_id, u.dept_id, u.login_name, u.user_name, u.user_type, u.hub_user_id, u.email, u.avatar, u.phonenumber, u.password, u.sex, u.salt, u.status, u.del_flag, u.login_ip, u.login_date, u.create_by, u.create_time, u.remark, d.dept_name, d.leader from sys_user u
|
||||
left join sys_dept d on u.dept_id = d.dept_id
|
||||
where u.del_flag = '0'
|
||||
<if test="userIdList!=null and userIdList.size>0">
|
||||
|
|
@ -139,7 +141,50 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
<include refid="selectUserVo"/>
|
||||
where u.login_name = #{userName} and u.del_flag = '0'
|
||||
</select>
|
||||
|
||||
|
||||
<!-- hub 免登认人:只按 hub_user_id 命中,不参与 login_name 匹配(ADR-0015) -->
|
||||
<select id="selectUserByHubUserId" parameterType="Long" resultMap="SysUserResult">
|
||||
<include refid="selectUserVo"/>
|
||||
where u.hub_user_id = #{hubUserId} and u.del_flag = '0'
|
||||
</select>
|
||||
|
||||
<!-- 目录同步自动绑定用:姓名是唯一可用的匹配键(OMS 的 login_name 是手机号,
|
||||
hub 全量目录不下发手机号)。只取尚未绑定的行,命中多行(重名)一律不自动绑定,转人工。 -->
|
||||
<select id="selectUnboundByUserName" parameterType="String" resultMap="SysUserResult">
|
||||
select user_id, dept_id, login_name, user_name, user_type, hub_user_id, email, phonenumber, status
|
||||
from sys_user where user_name = #{userName} and del_flag = '0' and hub_user_id is null
|
||||
</select>
|
||||
|
||||
<!-- 同步绑定:只写 hub 两列与资料列,不动 login_name、不动角色(ADR-0015) -->
|
||||
<update id="bindUserToHub" parameterType="SysUser">
|
||||
update sys_user
|
||||
<set>
|
||||
hub_user_id = #{hubUserId},
|
||||
hub_sync_time = sysdate(),
|
||||
<if test="userName != null and userName != ''">user_name = #{userName},</if>
|
||||
<if test="email != null and email != ''">email = #{email},</if>
|
||||
<if test="phonenumber != null and phonenumber != ''">phonenumber = #{phonenumber},</if>
|
||||
<if test="status != null and status != ''">status = #{status},</if>
|
||||
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
|
||||
update_time = sysdate()
|
||||
</set>
|
||||
where user_id = #{userId}
|
||||
</update>
|
||||
|
||||
<!-- hub 停用只置本地 status,绝不物理删除(业务表 create_by 与审批历史要留) -->
|
||||
<update id="deactivateUserByHubUserId" parameterType="Long">
|
||||
update sys_user set status = '1', hub_sync_time = sysdate(), update_time = sysdate()
|
||||
where hub_user_id = #{hubUserId} and status <> '1'
|
||||
</update>
|
||||
|
||||
<!-- 解绑:该账号回到本地口令登录。绑定关系只存 sys_user.hub_user_id 一处,
|
||||
清了就是真解了,镜像表不需要跟着改。 -->
|
||||
<update id="unbindHubByUserId" parameterType="Long">
|
||||
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
|
||||
</update>
|
||||
|
||||
<select id="selectUserByPhoneNumber" parameterType="String" resultMap="SysUserResult">
|
||||
<include refid="selectUserVo"/>
|
||||
where u.phonenumber = #{phonenumber} and u.del_flag = '0'
|
||||
|
|
@ -237,6 +282,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
<if test="loginName != null and loginName != ''">login_name,</if>
|
||||
<if test="userName != null and userName != ''">user_name,</if>
|
||||
<if test="userType != null and userType != ''">user_type,</if>
|
||||
<if test="hubUserId != null">hub_user_id,</if>
|
||||
<if test="hubSyncTime != null">hub_sync_time,</if>
|
||||
<if test="email != null and email != ''">email,</if>
|
||||
<if test="avatar != null and avatar != ''">avatar,</if>
|
||||
<if test="phonenumber != null and phonenumber != ''">phonenumber,</if>
|
||||
|
|
@ -254,6 +301,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
<if test="loginName != null and loginName != ''">#{loginName},</if>
|
||||
<if test="userName != null and userName != ''">#{userName},</if>
|
||||
<if test="userType != null and userType != ''">#{userType},</if>
|
||||
<if test="hubUserId != null">#{hubUserId},</if>
|
||||
<if test="hubSyncTime != null">#{hubSyncTime},</if>
|
||||
<if test="email != null and email != ''">#{email},</if>
|
||||
<if test="avatar != null and avatar != ''">#{avatar},</if>
|
||||
<if test="phonenumber != null and phonenumber != ''">#{phonenumber},</if>
|
||||
|
|
@ -268,4 +317,4 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||
)
|
||||
</insert>
|
||||
|
||||
</mapper>
|
||||
</mapper>
|
||||
|
|
|
|||
Loading…
Reference in New Issue