feat(企微签到):逻辑:员工使用企微扫码后直接跳出签到页面,在签到页面对该课程进行点击签到!
deploy-hxtesting / build-and-deploy (push) Successful in 1m14s

规则:1.签到要校验是否为培训当天签到,如果不是当天扫码签到则进行友好提示;2. 签到需提供员工工号及随机时间戳(超过签到二维码有效期后需重新扫码签到);3.签到二维码每5分钟自动更新一次(更新后之前扫码签到自动作废需重新扫码);
补充说明:1.签到页面需展示该签到课程相关信息;2.展示签到倒计时还有多久过期,过期后需重新扫码进行优化提示;3.签到后提示签到成功!自动登录进入平台系统并进入该课程详情页面
This commit is contained in:
runny committed 2026-11-25 11:02:48 +08:00
1 parent 9950a28346
commit f43fbef5db
24 files changed
+1336 -67

No files matched your search

@@ -1,6 +1,6 @@
# 企微扫码签到免登 · 落地方案
> 状态:方案评审阶段(未开发)
> 状态:**已实施(P0+P1 核心,待企微后台配置后联调)** —— 见文末「实施记录」
> 日期:2026-11-25
> 涉及模块:企业培训-培训签到(`frontend/src/views/training`、`internal/application/service/training_course.go`)
> 关联文档:`docs/design/企业培训系统-Academy落地方案.md` §5.3 权限模型
@@ -240,5 +240,38 @@
## 9. 待拍板事项
1. **宽限期**:严格按需求"轮换即作废",还是加 30s prev_token 宽限防"扫码即轮换"踩空?(建议加,`rotation_grace_sec` 可关)
1. ~~**宽限期**~~ → 已按"加宽限"实施(`rotation_grace_sec=30`,规则配置可关为 0)。
2. **企微后台三项配置**(可信域名/校验文件/可信IP)需管理员先落地,`well-trust.com` 的 ICP 备案状态需确认——这是整个方案的开关,建议最先验证。
## 10. 实施记录(2026-11-25)
### 变更文件
| 层 | 文件 | 内容 |
|---|---|---|
| 企微客户端 | `internal/im/wecom/proactive_client.go` | `BuildOAuthAuthorizeURL`(snsapi_base 授权链接)+ `GetOAuthUserID`(code 换 userid,token 过期错误码清缓存) |
| 推送适配 | `internal/im/wecompush/client.go` | `OAuthClientForTenant`(与消息推送同一套自建应用凭据) |
| 类型 | `internal/types/training.go` | `CheckinInput`/`WecomCheckinCourse`/`WecomCheckinPage`/`WecomCheckinSession` DTO;`tr_sign_codes.prev_token/prev_expire_at`、`tr_sign_records.nonce` 列 |
| 接口 | `internal/types/interfaces/training.go`、`user.go` | 仓库 3 个新方法(全局查码/企微反查/nonce 查重);服务新增免登 3 方法 + `Checkin` 签名改为 `CheckinInput`;`UserService.SessionResponseForUser`(与 /auth/login 同构的会话组装) |
| 用户服务 | `internal/application/service/user.go` | `SessionResponseForUser`:登录落点解析 + token 对 + 租户 + memberships 一次成型 |
| 免登服务 | `internal/application/service/training_wecom_oauth.go`(新) | `WecomCheckinAuthURL` / `WecomCheckinSession`(code→userid→绑定反查→签发 JWT→落地页数据)/ `WecomCheckinPage` / `resolveWecomSignCode`(前码宽限)/ `sameBeijingDay` |
| 签到域 | `internal/application/service/training_course.go` | `Checkin` 规则增强(当天性/工号+名单硬拒/nonce 防重放/时钟偏差/前码宽限);`GetSignCode` 惰性轮换;`rotateSignCode`;`CreateSignCode` 有效期改为 `min(now+rotation, 场次总有效期)` |
| 代录 | `internal/application/service/training_ops.go` | `CheckinFor` 适配新签名;代录不带工号/nonce,不受严格链路约束 |
| HTTP | `internal/handler/training/training.go` | `CheckinRequest` 增 `employee_no/nonce/client_ts`;`WecomCheckinAuth/Session/Page` 三个处理器 |
| 路由 | `internal/router/routes_training.go` | 两个匿名入口直挂 v1 + `WecomCheckinRateLimit`;`POST /training/wecom/checkin-page` 入 trainingGroup(Viewer) |
| 鉴权 | `internal/middleware/auth.go`、`auth_public_ratelimit.go` | noAuthAPI 白名单两行;**签到专用限流桶 600/min/IP**(教室共享出口 IP,复用 auth 共享桶 30/min 会整批 429) |
| 容器 | `internal/container/container.go` | `WecomOAuthBackend` provide + `trainingWecomBackend` 增 `OAuthClientForTenant` 适配 |
| 迁移 | `migrations/versioned/000162_training_sign_rotation.{up,down}.sql` | 两表三列,幂等 |
| 前端 API | `frontend/src/api/training/index.ts` | `getCheckinAuthUrl`/`wecomCheckinSession`/`wecomCheckinPage` + 类型;`checkin` 增严格链路参数 |
| 落地页 | `frontend/src/views/training/CheckinPage.vue` | 五态重构:OAuth 回跳换会话→复用登录持久化(签到即自动登录)→课程信息+身份确认行+倒计时→点击签到(工号+nonce)→成功后自动进课程详情;非企微环境引导重扫 |
| 讲师页 | `frontend/src/views/training/components/SignPanel.vue` | 10s 轻量轮询 sign-code 驱动惰性轮换(页面隐藏暂停);轮换倒计时展示;token 变化自动重绘二维码并提示 |
| 路由表 | `frontend/src/router/index.ts` | `trainingCheckin` 显式 `requiresAuth:false/requiresInit:false`(守卫对 undefined 仍拦截,必须显式 false) |
### 实施中的关键决策(与原方案差异)
1. **严格链路收口**:当天校验/工号+名单硬拒/nonce/时钟偏差仅在 `employee_no` 非空(新签到页)时生效 —— 代录补签常发生在非当天,须保持可用;既有登录态直签路径行为完全不变(名单外仍标 `not_in_roster` 进待复核)。
2. **补充规则落地**:签到录入工号必须在该场次「参加人员」名单中 → 扫码链路名单外**直接拒绝**(文案:"您不在该课程的『参加人员』名单中,请联系讲师或人事确认"),不再仅标记待复核。
3. **限流独立桶**:签到免登两个匿名入口用 `WecomCheckinRateLimit`(600/min/IP),不复用 auth 共享桶(30/min/IP)——教室几十人共享出口 IP,集中扫码会整批 429。
4. **轮换驱动**:后端 `GetSignCode` 读时惰性轮换(超 `rotation_sec` 窗口),讲师页每 10s 轮询;页面隐藏(`document.hidden`)暂停轮询,避免投屏不可见时的无谓轮换。
5. **验证状态**:`go build ./...` + `go vet` 全绿;前端 `vue-tsc --build` 全绿。本机 Go 测试因存量环境问题无法执行(gojieba cgo 在包 init 崩溃,干净工作树同样复现),单测需在 CI/正常环境跑:聚焦 `internal/application/service`、`internal/application/repository`、`internal/handler/training`、`internal/middleware`。
6. **联调前置(管理员)**:企微后台配 `kbt.well-trust.com`/`kb.well-trust.com` 可信域名(需确认 ICP 备案)+ 各自部署 `WW_verify_xxx.txt` + 企业可信 IP;然后测试环境走通全链路再复制到正式。
+57 -1
View File
@@ -647,13 +647,69 @@ export const createSignCode = (
export const getSignCode = (sessionId: string) =>
get<{ success: boolean; data: TrainingSignCode }>(`${base}/sessions/${enc(sessionId)}/sign-code`)
export const checkin = (token: string, lat = 0, lng = 0, channel = 'wecom_scan', memberId = '') =>
// 企微扫码签到免登(2026-11 需求):落地页免登与自动登录一条链路。
// checkin-auth 匿名(授权链接);checkin-session 匿名(code 换会话+页面数据,
// 响应与 /auth/login 同构,落地页复用登录持久化);checkin-page 登录态
// (PC 讲师自测/企微内已有会话)。
export const getCheckinAuthUrl = (token: string, redirectUri = '') =>
get<{ success: boolean; data: { authorize_url: string } }>(`${base}/wecom/checkin-auth`, {
params: { token, redirect_uri: redirectUri || undefined },
})
export interface WecomCheckinCourseInfo {
course_id: string
course_name: string
lecturer_name: string
start_at: string | null
end_at: string | null
location: string
status: string
can_sign_today: boolean
}
export interface WecomCheckinPageData {
member?: { employee_no: string; user_name?: string; post?: string; dept_name?: string }
course?: WecomCheckinCourseInfo
course_id: string
session_id: string
sign_expire_at: string | null
in_roster: boolean
already_signed: boolean
}
export interface WecomCheckinSessionData extends WecomCheckinPageData {
success?: boolean
token: string
refresh_token?: string
user?: Record<string, any>
active_tenant?: { id: number | string; name?: string; created_at?: string; updated_at?: string } | null
memberships?: Array<{ tenant_id: number; tenant_name?: string; role: string }>
}
export const wecomCheckinSession = (code: string, state: string) =>
post<{ success: boolean; data: WecomCheckinSessionData }>(`${base}/wecom/checkin-session`, { code, state })
export const wecomCheckinPage = (token: string) =>
post<{ success: boolean; data: WecomCheckinPageData }>(`${base}/wecom/checkin-page`, { token })
export const checkin = (
token: string,
lat = 0,
lng = 0,
channel = 'wecom_scan',
memberId = '',
opts?: { employee_no?: string; nonce?: string; client_ts?: number },
) =>
post<{ success: boolean; data: TrainingSignRecord }>(`${base}/sign-records/checkin`, {
token,
lat,
lng,
channel,
member_id: memberId || undefined,
// 2026-11 扫码严格链路:工号(须在参加人员名单)+ 随机时间戳防重放。
employee_no: opts?.employee_no || undefined,
nonce: opts?.nonce || undefined,
client_ts: opts?.client_ts || undefined,
})
export const listSignRecords = (sessionId: string) =>
+5 -2
View File
@@ -185,11 +185,14 @@ const router = createRouter({
meta: { requiresInit: true, requiresAuth: true }
},
{
// 学员扫码签到页:培训签到页二维码落地页,携 token 自动定位并签到(需登录态)。
// 学员扫码签到落地页(2026-11 企微扫码免登):企微「扫一扫」直接打开,
// 页面内自行完成免登(OAuth 静默授权)/自动登录/倒计时/点击签到,
// 故显式 requiresAuth:false + requiresInit:false 放行路由守卫
// (meta 缺省 = undefined 时守卫仍按需登录拦截,必须显式 false)。
path: "training/checkin/:token",
name: "trainingCheckin",
component: () => import("../views/training/CheckinPage.vue"),
meta: { requiresInit: true, requiresAuth: true }
meta: { requiresInit: false, requiresAuth: false }
},
{
// 组织架构:租户级共享组织架构(部门 + 员工档案),
+349 -31
View File
@@ -1,19 +1,21 @@
<template>
<!-- 学员扫码签到落地页:培训签到页二维码 → 企微/相机扫码直达,自动定位并提交签到 -->
<!-- 学员扫码签到落地页(2026-11 企微扫码免登需求):
企微「扫一扫」→ 静默免登(自动登录)→ 课程信息 + 签到倒计时 → 点击签到
→ 成功后自动进入该课程详情页。非企微环境提示改用企微扫码。 -->
<div class="checkin-page">
<div class="checkin-card">
<div class="checkin-card__icon" :class="`is-${state}`">
<!-- 定位中/提交中 -->
<svg v-if="state === 'pending'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<div class="checkin-card__icon" :class="`is-${iconState}`">
<!-- 免登中/取位中 -->
<svg v-if="iconState === 'pending'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="3.2" />
<path d="M12 2v3M12 19v3M2 12h3M19 12h3" />
</svg>
<!-- 成功 -->
<svg v-else-if="state === 'success'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<svg v-else-if="iconState === 'success'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="9" />
<path d="m8.5 12.2 2.4 2.4 4.8-4.9" />
</svg>
<!-- 失败 -->
<!-- 失败/受阻 -->
<svg v-else viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="9" />
<path d="M12 7.5V13" />
@@ -28,42 +30,271 @@
{{ record.status === 'normal' ? '签到成功' : record.status === 'late' ? '迟到签到' : '已提交,待复核' }}
</t-tag>
<!-- 落地页主体:课程信息 + 身份确认行 + 倒计时 + 签到按钮 -->
<template v-if="state === 'ready' && page">
<div class="course-box">
<div class="course-box__name">{{ page.course?.course_name || '培训课程' }}</div>
<div class="course-box__row" v-if="page.course?.lecturer_name">讲师:{{ page.course.lecturer_name }}</div>
<div class="course-box__row" v-if="page.course?.start_at">时间:{{ fmtBeijingTime(page.course.start_at) }}</div>
<div class="course-box__row" v-if="page.course?.location">地点:{{ page.course.location }}</div>
<div class="course-box__row" v-if="memberLabel">签到人:{{ memberLabel }}</div>
</div>
<!-- 签到倒计时:当前签到码剩余有效期,归零须重新扫码(需求补充 2) -->
<div class="countdown" :class="{ 'is-danger': remainSec <= 60 }">
<template v-if="remainSec > 0">
签到码有效期剩余 <b>{{ fmtRemain(remainSec) }}</b>
</template>
<template v-else>二维码已更新,请重新扫码签到</template>
</div>
<t-button
class="checkin-card__sign-btn"
theme="primary"
size="large"
block
:disabled="signDisabled"
@click="sign"
>
{{ signButtonText }}
</t-button>
<div v-if="signDisabledReason" class="checkin-card__warn">{{ signDisabledReason }}</div>
</template>
<div class="checkin-card__actions">
<t-button v-if="state === 'error'" theme="primary" @click="submit">重新签到</t-button>
<t-button variant="outline" @click="goTraining">前往企业培训</t-button>
<t-button v-if="state === 'error' && retryable" theme="primary" @click="sign">重新签到</t-button>
<t-button v-if="state !== 'submitting'" variant="outline" @click="goTraining">前往企业培训</t-button>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { MessagePlugin } from 'tdesign-vue-next'
import { checkin, unwrap, type TrainingSignRecord } from '@/api/training'
import { useAuthStore } from '@/stores/auth'
import { userInfoFromApi, } from '@/api/auth'
import {
checkin,
getCheckinAuthUrl,
unwrap,
wecomCheckinPage,
wecomCheckinSession,
type TrainingSignRecord,
type WecomCheckinPageData,
type WecomCheckinSessionData,
} from '@/api/training'
import { fmtBeijingTime } from '@/utils/datetime'
const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
type CheckinState = 'pending' | 'success' | 'error'
const state = ref<CheckinState>('pending')
type CheckinState = 'boot' | 'authing' | 'ready' | 'submitting' | 'success' | 'error' | 'blocked'
const state = ref<CheckinState>('boot')
const page = ref<WecomCheckinPageData | null>(null)
const record = ref<TrainingSignRecord | null>(null)
const errorMsg = ref('')
// 定位坐标:拒绝授权/不可用时以 0,0 提交,由后端 sign_policy(强制定位)决定是否放行
const geo = ref({ lat: 0, lng: 0 })
const routeToken = computed(() => String(route.params.token || ''))
// 企微内置浏览器 UA 含 wxwork;非企微环境无法静默授权,引导改用企微扫码。
const isWecomUA = computed(() =>
typeof navigator !== 'undefined' && /wxwork/i.test(navigator.userAgent || ''),
)
const iconState = computed(() => {
if (state.value === 'success') return 'success'
if (state.value === 'error' || state.value === 'blocked') return 'error'
return 'pending'
})
const title = computed(() => {
if (state.value === 'pending') return '正在签到…'
if (state.value === 'success') return '签到完成'
return '签到失败'
switch (state.value) {
case 'boot':
case 'authing':
return '正在进入签到…'
case 'ready':
return page.value?.already_signed ? '您已签到' : '培训签到'
case 'submitting':
return '正在签到…'
case 'success':
return '签到完成'
default:
return state.value === 'blocked' ? '无法签到' : '签到失败'
}
})
const hint = computed(() => {
if (state.value === 'pending') return '正在获取定位并提交签到,请保持页面打开'
if (state.value === 'success') return `签到时间:${fmtBeijingTime(record.value?.signed_at || null) || '—'}`
return errorMsg.value || '签到码无效或已过期,请联系讲师刷新签到码'
switch (state.value) {
case 'boot':
case 'authing':
return '正在验证身份并打开签到页,请稍候'
case 'ready':
return page.value?.already_signed
? '本课程您已完成签到,无需重复操作'
: '请核对课程与签到人信息,点击下方按钮完成签到'
case 'submitting':
return '正在获取定位并提交签到,请保持页面打开'
case 'success':
return `签到时间:${fmtBeijingTime(record.value?.signed_at || null) || '—'},即将进入课程详情…`
case 'blocked':
return errorMsg.value || '请使用企业微信「扫一扫」扫描培训签到码'
default:
return errorMsg.value || '签到失败,请重试'
}
})
// 错误态是否提供「重新签到」:仅瞬时失败(定位/网络/时间戳偏差)可重试;
// 名单外/非当天/工号不一致属确定性拒绝,提示后不重试。
const retryable = computed(() => {
const msg = errorMsg.value
return !(/名单|当天|已结束|尚未开始|工号|重复扫码|已签到/.test(msg))
})
// ---- 落地页主体态(ready)按钮/提示 ----
const memberLabel = computed(() => {
const m = page.value?.member
if (!m) return ''
return [m.user_name, m.employee_no].filter(Boolean).join(' · ')
})
const remainSec = ref(0)
let countdownTimer: number | undefined
const startCountdown = () => {
stopCountdown()
const tick = () => {
const exp = page.value?.sign_expire_at
remainSec.value = exp ? Math.max(0, Math.floor((new Date(exp).getTime() - Date.now()) / 1000)) : 0
}
tick()
countdownTimer = window.setInterval(tick, 1000)
}
const stopCountdown = () => {
if (countdownTimer) {
window.clearInterval(countdownTimer)
countdownTimer = undefined
}
}
const fmtRemain = (sec: number) => {
const m = Math.floor(sec / 60)
const s = sec % 60
return m > 0 ? `${m}分${String(s).padStart(2, '0')}秒` : `${s}秒`
}
const signDisabled = computed(() => {
if (!page.value) return true
if (page.value.already_signed) return true
if (remainSec.value <= 0) return true
if (page.value.course && !page.value.course.can_sign_today) return true
return false
})
const signDisabledReason = computed(() => {
if (!page.value) return ''
if (page.value.already_signed) return '本课程您已完成签到'
if (remainSec.value <= 0) return '签到码已过期,请用企业微信重新扫码'
if (page.value.course && !page.value.course.can_sign_today) {
const start = page.value.course.start_at ? fmtBeijingTime(page.value.course.start_at) : ''
return `培训尚未开始(${start} 开课),培训当天再来签到`
}
if (!page.value.in_roster) return '您不在该课程的「参加人员」名单中,请联系讲师或人事确认'
return ''
})
const signButtonText = computed(() => {
if (page.value?.already_signed) return '已签到'
if (state.value === 'submitting') return '签到中…'
return '点击签到'
})
// ---- 链路编排 ----
// 企微 OAuth 静默授权跳转:snsapi_base,学员无感;回跳落地页带 code+state。
const startOAuth = async () => {
state.value = 'authing'
try {
const res = unwrap<{ authorize_url: string }>(
await getCheckinAuthUrl(routeToken.value, `${window.location.origin}/platform/training/checkin/${routeToken.value}`),
)
if (!res?.authorize_url) throw new Error('empty authorize_url')
window.location.replace(res.authorize_url)
} catch (e: any) {
state.value = 'blocked'
errorMsg.value = e?.response?.data?.message || '免登跳转失败,请重新扫码'
}
}
// OAuth 回跳:code 换平台会话(token/refresh_token/user/tenant/memberships,
// 与 /auth/login 同构)→ 复用登录持久化路径完成"签到即自动登录"。
const persistLogin = (data: WecomCheckinSessionData) => {
const activeTenant = data.active_tenant || null
const homeTenantIdRaw = (data.user as any)?.tenant_id ?? activeTenant?.id ?? ''
if (data.user) {
authStore.setUser(userInfoFromApi(data.user, homeTenantIdRaw))
}
authStore.setToken(data.token)
if (data.refresh_token) authStore.setRefreshToken(data.refresh_token)
if (activeTenant) {
authStore.setTenant({
id: String(activeTenant.id) || '',
name: activeTenant.name || '',
owner_id: String((data.user as any)?.id || ''),
created_at: activeTenant.created_at || new Date().toISOString(),
updated_at: activeTenant.updated_at || new Date().toISOString(),
})
} else {
authStore.setTenant(null)
}
if (Array.isArray(data.memberships)) authStore.setMemberships(data.memberships)
// 后端按"最近活跃租户"偏好落点时,同步选中态让后续请求带 X-Tenant-ID。
const activeIdNum = Number(activeTenant?.id)
const homeIdNum = Number(homeTenantIdRaw)
if (Number.isFinite(activeIdNum) && Number.isFinite(homeIdNum) && activeIdNum !== homeIdNum) {
authStore.setSelectedTenant(activeIdNum, activeTenant?.name || null)
} else {
authStore.setSelectedTenant(null, null)
}
}
const exchangeSession = async (code: string, stateToken: string) => {
state.value = 'authing'
try {
const data = unwrap<WecomCheckinSessionData>(await wecomCheckinSession(code, stateToken))
if (!data?.token) throw new Error('empty session token')
persistLogin(data)
applyPage(data)
// 清理回跳参数,避免刷新重复消费一次性 code。
window.history.replaceState(null, '', window.location.pathname)
} catch (e: any) {
state.value = 'blocked'
errorMsg.value = e?.response?.data?.message || '免登失败,请重新扫码'
}
}
const applyPage = (data: WecomCheckinPageData) => {
page.value = data
state.value = 'ready'
startCountdown()
}
// 已登录(PC 讲师自测 / 企微内已有会话):直接取落地页数据;token 失效时在
// 企微环境回退免登链路。
const loadPage = async () => {
try {
const data = unwrap<WecomCheckinPageData>(await wecomCheckinPage(routeToken.value))
if (!data) throw new Error('empty page data')
applyPage(data)
} catch (e: any) {
if (isWecomUA.value) {
await startOAuth()
return
}
state.value = 'blocked'
errorMsg.value = e?.response?.data?.message || '签到码无效或已过期,请重新扫码'
}
}
// 取定位:最多等 6 秒,失败不阻塞签到(是否强制定位由后端规则决定)
const locate = () =>
new Promise<void>((resolve) => {
@@ -77,29 +308,41 @@ const locate = () =>
},
() => {
window.clearTimeout(timer)
MessagePlugin.warning('未获取到定位,如课程开启定位校验将无法签到')
MessagePlugin.warning('未获取到定位,如课程开启定位校验将标记定位异常')
resolve()
},
{ timeout: 5500, maximumAge: 30000 },
)
})
const submit = async () => {
state.value = 'pending'
const token = String(route.params.token || '')
if (!token) {
state.value = 'error'
errorMsg.value = '签到链接不完整'
return
}
// 点击签到(2026-11 需求:不再进页自动签):工号 + 随机时间戳随请求提交,
// 后端做当天性/名单硬校验与防重放。
const sign = async () => {
if (!page.value || signDisabled.value) return
state.value = 'submitting'
errorMsg.value = ''
await locate()
const nonce = `${Date.now()}${Math.random().toString(36).slice(2, 10)}`
try {
const res = await checkin(token, geo.value.lat, geo.value.lng, 'wecom_scan')
record.value = (unwrap(res) as TrainingSignRecord | undefined) || null
const res = unwrap<TrainingSignRecord>(
await checkin(routeToken.value, geo.value.lat, geo.value.lng, 'wecom_scan', '', {
employee_no: page.value.member?.employee_no || '',
nonce,
client_ts: Date.now(),
}),
)
record.value = res || null
state.value = 'success'
stopCountdown()
// 签到成功 → 已自动登录,稍作停留后进入该课程详情页(需求补充 3)。
window.setTimeout(() => {
if (page.value?.course_id) {
router.push(`/platform/training/course/${page.value.course_id}`)
}
}, 1800)
} catch (e: any) {
state.value = 'error'
errorMsg.value = e?.response?.data?.message || '签到码无效或已过期,请联系讲师刷新签到码'
errorMsg.value = e?.response?.data?.message || '签到失败,请重试'
}
}
@@ -107,7 +350,32 @@ const goTraining = () => {
router.push('/platform/training/dashboard')
}
onMounted(submit)
onMounted(() => {
const oauthCode = route.query.code ? String(route.query.code) : ''
const oauthState = route.query.state ? String(route.query.state) : ''
if (oauthCode && oauthState) {
// 企微 OAuth 回跳:优先消费一次性 code 完成免登。
exchangeSession(oauthCode, oauthState)
return
}
if (!routeToken.value) {
state.value = 'blocked'
errorMsg.value = '签到链接不完整'
return
}
if (authStore.isLoggedIn) {
loadPage()
return
}
if (isWecomUA.value) {
startOAuth()
return
}
state.value = 'blocked'
errorMsg.value = '请使用企业微信「扫一扫」扫描培训签到码完成签到'
})
onBeforeUnmount(stopCountdown)
</script>
<style lang="less" scoped>
@@ -173,6 +441,16 @@ onMounted(submit)
overflow-wrap: anywhere;
}
&__sign-btn {
margin-top: 4px;
}
&__warn {
color: var(--td-warning-color, #e37318);
font-size: var(--app-text-sm, 13px);
overflow-wrap: anywhere;
}
&__actions {
display: flex;
gap: 10px;
@@ -180,6 +458,46 @@ onMounted(submit)
}
}
.course-box {
width: 100%;
padding: 14px 16px;
margin-top: 4px;
text-align: left;
background: var(--td-bg-color-secondarycontainer, rgba(0, 0, 0, 0.03));
border-radius: var(--app-radius-md, 8px);
&__name {
margin-bottom: 6px;
font-weight: 600;
font-size: var(--app-text-lg, 16px);
}
&__row {
color: var(--td-text-color-secondary);
font-size: var(--app-text-sm, 13px);
line-height: 1.8;
overflow-wrap: anywhere;
}
}
.countdown {
width: 100%;
padding: 8px 12px;
color: var(--td-success-color);
font-size: var(--app-text-sm, 13px);
background: var(--td-success-color-1, rgba(0, 168, 112, 0.08));
border-radius: var(--app-radius-md, 8px);
b {
font-weight: 600;
}
&.is-danger {
color: var(--td-error-color);
background: var(--td-error-color-1, rgba(227, 77, 89, 0.08));
}
}
@keyframes checkin-breath {
0%, 100% { opacity: 1; }
50% { opacity: 0.55; }
@@ -31,6 +31,12 @@
有效期至 {{ fmtTime(signCode.expire_at) }}
<template v-if="signCode.geo_radius"> · 定位半径 {{ signCode.geo_radius }}m</template>
</div>
<!-- 自动轮换倒计时(2026-11 需求:二维码每 5 分钟自动更新,旧码即时作废;
轮换由后端在轮询读取时惰性触发,本页每 10s 轻量轮询驱动) -->
<div class="sign-code-box__countdown" v-if="signCode && rotateRemainSec > 0">
{{ rotateRemainText }}后自动更新,旧码作废需重扫
</div>
<div class="sign-code-box__countdown is-stale" v-else-if="signCode">即将自动更新签到码…</div>
<t-button v-if="canReview" theme="primary" variant="outline" :loading="genLoading" @click="onGenCode">
{{ signCode ? '刷新签到码' : '生成签到码' }}
</t-button>
@@ -159,7 +165,7 @@
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { MessagePlugin } from 'tdesign-vue-next'
import QRCode from 'qrcode'
@@ -255,6 +261,60 @@ const buildSignQr = async () => {
}
watch(signCode, buildSignQr, { immediate: true })
// ---- 签到码自动轮换(2026-11 企微扫码需求) ----
// 后端在 GET sign-code 超过轮换窗口(rotation_sec,默认 5 分钟)时惰性轮换:
// 旧 token 挪入 prev(30s 宽限后彻底作废),新码即时生效。本页每 10s 轻量轮询
// sign-code(不带明细/佐证),token 变化经上方 watch 自动重绘二维码并提示重扫;
// 页面隐藏时暂停轮询(投屏不在展示态时不做无谓轮换)。
const rotateRemainSec = ref(0)
let rotateDisplayTimer: number | undefined
let rotatePollTimer: number | undefined
const fmtRemainText = (sec: number) => {
const m = Math.floor(sec / 60)
const s = sec % 60
return m > 0 ? `${m}分${String(s).padStart(2, '0')}秒` : `${s}秒`
}
const rotateRemainText = computed(() => fmtRemainText(rotateRemainSec.value))
const tickRotateRemain = () => {
const exp = signCode.value?.expire_at
rotateRemainSec.value = exp ? Math.max(0, Math.floor((new Date(exp).getTime() - Date.now()) / 1000)) : 0
}
const pollSignCode = async () => {
if (!selectedSessionId.value || document.hidden) return
try {
const next = unwrap<TrainingSignCode | null>(await getSignCode(selectedSessionId.value))
if (!next) return
if (next.token !== signCode.value?.token) {
// 仅在 token 变化时回写:watch(signCode) 会重绘二维码并提示重扫;
// token 未变时跳过赋值,避免每 10s 触发一次无谓重绘。
signCode.value = next
MessagePlugin.info('签到码已自动更新,旧码已作废,请提醒学员重新扫码')
}
} catch {
// 场次尚未生成签到码/网络抖动:静默,不打断投屏。
}
}
const startCodeRotation = () => {
stopCodeRotation()
tickRotateRemain()
rotateDisplayTimer = window.setInterval(tickRotateRemain, 1000)
rotatePollTimer = window.setInterval(pollSignCode, 10000)
}
const stopCodeRotation = () => {
if (rotateDisplayTimer) {
window.clearInterval(rotateDisplayTimer)
rotateDisplayTimer = undefined
}
if (rotatePollTimer) {
window.clearInterval(rotatePollTimer)
rotatePollTimer = undefined
}
}
watch(selectedSessionId, (sid) => {
if (sid) startCodeRotation()
else stopCodeRotation()
})
const flagText = (f: string) => ({ late: '迟到', outside: '定位异常', not_in_roster: '名单外' }[f] || f)
const courseName = (courseId: string) => courses.value.find((c) => c.id === courseId)?.name || '课程'
@@ -483,7 +543,11 @@ watch(() => route.query.courseId, applyRouteCourse)
onMounted(async () => {
await loadAll()
applyRouteCourse()
// 签到码轮换:进页即启动(选中场次后 watch 也会重启,双保险覆盖异步加载)。
startCodeRotation()
})
onUnmounted(stopCodeRotation)
</script>
<style lang="less" scoped>
@@ -537,6 +601,15 @@ onMounted(async () => {
padding: 8px;
}
&__meta { color: var(--td-text-color-placeholder); font-size: var(--app-text-sm); margin-bottom: 10px; }
// 自动轮换倒计时(2026-11 需求):临期转警示色,提醒讲师学员需重扫。
&__countdown {
color: var(--td-brand-color);
font-size: var(--app-text-sm);
margin-bottom: 10px;
&.is-stale { color: var(--td-warning-color, #e37318); }
}
}
.stat-cards {
@@ -48,6 +48,17 @@ func (r *trainingRepository) GetMemberByUserID(ctx context.Context, tenantID uin
return &m, nil
}
// GetMemberByWecomUserid 企微免登反查(2026-11 扫码签到):按绑定定位培训档案。
func (r *trainingRepository) GetMemberByWecomUserid(ctx context.Context, tenantID uint64, wecomUserid string) (*types.TrainingMember, error) {
var m types.TrainingMember
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND wecom_userid = ?", tenantID, wecomUserid).
First(&m).Error; err != nil {
return nil, err
}
return &m, nil
}
// FindArchiveTenantID 跨租户查找用户最早的在职员工档案所属租户(000160):
// 企业培训按「员工档案归属」解析数据空间 —— 用户当前所在工作区没有培训档案、
// 但组织中心(共享 org_employees)有在职档案时,培训域回落到档案所在租户,
@@ -751,18 +751,22 @@ func (r *trainingRepository) UpdateMaterial(ctx context.Context, material *types
// ---------------------------------------------------------------------------
// UpsertSignCode creates or refreshes the session's sign-in code.
// 2026-11 轮换需求:轮换时新行携带 prev_token/prev_expire_at(旧码宽限用),
// 一并覆盖,旧 token 即时退出当前码位。
func (r *trainingRepository) UpsertSignCode(ctx context.Context, code *types.TrainingSignCode) error {
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "session_id"}},
DoUpdates: clause.Assignments(map[string]interface{}{
"token": gorm.Expr("EXCLUDED.token"),
"expire_at": gorm.Expr("EXCLUDED.expire_at"),
"geo_lat": gorm.Expr("EXCLUDED.geo_lat"),
"geo_lng": gorm.Expr("EXCLUDED.geo_lng"),
"geo_radius": gorm.Expr("EXCLUDED.geo_radius"),
"created_by": gorm.Expr("EXCLUDED.created_by"),
"updated_at": gorm.Expr("CURRENT_TIMESTAMP"),
"token": gorm.Expr("EXCLUDED.token"),
"expire_at": gorm.Expr("EXCLUDED.expire_at"),
"prev_token": gorm.Expr("EXCLUDED.prev_token"),
"prev_expire_at": gorm.Expr("EXCLUDED.prev_expire_at"),
"geo_lat": gorm.Expr("EXCLUDED.geo_lat"),
"geo_lng": gorm.Expr("EXCLUDED.geo_lng"),
"geo_radius": gorm.Expr("EXCLUDED.geo_radius"),
"created_by": gorm.Expr("EXCLUDED.created_by"),
"updated_at": gorm.Expr("CURRENT_TIMESTAMP"),
}),
}).
Create(code).Error
@@ -790,6 +794,19 @@ func (r *trainingRepository) GetSignCodeByToken(ctx context.Context, tenantID ui
return &c, nil
}
// GetSignCodeByTokenGlobal 匿名扫码入口按 token 全局定位签到码(不带租户条件,
// 租户由码行反解):命中当前码或轮换宽限中的前码(prev_token)。表按
// (tenant, session) 唯一,行数极小,OR 扫描无性能顾虑。
func (r *trainingRepository) GetSignCodeByTokenGlobal(ctx context.Context, token string) (*types.TrainingSignCode, error) {
var c types.TrainingSignCode
if err := r.db.WithContext(ctx).
Where("(token = ? OR prev_token = ?) AND deleted_at IS NULL", token, token).
Order("created_at DESC").First(&c).Error; err != nil {
return nil, err
}
return &c, nil
}
// UpsertSignRecord stores one sign-in (unique per session+member).
func (r *trainingRepository) UpsertSignRecord(ctx context.Context, record *types.TrainingSignRecord) error {
return r.db.WithContext(ctx).
@@ -808,6 +825,18 @@ func (r *trainingRepository) GetSignRecord(ctx context.Context, tenantID uint64,
return &rec, nil
}
// GetSignRecordByNonce 防重放(2026-11 扫码签到):nonce 已用过则拒绝。
// 调用方保证 nonce 非空(空 nonce 不查,避免命中历史空值行)。
func (r *trainingRepository) GetSignRecordByNonce(ctx context.Context, tenantID uint64, nonce string) (*types.TrainingSignRecord, error) {
var rec types.TrainingSignRecord
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND nonce = ? AND deleted_at IS NULL", tenantID, nonce).
First(&rec).Error; err != nil {
return nil, err
}
return &rec, nil
}
// GetSignRecordByID fetches one record by ID (复核入口)。
func (r *trainingRepository) GetSignRecordByID(ctx context.Context, tenantID uint64, id string) (*types.TrainingSignRecord, error) {
var rec types.TrainingSignRecord
+7 -2
View File
@@ -38,11 +38,16 @@ type trainingService struct {
chunkSvc interfaces.ChunkService
// db 供 OA 企微 userid 同步直查 org_employees(见 training_scheduler 之外的 oa 集成)。
db *gorm.DB
// users 平台用户服务:企微扫码免登以绑定身份签发平台 JWT(签到即自动登录,
// 2026-11 需求,见 training_wecom_oauth.go)。
users interfaces.UserService
// wecomOAuth 企微网页授权后端(容器注入 wecompush 适配,本层不引 internal/im)。
wecomOAuth WecomOAuthBackend
}
// NewTrainingService constructs the production training service.
func NewTrainingService(repo interfaces.TrainingRepository, kbService interfaces.KnowledgeBaseService, knowledgeSvc interfaces.KnowledgeService, org interfaces.OrgCenterService, fileSvc interfaces.FileService, models interfaces.ModelService, chunkSvc interfaces.ChunkService, db *gorm.DB) interfaces.TrainingService {
return &trainingService{repo: repo, kbService: kbService, knowledgeSvc: knowledgeSvc, org: org, fileSvc: fileSvc, models: models, chunkSvc: chunkSvc, db: db}
func NewTrainingService(repo interfaces.TrainingRepository, kbService interfaces.KnowledgeBaseService, knowledgeSvc interfaces.KnowledgeService, org interfaces.OrgCenterService, fileSvc interfaces.FileService, models interfaces.ModelService, chunkSvc interfaces.ChunkService, db *gorm.DB, users interfaces.UserService, wecomOAuth WecomOAuthBackend) interfaces.TrainingService {
return &trainingService{repo: repo, kbService: kbService, knowledgeSvc: knowledgeSvc, org: org, fileSvc: fileSvc, models: models, chunkSvc: chunkSvc, db: db, users: users, wecomOAuth: wecomOAuth}
}
// ---------------------------------------------------------------------------
+147 -9
View File
@@ -711,6 +711,8 @@ func (s *trainingService) AttachQuestionBank(ctx context.Context, tenantID uint6
// CreateSignCode generates (or refreshes) the session's sign-in code with an
// optional geo-fence; default expiry = start + 4h or now + 12h.
// 2026-11 轮换需求:每轮 token 有效期 = min(now + rotation_sec, 场次总有效期),
// 讲师页轮询 GetSignCode 惰性续轮。
func (s *trainingService) CreateSignCode(ctx context.Context, tenantID uint64, sessionID string, lat, lng float64, radius int, operatorID string) (*types.TrainingSignCode, error) {
session, err := s.repo.GetSession(ctx, tenantID, sessionID)
if err != nil {
@@ -719,12 +721,19 @@ func (s *trainingService) CreateSignCode(ctx context.Context, tenantID uint64, s
if radius <= 0 {
radius = int(s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "geo_radius_m", 300))
}
expire := time.Now().Add(12 * time.Hour)
now := time.Now()
expire := now.Add(12 * time.Hour)
if session.StartAt != nil {
if candidate := session.StartAt.Add(4 * time.Hour); candidate.After(time.Now()) {
if candidate := session.StartAt.Add(4 * time.Hour); candidate.After(now) {
expire = candidate
}
}
rotation := time.Duration(s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "rotation_sec", 300)) * time.Second
if rotation > 0 {
if capped := now.Add(rotation); capped.Before(expire) {
expire = capped
}
}
code := &types.TrainingSignCode{
ID: trainingNewID(),
TenantID: tenantID,
@@ -747,22 +756,86 @@ func trainingNewToken() string {
return strings.ReplaceAll(trainingNewID(), "-", "")[:32]
}
// GetSignCode returns the session's active sign-in code.
// GetSignCode returns the session's active sign-in code. 超过轮换窗口
// (rotation_sec,默认 5 分钟)时惰性轮换:旧 token 挪入 prev(宽限期内仍可
// 签到),新码即时生效 —— 讲师页每 10s 轮询本接口即可驱动自动更新。
func (s *trainingService) GetSignCode(ctx context.Context, tenantID uint64, sessionID string) (*types.TrainingSignCode, error) {
code, err := s.repo.GetSignCodeBySession(ctx, tenantID, sessionID)
if err != nil {
return nil, errors.NewNotFoundError("尚未生成签到码")
}
return code, nil
rotation := time.Duration(s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "rotation_sec", 300)) * time.Second
if rotation <= 0 || time.Now().Before(code.UpdatedAt.Add(rotation)) {
return code, nil
}
return s.rotateSignCode(ctx, tenantID, code)
}
// rotateSignCode 轮换场次签到码:生成新 token,旧 token/有效期挪入 prev 供
// 宽限签到(rotation_grace_sec,默认 30s,0 = 严格作废);upsert 覆盖唯一行后
// 旧 token 即刻退出当前码位(GetSignCodeByToken 不再命中,自然作废)。
// 新码有效期 = min(now + rotation_sec, 场次总有效期):后者沿用开课 +4h /
// 兜底 +12h 的既有口径,超期后不再续轮,交由现有过期校验拦截。
func (s *trainingService) rotateSignCode(ctx context.Context, tenantID uint64, code *types.TrainingSignCode) (*types.TrainingSignCode, error) {
session, err := s.repo.GetSession(ctx, tenantID, code.SessionID)
if err != nil {
return nil, errors.NewNotFoundError("课程场次不存在")
}
now := time.Now()
rotation := time.Duration(s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "rotation_sec", 300)) * time.Second
expire := now.Add(rotation)
overall := now.Add(12 * time.Hour)
if session.StartAt != nil {
if candidate := session.StartAt.Add(4 * time.Hour); candidate.After(now) {
overall = candidate
}
}
if expire.After(overall) {
expire = overall
}
next := &types.TrainingSignCode{
ID: trainingNewID(),
TenantID: tenantID,
SessionID: code.SessionID,
Token: trainingNewToken(),
ExpireAt: &expire,
PrevToken: code.Token,
PrevExpireAt: code.ExpireAt,
GeoLat: code.GeoLat,
GeoLng: code.GeoLng,
GeoRadius: code.GeoRadius,
CreatedBy: code.CreatedBy,
}
if err := s.repo.UpsertSignCode(ctx, next); err != nil {
return nil, err
}
return next, nil
}
// Checkin performs the scan sign-in with rule-based anti-fraud checks:
// token/expiry, roster membership, duplicate scan, late arrival, geo fence.
// token/expiry, same-day, roster membership, employee-no match, nonce replay,
// duplicate scan, late arrival, geo fence.
// 一期为确定性规则引擎,不调 LLM;规则参数来自 sign_policy 配置。
func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID, token string, lat, lng float64, channel string) (*types.TrainingSignRecord, error) {
// 2026-11 企微扫码需求增强:
// - 培训当天校验:非当天扫码签到直接友好提示(提前扫/过期补扫分文案);
// - 工号严格校验(in.EmployeeNo 非空时):须与登录账号档案工号一致,且必须在
// 该场次「参加人员」名单中 —— 名单外直接拒绝(不再仅标记待复核);
// - nonce 防重放 + client_ts 时钟偏差校验;
// - 轮换宽限:token 未命中当前码时接受 prev_token 在宽限期内签到。
// 既有登录态签到(不带 employee_no/nonce)行为不变:名单外仍标记 not_in_roster
// 进待复核,不硬拒。
func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID string, in *types.CheckinInput) (*types.TrainingSignRecord, error) {
if in == nil || in.Token == "" {
return nil, errors.NewBadRequestError("签到码无效")
}
token, lat, lng := in.Token, in.Lat, in.Lng
code, err := s.repo.GetSignCodeByToken(ctx, tenantID, token)
if err != nil {
return nil, errors.NewBadRequestError("签到码无效")
// 轮换宽限:未命中当前码时尝试前码(prev_token),宽限期内放行。
code, err = s.resolveCheckinPrevToken(ctx, tenantID, token)
if err != nil {
return nil, errors.NewBadRequestError("签到码无效或已更新,请重新扫码")
}
}
if code.ExpireAt != nil && time.Now().After(*code.ExpireAt) {
return nil, errors.NewBadRequestError("签到码已过期")
@@ -779,7 +852,7 @@ func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID,
return nil, errors.NewForbiddenError("未建立培训档案,无法签到")
}
// 名单校验(名单外人员自动标记)。
// 名单校验(名单外人员自动标记;严格模式下直接拒绝,见下)。
roster, err := s.repo.ListEnrollments(ctx, tenantID, session.ID)
if err != nil {
return nil, err
@@ -793,6 +866,47 @@ func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID,
}
now := time.Now()
// 严格扫码链路(employee_no 非空,即 2026-11 新签到页):当天校验/工号+名单
// 硬拒/nonce 防重放/时钟偏差仅作用于此链路。既有路径(登录态直签、代录补签)
// 行为不变 —— 尤其代录补签常发生在非当天,当天校验不得拦截。
strictScan := strings.TrimSpace(in.EmployeeNo) != ""
// 培训当天校验(2026-11 需求规则 1):非当天扫码签到,分提前/滞后友好提示。
// 时区固定北京时间,与前端 fmtBeijingTime 口径一致。
if strictScan && s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "same_day_check", 1) > 0 &&
session.StartAt != nil && !sameBeijingDay(now, *session.StartAt) {
if session.StartAt.After(now) {
return nil, errors.NewBadRequestError(
"培训尚未开始:该课程 " + fmtBeijingCST(session.StartAt) + " 开课,培训当天再来签到")
}
return nil, errors.NewBadRequestError("本课程签到已结束,无法补签")
}
// 工号严格校验(2026-11 需求规则 2 + 补充规则):工号须与档案一致,且必须在
// 「参加人员」名单中,名单外直接拒绝。
if strictScan {
if !strings.EqualFold(strings.TrimSpace(member.EmployeeNo), strings.TrimSpace(in.EmployeeNo)) {
return nil, errors.NewForbiddenError("录入工号与当前账号的档案工号不一致,请确认后重试")
}
if !inRoster {
return nil, errors.NewForbiddenError("您不在该课程的「参加人员」名单中,请联系讲师或人事确认")
}
}
// nonce 防重放 + 时钟偏差(仅扫码链路携带;同 nonce 二次提交直接拒绝)。
if strictScan && in.Nonce != "" {
if dup, derr := s.repo.GetSignRecordByNonce(ctx, tenantID, in.Nonce); derr == nil && dup != nil {
return nil, errors.NewBadRequestError("签到请求无效,请刷新页面后重试")
}
}
skewSec := s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "clock_skew_sec", 60)
if strictScan && in.ClientTS > 0 && skewSec > 0 {
if diff := now.UnixMilli() - in.ClientTS; diff > int64(skewSec)*1000 || diff < -int64(skewSec)*1000 {
return nil, errors.NewBadRequestError("签到请求时间异常,请校准手机时间后重试")
}
}
flags := []string{}
status := types.TrainingSignNormal
@@ -813,7 +927,7 @@ func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID,
}
}
// 名单外人员标记。
// 名单外人员标记(工号严格链路已在上方硬拒,此处仅既有登录态路径可达)。
if !inRoster {
flags = append(flags, "not_in_roster")
status = types.TrainingSignAbnormal
@@ -824,6 +938,7 @@ func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID,
return nil, errors.NewBadRequestError("您已签到,请勿重复扫码")
}
channel := in.Channel
if channel == "" {
channel = "wecom_scan"
}
@@ -839,6 +954,7 @@ func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID,
Lng: lng,
DistanceM: distance,
Status: status,
Nonce: strings.TrimSpace(in.Nonce),
AbnormalFlags: flagsJSON,
}
if err := s.repo.UpsertSignRecord(ctx, record); err != nil {
@@ -852,6 +968,28 @@ func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID,
return record, nil
}
// resolveCheckinPrevToken 轮换宽限:当前码未命中时按前码定位,宽限期内放行
// (rotation_grace_sec,默认 30s,0 = 严格作废)。跨租户 token 一律拒绝。
func (s *trainingService) resolveCheckinPrevToken(ctx context.Context, tenantID uint64, token string) (*types.TrainingSignCode, error) {
code, err := s.repo.GetSignCodeByTokenGlobal(ctx, token)
if err != nil || code == nil || code.TenantID != tenantID || code.Token == token {
return nil, errors.NewBadRequestError("签到码无效")
}
grace := time.Duration(s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "rotation_grace_sec", 30)) * time.Second
if code.PrevExpireAt == nil || time.Now().After(code.PrevExpireAt.Add(grace)) {
return nil, errors.NewBadRequestError("签到码已更新,请重新扫码")
}
return code, nil
}
// fmtBeijingCST 时间格式化为北京时间文案(当天性提示用)。
func fmtBeijingCST(t *time.Time) string {
if t == nil {
return ""
}
return t.In(time.FixedZone("CST", 8*3600)).Format("2006-01-02 15:04")
}
// haversineMeters computes the great-circle distance in meters.
func haversineMeters(lat1, lng1, lat2, lng2 float64) float64 {
const earthRadius = 6371000.0
+3 -2
View File
@@ -26,10 +26,11 @@ func (s *trainingService) CheckinFor(ctx context.Context, tenantID uint64, opera
return nil, errors.NewNotFoundError("成员不存在")
}
if target.UserID == operatorUserID {
return s.Checkin(ctx, tenantID, operatorUserID, token, lat, lng, channel)
return s.Checkin(ctx, tenantID, operatorUserID, &types.CheckinInput{Token: token, Lat: lat, Lng: lng, Channel: channel})
}
// 复用 Checkin 的规则引擎,以目标成员的 user_id 走完整校验。
record, err := s.Checkin(ctx, tenantID, target.UserID, token, lat, lng, "proxy")
// 代录不携工号/nonce:工号严格名单硬拒与防重放仅约束学员扫码链路。
record, err := s.Checkin(ctx, tenantID, target.UserID, &types.CheckinInput{Token: token, Lat: lat, Lng: lng, Channel: "proxy"})
if err != nil {
return nil, err
}
@@ -0,0 +1,239 @@
package service
// 企微扫码签到免登(2026-11 需求):
//
// 讲师端二维码(每 rotation_sec=5 分钟惰性轮换)→ 学员企微「扫一扫」→ 落地页
// → snsapi_base 静默授权 → code 换 userid → org_employees.wecom_userid 反查
// 培训档案 → 签发平台 JWT(签到即自动登录,SessionResponseForUser 与
// /auth/login 同构)→ 落地页点击「签到」→ 走 Checkin 规则引擎。
//
// 身份映射完全复用既有 wecom_userid 绑定(组织架构页维护/OA 同步);企微凭据
// 复用租户 IM webhook 渠道(与推送同一套 corp_id/agent_secret/corp_agent_id)。
// 本文件不 import internal/im:客户端经 WecomOAuthBackend 接口由容器注入
// (wecompush.Backend 适配,与 WecomPushBackend 同一模式,避免 im 测试环)。
import (
"context"
"strings"
"time"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/types"
"gorm.io/gorm"
)
// WecomOAuthClient 企微网页授权客户端(按租户解析出的自建应用凭据)。
type WecomOAuthClient interface {
// BuildOAuthAuthorizeURL 拼 snsapi_base 静默授权链接(state=签到码 token)。
BuildOAuthAuthorizeURL(redirectURI, state string) string
// GetOAuthUserID 网页授权 code 换企微 userid(code 一次性,5 分钟有效)。
GetOAuthUserID(ctx context.Context, code string) (string, error)
}
// WecomOAuthBackend resolves the per-tenant OAuth client. Implemented by
// internal/im/wecompush (which owns the internal/im dependency the service
// layer must avoid — same rationale as WecomPushBackend).
type WecomOAuthBackend interface {
OAuthClientForTenant(ctx context.Context, db *gorm.DB, tenantID uint64) (WecomOAuthClient, error)
}
// WecomCheckinAuthURL implements interfaces.TrainingService.
// GET /training/wecom/checkin-auth?token=xxx — 匿名入口:校验签到码后返回
// 企微授权链接;redirectURI 由落地页按当前域名拼出(kbt/kb 跟随二维码环境)。
func (s *trainingService) WecomCheckinAuthURL(ctx context.Context, token, redirectURI string) (string, error) {
token = strings.TrimSpace(token)
if token == "" {
return "", errors.NewBadRequestError("缺少签到码")
}
code, err := s.repo.GetSignCodeByTokenGlobal(ctx, token)
if err != nil || code == nil {
return "", errors.NewBadRequestError("签到码无效或已过期,请联系讲师刷新")
}
if code.ExpireAt != nil && time.Now().After(*code.ExpireAt) {
return "", errors.NewBadRequestError("签到码已更新,请重新扫码")
}
if s.wecomOAuth == nil {
return "", errors.NewInternalServerError("企微免登通道未配置")
}
client, err := s.wecomOAuth.OAuthClientForTenant(ctx, s.db, code.TenantID)
if err != nil {
// 渠道未配置(corp_id/secret 缺失)是运营配置问题,给可行动的文案。
return "", errors.NewBadRequestError("该空间未配置企微自建应用渠道,请联系管理员在 IM 集成中创建")
}
redirectURI = strings.TrimSpace(redirectURI)
if redirectURI == "" {
return "", errors.NewBadRequestError("缺少回跳地址")
}
return client.BuildOAuthAuthorizeURL(redirectURI, token), nil
}
// WecomCheckinSession implements interfaces.TrainingService.
// POST /training/wecom/checkin-session {code, state} — 匿名入口:OAuth code 换
// 身份并签发平台会话(签到即自动登录),同时一次带回落地页数据。
func (s *trainingService) WecomCheckinSession(ctx context.Context, oauthCode, state string) (*types.WecomCheckinSession, error) {
oauthCode, state = strings.TrimSpace(oauthCode), strings.TrimSpace(state)
if oauthCode == "" || state == "" {
return nil, errors.NewBadRequestError("授权参数不完整")
}
if s.wecomOAuth == nil {
return nil, errors.NewInternalServerError("企微免登通道未配置")
}
// state 即签到码 token(前端从落地页 URL 透传);命中当前码,或轮换宽限中的
// 前码 —— 后者覆盖"学员扫码后、OAuth 回跳前恰好轮换"的踩空窗口。
code, prev, err := s.resolveWecomSignCode(ctx, state)
if err != nil {
return nil, err
}
// 1) code → 企微 userid → 绑定反查培训档案(限定签到码所在空间)。
client, err := s.wecomOAuth.OAuthClientForTenant(ctx, s.db, code.TenantID)
if err != nil {
return nil, errors.NewBadRequestError("该空间未配置企微自建应用渠道,请联系管理员在 IM 集成中创建")
}
wecomUserid, err := client.GetOAuthUserID(ctx, oauthCode)
if err != nil {
logger.Warnf(ctx, "wecom checkin: oauth code exchange failed: %v", err)
return nil, errors.NewUnauthorizedError("企微授权失败或已过期,请重新扫码")
}
member, err := s.repo.GetMemberByWecomUserid(ctx, code.TenantID, wecomUserid)
if err != nil || member == nil {
return nil, errors.NewForbiddenError("未找到您的培训档案:企微账号未绑定或不在该空间培训名册,请联系人事在组织架构中维护")
}
// 2) 平台用户 + 签发会话(落点沿用登录解析,与 /auth/login 同构)。
user, err := s.users.GetUserByID(ctx, member.UserID)
if err != nil || user == nil {
return nil, errors.NewForbiddenError("培训档案未关联平台账号,请联系管理员")
}
login, err := s.users.SessionResponseForUser(ctx, user)
if err != nil {
logger.Warnf(ctx, "wecom checkin: issue session failed for user %s: %v", user.ID, err)
return nil, errors.NewInternalServerError("自动登录失败,请稍后重试")
}
// 3) 落地页数据一次带回(课程信息/倒计时/名单/重复标记)。
page, err := s.buildWecomCheckinPage(ctx, code, member, prev)
if err != nil {
return nil, err
}
return &types.WecomCheckinSession{LoginResponse: *login, WecomCheckinPage: *page}, nil
}
// WecomCheckinPage implements interfaces.TrainingService.
// POST /training/wecom/checkin-page {token} — 已登录用户(PC 讲师自测/企微内已
// 有会话)取落地页数据;租户走常规培训空间解析。
func (s *trainingService) WecomCheckinPage(ctx context.Context, tenantID uint64, userID, token string) (*types.WecomCheckinPage, error) {
code, err := s.repo.GetSignCodeByToken(ctx, tenantID, strings.TrimSpace(token))
if err != nil || code == nil {
return nil, errors.NewBadRequestError("签到码无效或已过期,请联系讲师刷新")
}
member, err := s.repo.GetMemberByUserID(ctx, tenantID, userID)
if err != nil || member == nil {
return nil, errors.NewForbiddenError("未建立培训档案,无法签到")
}
page, err := s.buildWecomCheckinPage(ctx, code, member, false)
if err != nil {
return nil, err
}
return page, nil
}
// ---------------------------------------------------------------------------
// 内部工具
// ---------------------------------------------------------------------------
// resolveWecomSignCode 按 state(token)定位签到码:优先当前码;未命中时接受
// 轮换宽限中的前码(rotation_grace_sec,默认 30s)。返回 (码行, 是否前码, 错误)。
func (s *trainingService) resolveWecomSignCode(ctx context.Context, token string) (*types.TrainingSignCode, bool, error) {
code, err := s.repo.GetSignCodeByTokenGlobal(ctx, token)
if err != nil || code == nil {
return nil, false, errors.NewBadRequestError("签到码无效或已过期,请重新扫码")
}
if code.Token == token {
return code, false, nil
}
// 前码:宽限期内放行(与 Checkin 的 prev-token 宽限同口径)。
grace := time.Duration(s.ruleFloat(ctx, code.TenantID, types.RuleKeySignPolicy, "rotation_grace_sec", 30)) * time.Second
if code.PrevExpireAt == nil || time.Now().After(code.PrevExpireAt.Add(grace)) {
return nil, false, errors.NewBadRequestError("签到码已更新,请重新扫码")
}
return code, true, nil
}
// buildWecomCheckinPage 组装落地页载荷:课程/场次摘要 + 当前成员名单/重复标记。
func (s *trainingService) buildWecomCheckinPage(ctx context.Context, code *types.TrainingSignCode, member *types.TrainingMember, prevToken bool) (*types.WecomCheckinPage, error) {
// 姓名:档案 UserName 为联查字段,直查不回填;用平台账号显示名补齐,
// 落地页「工号 + 姓名」确认行展示(免登链路学员核对身份用)。
if s.users != nil && member.UserName == "" {
if u, uerr := s.users.GetUserByID(ctx, member.UserID); uerr == nil && u != nil {
if u.DisplayName != "" {
member.UserName = u.DisplayName
} else {
member.UserName = u.Username
}
}
}
page := &types.WecomCheckinPage{
Member: member,
SessionID: code.SessionID,
SignExpireAt: code.ExpireAt,
}
session, err := s.repo.GetSession(ctx, code.TenantID, code.SessionID)
if err != nil || session == nil {
return nil, errors.NewBadRequestError("课程场次不存在")
}
course, err := s.repo.GetCourse(ctx, code.TenantID, session.CourseID)
if err != nil || course == nil {
return nil, errors.NewBadRequestError("课程不存在")
}
// 前码宽限进来时,倒计时以旧码剩余时间为准(归零即须重新扫码)。
if prevToken && code.PrevExpireAt != nil {
page.SignExpireAt = code.PrevExpireAt
}
// 讲师姓名:档案 UserName 为联查字段,直查不回填,取平台账号显示名兜底。
lecturerName := ""
if course.LecturerID != "" {
if lecturer, lerr := s.repo.GetMember(ctx, code.TenantID, course.LecturerID); lerr == nil && lecturer != nil && lecturer.UserName != "" {
lecturerName = lecturer.UserName
}
}
if lecturerName == "" && course.LecturerID != "" {
if lu, lerr := s.users.GetUserByID(ctx, course.LecturerID); lerr == nil && lu != nil {
lecturerName = lu.DisplayName
if lecturerName == "" {
lecturerName = lu.Username
}
}
}
page.Course = &types.WecomCheckinCourse{
CourseID: course.ID,
CourseName: course.Name,
LecturerName: lecturerName,
StartAt: session.StartAt,
EndAt: session.EndAt,
Location: session.Location,
Status: session.Status,
// 当天性判定与 Checkin 的 same-day 规则同一口径(北京时间)。
CanSignToday: session.StartAt != nil && sameBeijingDay(time.Now(), *session.StartAt),
}
// 名单/重复标记:前端提前渲染按钮态(置灰/已签到),提交时后端仍强校验兜底。
if roster, rerr := s.repo.ListEnrollments(ctx, code.TenantID, session.ID); rerr == nil {
for _, e := range roster {
if e.MemberID == member.ID {
page.InRoster = true
break
}
}
}
if rec, rerr := s.repo.GetSignRecord(ctx, code.TenantID, session.ID, member.ID); rerr == nil && rec != nil {
page.AlreadySigned = true
}
return page, nil
}
// sameBeijingDay 判断两个时刻是否同一「北京时间」自然日(签到当天性校验统一
// 口径;固定 +8 偏移,不依赖服务器时区,与前端 fmtBeijingTime 一致)。
func sameBeijingDay(a, b time.Time) bool {
cst := time.FixedZone("CST", 8*3600)
ay, am, ad := a.In(cst).Date()
by, bm, bd := b.In(cst).Date()
return ay == by && am == bm && ad == bd
}
+33
View File
@@ -324,6 +324,39 @@ func (s *userService) Login(ctx context.Context, req *types.LoginRequest) (*type
}, nil
}
// SessionResponseForUser assembles a login response for an already
// authenticated identity (2026-11 企微扫码签到免登):落点沿用登录解析(最近活跃
// 租户偏好优先),token/tenant/memberships 与 /auth/login 同构,前端复用同一
// 持久化路径完成"签到即自动登录"。
func (s *userService) SessionResponseForUser(ctx context.Context, user *types.User) (*types.LoginResponse, error) {
if user == nil {
return nil, errors.New("user is required")
}
resolvedTenantID := s.resolveLoginTenantID(ctx, user)
accessToken, refreshToken, err := s.generateTokensForTenant(ctx, user, resolvedTenantID)
if err != nil {
logger.Errorf(ctx, "Failed to generate session tokens: %v", err)
return nil, fmt.Errorf("generate session tokens: %w", err)
}
var tenant *types.Tenant
if resolvedTenantID > 0 {
if t, terr := s.tenantService.GetTenantByID(ctx, resolvedTenantID); terr == nil {
tenant = t
} else {
logger.Warn(ctx, "Failed to get tenant info")
}
}
return &types.LoginResponse{
Success: true,
Message: "Login successful",
User: user,
ActiveTenant: tenant,
Memberships: s.buildMembershipsForUser(ctx, user, tenant),
Token: accessToken,
RefreshToken: refreshToken,
}, nil
}
// buildMembershipsForUser returns the user's tenant memberships projected
// into the login-response shape. activeTenant (if non-nil and matching one
// of the rows) is used to reuse its already-fetched name without a second
+17
View File
@@ -413,6 +413,12 @@ func BuildContainer(container *dig.Container) *dig.Container {
// Training domain (企业培训业务域): repo → service(interface) → handler.
must(container.Provide(repository.NewTrainingRepository))
must(container.Provide(service.NewTrainingService, dig.As(new(interfaces.TrainingService))))
// 企微扫码签到免登后端(2026-11 需求):与 scheduler 的 wecom 适配同一来源
// (trainingWecomBackend 包装 wecompush.Backend),经接口注入 service 层,
// service 不 import internal/im(同 WecomPushBackend 的防环理由)。
must(container.Provide(func() service.WecomOAuthBackend {
return trainingWecomBackend{wecompush.Backend{}}
}))
// Session service (depends on agent service)
// SessionService is created after AgentService and passes itself to AgentService.CreateAgentEngine when needed
@@ -2181,6 +2187,17 @@ func (b trainingWecomBackend) TenantWecomUserIDs(ctx context.Context, db *gorm.D
return b.inner.TenantWecomUserIDs(ctx, db, tenantID, userIDs)
}
// OAuthClientForTenant boxes the concrete *wecom.ProactiveClient into
// service.WecomOAuthClient (培训扫码签到免登:snsapi_base 授权链接 + code 换
// userid;同一自建应用凭据,复用 ClientForTenant 的渠道解析)。
func (b trainingWecomBackend) OAuthClientForTenant(ctx context.Context, db *gorm.DB, tenantID uint64) (service.WecomOAuthClient, error) {
client, err := b.inner.OAuthClientForTenant(ctx, db, tenantID)
if err != nil {
return nil, err
}
return client, nil
}
// startTrainingScheduler starts the training WeCom reminder scheduler and
// registers cleanup. Best-effort like the other background runners.
func startTrainingScheduler(scheduler *service.TrainingScheduler, cleaner interfaces.ResourceCleaner) {
+100 -1
View File
@@ -1788,6 +1788,12 @@ type CheckinRequest struct {
Channel string `json:"channel"`
// MemberID 可选:讲师/课长/人事现场代扫码/补录。
MemberID string `json:"member_id"`
// EmployeeNo 录入工号(2026-11 扫码签到页必带):非空时启用严格校验
// (工号与档案一致 + 必须在「参加人员」名单 + 当天性 + nonce 防重放)。
EmployeeNo string `json:"employee_no"`
// Nonce 随机时间戳防重放;ClientTS 客户端提交时刻毫秒(时钟偏差校验)。
Nonce string `json:"nonce"`
ClientTS int64 `json:"client_ts"`
}
// Checkin POST /training/sign-records/checkin — 学员扫码签到(带定位校验);
@@ -1811,7 +1817,15 @@ func (h *Handler) Checkin(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "data": record})
return
}
record, err := h.svc.Checkin(ctx, callerTenantID(c), callerUserID(c), req.Token, req.Lat, req.Lng, req.Channel)
record, err := h.svc.Checkin(ctx, callerTenantID(c), callerUserID(c), &types.CheckinInput{
Token: req.Token,
Lat: req.Lat,
Lng: req.Lng,
Channel: req.Channel,
EmployeeNo: req.EmployeeNo,
Nonce: req.Nonce,
ClientTS: req.ClientTS,
})
if err != nil {
_ = c.Error(err)
return
@@ -1819,6 +1833,91 @@ func (h *Handler) Checkin(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "data": record})
}
// ---------------------------------------------------------------------------
// 企微扫码签到免登(2026-11 需求):匿名入口,路由直挂 v1 组外 +
// noAuthAPI 白名单 + PublicAuthRateLimit,身份由签到码 token / OAuth code 承载。
// ---------------------------------------------------------------------------
// WecomCheckinAuthRequest is the query of GET /training/wecom/checkin-auth.
// redirect_uri 由落地页按当前域名拼出(测试 kbt / 正式 kb 跟随二维码环境)。
type WecomCheckinAuthRequest struct {
Token string `form:"token" binding:"required"`
RedirectURI string `form:"redirect_uri"`
}
// WecomCheckinAuth GET /training/wecom/checkin-auth — 返回企微 snsapi_base
// 静默授权链接,前端 location.replace 跳转(学员无感)。
func (h *Handler) WecomCheckinAuth(c *gin.Context) {
var q WecomCheckinAuthRequest
if err := c.ShouldBindQuery(&q); err != nil {
_ = c.Error(errors.NewBadRequestError("缺少签到码").WithDetails(err.Error()))
return
}
redirectURI := strings.TrimSpace(q.RedirectURI)
if redirectURI == "" {
// 兜底:按请求 Host 还原落地页地址(反代透传 X-Forwarded-Proto)。
scheme := "https"
if c.Request.TLS == nil {
if proto := strings.TrimSpace(c.GetHeader("X-Forwarded-Proto")); proto != "" {
scheme = proto
} else {
scheme = "http"
}
}
redirectURI = fmt.Sprintf("%s://%s/platform/training/checkin/%s", scheme, c.Request.Host, q.Token)
}
url, err := h.svc.WecomCheckinAuthURL(c.Request.Context(), q.Token, redirectURI)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"authorize_url": url}})
}
// WecomCheckinSessionRequest is the body of POST /training/wecom/checkin-session.
type WecomCheckinSessionRequest struct {
Code string `json:"code" binding:"required"`
State string `json:"state" binding:"required"`
}
// WecomCheckinSession POST /training/wecom/checkin-session — OAuth code 换
// 平台会话(token/refresh_token/user/active_tenant/memberships,与 /auth/login
// 同构,前端复用登录持久化路径即"签到即自动登录")+ 落地页数据。
func (h *Handler) WecomCheckinSession(c *gin.Context) {
var req WecomCheckinSessionRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("授权参数不完整").WithDetails(err.Error()))
return
}
session, err := h.svc.WecomCheckinSession(c.Request.Context(), req.Code, req.State)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": session})
}
// WecomCheckinPageRequest is the body of POST /training/wecom/checkin-page.
type WecomCheckinPageRequest struct {
Token string `json:"token" binding:"required"`
}
// WecomCheckinPage POST /training/wecom/checkin-page — 已登录用户(PC 讲师
// 自测/企微内已有会话)取落地页数据;认证守卫 + 培训空间解析之后。
func (h *Handler) WecomCheckinPage(c *gin.Context) {
var req WecomCheckinPageRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("缺少签到码").WithDetails(err.Error()))
return
}
page, err := h.svc.WecomCheckinPage(c.Request.Context(), callerTenantID(c), callerUserID(c), req.Token)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": page})
}
// ListSignRecords GET /training/sessions/:id/sign-records — 签到明细。
func (h *Handler) ListSignRecords(c *gin.Context) {
items, err := h.svc.ListSignRecords(c.Request.Context(), callerTenantID(c), c.Param("id"))
+60
View File
@@ -13,6 +13,7 @@ import (
"encoding/json"
"fmt"
"net/http"
neturl "net/url"
"strings"
"sync"
"time"
@@ -111,6 +112,65 @@ func (c *ProactiveClient) SendMarkdown(ctx context.Context, userIDs []string, co
return nil
}
// wecomOAuthAuthorizeBase 企微网页授权入口(公开固定地址,不走 apiBaseURL ——
// 后者可被私有化部署改写,而 OAuth 授权页始终由微信侧提供)。
const wecomOAuthAuthorizeBase = "https://open.weixin.qq.com/connect/oauth2/authorize"
// BuildOAuthAuthorizeURL 企微网页授权链接(snsapi_base 静默免登,培训扫码签到用):
// 学员在企微内置浏览器打开后无感授权,302 回 redirect_uri 并携带 code 与 state。
func (c *ProactiveClient) BuildOAuthAuthorizeURL(redirectURI, state string) string {
return fmt.Sprintf(
"%s?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=%s&agentid=%d#wechat_redirect",
wecomOAuthAuthorizeBase,
neturl.QueryEscape(c.corpID),
neturl.QueryEscape(redirectURI),
neturl.QueryEscape(state),
c.corpAgentID,
)
}
// GetOAuthUserID 网页授权 code 换用户身份(GET /cgi-bin/auth/getuserinfo):
// snsapi_base 静默授权即可拿到 userid;code 由企微保证一次性(5 分钟有效)。
func (c *ProactiveClient) GetOAuthUserID(ctx context.Context, code string) (string, error) {
accessToken, err := c.getAccessToken(ctx)
if err != nil {
return "", fmt.Errorf("get access token: %w", err)
}
userURL := fmt.Sprintf("%s/cgi-bin/auth/getuserinfo?access_token=%s&code=%s",
c.apiBaseURL, accessToken, neturl.QueryEscape(code))
req, err := http.NewRequestWithContext(ctx, http.MethodGet, userURL, nil)
if err != nil {
return "", fmt.Errorf("create request: %w", err)
}
resp, err := httpClient.Do(req)
if err != nil {
return "", fmt.Errorf("request oauth userinfo: %w", err)
}
defer resp.Body.Close()
var result struct {
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
UserID string `json:"userid"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", fmt.Errorf("decode oauth userinfo: %w", err)
}
if result.ErrCode != 0 {
// 42001/40014 token 过期类错误清缓存,让下次调用重新获取。
if result.ErrCode == 42001 || result.ErrCode == 40014 {
c.tokenMu.Lock()
c.tokenCache = ""
c.tokenExpAt = time.Time{}
c.tokenMu.Unlock()
}
return "", fmt.Errorf("wecom oauth api error: code=%d msg=%s", result.ErrCode, result.ErrMsg)
}
if result.UserID == "" {
return "", fmt.Errorf("wecom oauth api returned empty userid")
}
return result.UserID, nil
}
// getAccessToken retrieves the WeCom access token with caching.
func (c *ProactiveClient) getAccessToken(ctx context.Context) (string, error) {
c.tokenMu.Lock()
+6
View File
@@ -91,6 +91,12 @@ func (Backend) ClientForTenant(ctx context.Context, db *gorm.DB, tenantID uint64
return TenantClient(ctx, db, tenantID)
}
// OAuthClientForTenant resolves the tenant's client for web OAuth (培训扫码
// 签到免登):同一个自建应用凭据既推消息也做网页授权,复用一套配置。
func (Backend) OAuthClientForTenant(ctx context.Context, db *gorm.DB, tenantID uint64) (*wecom.ProactiveClient, error) {
return TenantClient(ctx, db, tenantID)
}
// TenantWecomUserIDs resolves the userid bindings.
func (Backend) TenantWecomUserIDs(ctx context.Context, db *gorm.DB, tenantID uint64, userIDs []string) (map[string]string, error) {
return TenantWecomUserIDs(ctx, db, tenantID, userIDs)
+5
View File
@@ -64,6 +64,11 @@ var noAuthAPI = map[string][]string{
// template key + 20-day expiry), never by caller-supplied ids. HEAD is
// allowed for the same preview-validation reason as /files/presigned.
"/api/v1/training/templates/signed-file": {"GET", "HEAD"},
// 企微扫码签到免登(2026-11 需求):学员在企微内置浏览器打开落地页时没有
// 平台会话,免登链路凭「未过期签到码 token(state)+ 一次性 OAuth code」
// 鉴权,路由级 IP 限流承担防滥用;checkin-page(登录态)不在此列。
"/api/v1/training/wecom/checkin-auth": {"GET"},
"/api/v1/training/wecom/checkin-session": {"POST"},
// IM platforms (Feishu, Slack, etc.) commonly issue a HEAD request
// before GET to validate Content-Type / Content-Length when rendering
// image previews — both verbs must be allowed for image links to work.
+22 -1
View File
@@ -119,9 +119,30 @@ var publicAuthLimiter = newIPRateLimiter(
// through the project's AppError type so it flows through the same
// error middleware as the rest of the auth surface.
func PublicAuthRateLimit() gin.HandlerFunc {
return rateLimitWith(publicAuthLimiter)
}
// wecomCheckinRateLimitMax 培训扫码免登专用预算:教室场景几十名学员共享同一
// 办公网出口 IP,若复用 30/min 的共享 auth 限流,集中扫码会整批 429。签到
// 链路独立限流器放宽到 600/min/IP(百人级课堂在 5 分钟轮换窗口内仍宽裕),
// 同时保留对脚本刷 code/token 的约束。
const wecomCheckinRateLimitMax = 600
// wecomCheckinLimiter 独立桶,不与 share-link/auth 端点共享预算。
var wecomCheckinLimiter = newIPRateLimiter(publicAuthRateLimitWindow, wecomCheckinRateLimitMax)
// WecomCheckinRateLimit rate-limits the anonymous WeCom scan-checkin endpoints
// (checkin-auth / checkin-session) by client IP.
func WecomCheckinRateLimit() gin.HandlerFunc {
return rateLimitWith(wecomCheckinLimiter)
}
// rateLimitWith adapts an ipRateLimiter into Gin middleware; 429 flows through
// the project's AppError middleware like the rest of the auth surface.
func rateLimitWith(l *ipRateLimiter) gin.HandlerFunc {
return func(c *gin.Context) {
ip := c.ClientIP()
if !publicAuthLimiter.allow(ip) {
if !l.allow(ip) {
c.Error(&apperrors.AppError{
Code: apperrors.ErrTooManyRequests,
Message: "too many requests; please retry shortly",
+11
View File
@@ -4,6 +4,7 @@ import (
"strings"
"academy/internal/handler/training"
"academy/internal/middleware"
"academy/internal/utils"
"github.com/gin-gonic/gin"
)
@@ -24,6 +25,12 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
// trainingGroup 之外直挂 v1;静态段先于 :key 参数段注册。常量是含 /api/v1
// 的全路径(noAuthAPI 白名单与企微 footer 共用),此处挂 v1 组剥掉前缀。
r.GET(strings.TrimPrefix(utils.TrainingTemplateSignedFilePath, "/api/v1"), h.DownloadTrainingTemplateSigned)
// 企微扫码签到免登(2026-11 需求):两个匿名入口直挂 v1(noAuthAPI 白名单 +
// 路由级 IP 限流),身份由签到码 token / OAuth code 承载,不走 Viewer 登录
// 守卫。限流用签到专用桶 WecomCheckinRateLimit(600/min/IP):教室几十人
// 共享一个出口 IP,共享 auth 限流(30/min)会整批 429。
r.GET("/training/wecom/checkin-auth", middleware.WecomCheckinRateLimit(), h.WecomCheckinAuth)
r.POST("/training/wecom/checkin-session", middleware.WecomCheckinRateLimit(), h.WecomCheckinSession)
// TrainingTenantResolution(000160):培训域数据空间按员工档案归属解析 ——
// 当前空间无培训档案但组织中心有在职档案的用户,培训读写回落到档案所在
// 空间;同一组织的人员在任意工作区都能参与企业培训(须在 Viewer 守卫之后)。
@@ -134,8 +141,12 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
// ---- 签到域 ----
trainingGroup.POST("/sessions/:id/sign-code", g.Contributor(), h.CreateSignCode)
// sessions/:id/sign-code GET 兼职惰性轮换触发器(2026-11:讲师页每 10s
// 轮询,超 rotation_sec 窗口自动轮换返回新码,旧码即时作废)。
trainingGroup.GET("/sessions/:id/sign-code", h.GetSignCode)
trainingGroup.POST("/sign-records/checkin", h.Checkin)
// wecom/checkin-page 落地页数据(登录态;PC 讲师自测/企微内已有会话)。
trainingGroup.POST("/wecom/checkin-page", h.WecomCheckinPage)
trainingGroup.GET("/sessions/:id/sign-records", h.ListSignRecords)
trainingGroup.POST("/sign-records/:id/review", g.Contributor(), h.ReviewSignRecord)
trainingGroup.GET("/sessions/:id/sign-summary", h.SignSummary)
+21 -1
View File
@@ -49,6 +49,9 @@ type TrainingRepository interface {
// 等场景高频只读);部门与名册管理走 OrgCenterRepository。
GetMember(ctx context.Context, tenantID uint64, id string) (*types.TrainingMember, error)
GetMemberByUserID(ctx context.Context, tenantID uint64, userID string) (*types.TrainingMember, error)
// GetMemberByWecomUserid 企微免登反查:按 org_employees.wecom_userid 定位
// 培训档案(扫码签到 code 换身份,2026-11 需求)。
GetMemberByWecomUserid(ctx context.Context, tenantID uint64, wecomUserid string) (*types.TrainingMember, error)
// FindArchiveTenantID 跨租户定位用户最早在职员工档案(org_employees)的租户
// (000160 培训数据空间解析的回退依据;无档案返回 0,nil)。
FindArchiveTenantID(ctx context.Context, userID string) (uint64, error)
@@ -141,9 +144,14 @@ type TrainingRepository interface {
UpsertSignCode(ctx context.Context, code *types.TrainingSignCode) error
GetSignCodeBySession(ctx context.Context, tenantID uint64, sessionID string) (*types.TrainingSignCode, error)
GetSignCodeByToken(ctx context.Context, tenantID uint64, token string) (*types.TrainingSignCode, error)
// GetSignCodeByTokenGlobal 匿名扫码入口(checkin-auth/checkin-session)按 token
// 全局定位签到码,租户由码行反解;同时命中当前码与轮换宽限中的前码(prev_token)。
GetSignCodeByTokenGlobal(ctx context.Context, token string) (*types.TrainingSignCode, error)
UpsertSignRecord(ctx context.Context, record *types.TrainingSignRecord) error
GetSignRecord(ctx context.Context, tenantID uint64, sessionID, memberID string) (*types.TrainingSignRecord, error)
GetSignRecordByID(ctx context.Context, tenantID uint64, id string) (*types.TrainingSignRecord, error)
// GetSignRecordByNonce 防重放:扫码签到 nonce 已用过则拒绝(2026-11 需求)。
GetSignRecordByNonce(ctx context.Context, tenantID uint64, nonce string) (*types.TrainingSignRecord, error)
ListSignRecords(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingSignRecord, error)
ReviewSignRecord(ctx context.Context, record *types.TrainingSignRecord) error
SignSummary(ctx context.Context, tenantID uint64, sessionID string) (*types.TrainingSignSummary, error)
@@ -369,14 +377,26 @@ type TrainingService interface {
// 签到域
CreateSignCode(ctx context.Context, tenantID uint64, sessionID string, lat, lng float64, radius int, operatorID string) (*types.TrainingSignCode, error)
// GetSignCode 取场次当前签到码;超过轮换窗口(rotation_sec,默认 5 分钟)时
// 惰性轮换:旧 token 挪入 prev,新码即时生效(2026-11 企微扫码需求)。
GetSignCode(ctx context.Context, tenantID uint64, sessionID string) (*types.TrainingSignCode, error)
Checkin(ctx context.Context, tenantID uint64, userID, token string, lat, lng float64, channel string) (*types.TrainingSignRecord, error)
// Checkin 学员扫码签到(带定位校验);in.EmployeeNo 非空时启用严格校验:
// 工号须与档案一致且在「参加人员」名单中,名单外直接拒绝(2026-11 需求)。
Checkin(ctx context.Context, tenantID uint64, userID string, in *types.CheckinInput) (*types.TrainingSignRecord, error)
// CheckinFor 文员代扫码/补录:以目标成员身份签到(proxy 标记留痕)。
CheckinFor(ctx context.Context, tenantID uint64, operatorUserID, token, targetMemberID string, lat, lng float64, channel string) (*types.TrainingSignRecord, error)
ListSignRecords(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingSignRecord, error)
ReviewSignRecord(ctx context.Context, tenantID uint64, recordID, decision, operatorID string) (*types.TrainingSignRecord, error)
SignSummary(ctx context.Context, tenantID uint64, sessionID string) (*types.TrainingSignSummary, error)
ExportEvidence(ctx context.Context, tenantID uint64, sessionIDs []string) (filename string, data []byte, err error)
// ---- 企微扫码签到免登(2026-11 需求) ----
// WecomCheckinAuthURL 按签到码 token 生成企微网页授权链接(snsapi_base 静默)。
WecomCheckinAuthURL(ctx context.Context, token, redirectURI string) (string, error)
// WecomCheckinSession OAuth code 换身份:反查 wecom_userid 绑定、签发平台
// JWT(签到即自动登录)并一次带回落地页数据。
WecomCheckinSession(ctx context.Context, code, state string) (*types.WecomCheckinSession, error)
// WecomCheckinPage 已登录用户(PC 自测)取落地页数据。
WecomCheckinPage(ctx context.Context, tenantID uint64, userID, token string) (*types.WecomCheckinPage, error)
// ---- 培训佐证文件(签到照/培训视频) ----
// UploadSessionEvidence 上传线下课佐证:签到照/培训视频按 file_key 落对象存储。
+6
View File
@@ -51,6 +51,12 @@ type UserService interface {
ValidatePassword(ctx context.Context, userID string, password string) error
// GenerateTokens generates access and refresh tokens for user
GenerateTokens(ctx context.Context, user *types.User) (accessToken, refreshToken string, err error)
// SessionResponseForUser assembles a full login response (token pair +
// active tenant + memberships) for an already authenticated identity,
// honouring the same login tenant resolution as /auth/login. Used by the
// WeCom scan-checkin silent-login path so the browser persists the
// session exactly like a normal login (2026-11 需求).
SessionResponseForUser(ctx context.Context, user *types.User) (*types.LoginResponse, error)
// BuildLoginMemberships projects the user's tenant memberships into
// the login-response shape. activeTenant is reused (without an extra
// lookup) for the matching row's TenantName. The slice is guaranteed
+66 -7
View File
@@ -749,13 +749,18 @@ type TrainingSignCode struct {
SessionID string `json:"session_id" gorm:"type:varchar(36);not null;uniqueIndex:uq_tr_sign_codes_session"`
Token string `json:"token" gorm:"type:varchar(64);not null;uniqueIndex:uq_tr_sign_codes_token"`
ExpireAt *time.Time `json:"expire_at"`
GeoLat float64 `json:"geo_lat" gorm:"default:0"`
GeoLng float64 `json:"geo_lng" gorm:"default:0"`
GeoRadius int `json:"geo_radius" gorm:"default:0"`
CreatedBy string `json:"created_by" gorm:"type:varchar(36);default:''"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"-" gorm:"index"`
// PrevToken/PrevExpireAt 轮换宽限(2026-11 需求:二维码每 5 分钟自动轮换,
// 旧码即时作废;宽限期内(prev_expire_at + rotation_grace_sec)仍可签到,
// 防"扫码即轮换"踩空。零值 = 无前码,严格作废。
PrevToken string `json:"prev_token" gorm:"type:varchar(64);default:''"`
PrevExpireAt *time.Time `json:"prev_expire_at"`
GeoLat float64 `json:"geo_lat" gorm:"default:0"`
GeoLng float64 `json:"geo_lng" gorm:"default:0"`
GeoRadius int `json:"geo_radius" gorm:"default:0"`
CreatedBy string `json:"created_by" gorm:"type:varchar(36);default:''"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"-" gorm:"index"`
}
// TableName pins the physical table name.
@@ -773,6 +778,8 @@ type TrainingSignRecord struct {
Lng float64 `json:"lng" gorm:"default:0"`
DistanceM float64 `json:"distance_m" gorm:"default:0"`
Status string `json:"status" gorm:"type:varchar(16);default:'normal';index"`
// Nonce 扫码签到随机时间戳(防重放留痕;同 nonce 二次提交直接拒绝,2026-11 需求)。
Nonce string `json:"nonce" gorm:"type:varchar(64);default:''"`
AbnormalFlags JSON `json:"abnormal_flags" gorm:"type:jsonb;default:'[]'"`
ReviewedBy string `json:"reviewed_by" gorm:"type:varchar(36);default:''"`
ReviewedAt *time.Time `json:"reviewed_at"`
@@ -784,6 +791,58 @@ type TrainingSignRecord struct {
// TableName pins the physical table name.
func (TrainingSignRecord) TableName() string { return "tr_sign_records" }
// CheckinInput 学员本人扫码签到入参(2026-11 企微扫码免登需求;代录仍走
// CheckinFor,不受这些严格校验约束)。
type CheckinInput struct {
Token string `json:"token"`
Lat float64 `json:"lat"`
Lng float64 `json:"lng"`
Channel string `json:"channel"`
// EmployeeNo 录入工号:非空时启用严格校验 —— 必须与登录账号档案工号一致,
// 且必须在该场次「参加人员」名单中(名单外直接拒绝,不再仅标记待复核)。
EmployeeNo string `json:"employee_no"`
// Nonce 随机时间戳(前端生成 Date.now()+随机段):同 nonce 二次提交拒绝(防重放)。
Nonce string `json:"nonce"`
// ClientTS 客户端提交时刻(毫秒):>0 时校验与服务器时钟偏差(clock_skew_sec)。
ClientTS int64 `json:"client_ts"`
}
// WecomCheckinCourse 企微扫码签到落地页的课程/场次摘要(补充需求 1:签到页展示课程信息)。
type WecomCheckinCourse struct {
CourseID string `json:"course_id"`
CourseName string `json:"course_name"`
LecturerName string `json:"lecturer_name"`
StartAt *time.Time `json:"start_at"`
EndAt *time.Time `json:"end_at"`
Location string `json:"location"`
Status string `json:"status"`
// CanSignToday 是否培训当天(非当天前端置灰签到按钮并提示,后端仍强校验兜底)。
CanSignToday bool `json:"can_sign_today"`
}
// WecomCheckinPage 企微扫码签到落地页数据:免登(code 换会话)与已登录 PC 自测
// 两条路径共用同一份页面载荷。
type WecomCheckinPage struct {
Member *OrgEmployee `json:"member,omitempty"` // 工号/姓名确认行
Course *WecomCheckinCourse `json:"course,omitempty"`
// CourseID 课程详情页跳转(签到成功后自动进入,2026-11 需求补充 3)。
CourseID string `json:"course_id"`
// SessionID 场次 id(签到接口定位/排查用)。
SessionID string `json:"session_id"`
// SignExpireAt 当前签到码有效期:落地页倒计时数据源(补充需求 2)。
SignExpireAt *time.Time `json:"sign_expire_at"`
InRoster bool `json:"in_roster"`
AlreadySigned bool `json:"already_signed"`
}
// WecomCheckinSession 企微 OAuth code 换会话响应:内嵌 LoginResponse(token/
// refresh_token/user/active_tenant/memberships),前端与 /auth/login 同构持久化,
// 即"签到即自动登录";并携带落地页数据一次返回。
type WecomCheckinSession struct {
LoginResponse
WecomCheckinPage
}
// 培训佐证文件类型:签到照 / 培训视频。
const (
TrainingEvidenceSignPhoto = "sign_photo"
@@ -0,0 +1,9 @@
-- Migration: 000162_training_sign_rotation (down)
-- 回滚轮换/防重放列;签到流水 nonce 列一并移除(留痕数据随列删除)。
ALTER TABLE tr_sign_codes
DROP COLUMN IF EXISTS prev_token,
DROP COLUMN IF EXISTS prev_expire_at;
ALTER TABLE tr_sign_records
DROP COLUMN IF EXISTS nonce;
@@ -0,0 +1,17 @@
-- Migration: 000162_training_sign_rotation
-- 企微扫码签到免登 + 二维码 5 分钟轮换(2026-11 需求):
-- 1. tr_sign_codes 增 prev_token / prev_expire_at:轮换时旧 token 挪入前码位,
-- 宽限期内(rotation_grace_sec,默认 30s)仍可签到,防"扫码即轮换"踩空;
-- upsert 覆盖后旧 token 即刻退出当前码位(GetSignCodeByToken 不再命中)。
-- 2. tr_sign_records 增 nonce:扫码签到随机时间戳防重放留痕,同 nonce 二次
-- 提交直接拒绝;历史行默认空串,不参与查重(空 nonce 不查)。
-- 全部 ADD COLUMN IF NOT EXISTS,迁移幂等可重放。
DO $$ BEGIN RAISE NOTICE '[Migration 000162] Adding sign-code rotation / sign-record nonce columns...'; END $$;
ALTER TABLE tr_sign_codes
ADD COLUMN IF NOT EXISTS prev_token VARCHAR(64) NOT NULL DEFAULT '',
ADD COLUMN IF NOT EXISTS prev_expire_at TIMESTAMP WITH TIME ZONE;
ALTER TABLE tr_sign_records
ADD COLUMN IF NOT EXISTS nonce VARCHAR(64) NOT NULL DEFAULT '';