跟新
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
import request from '@/utils/request'
|
||||
export type IdentityOperation = {
|
||||
kind: 'bind' | 'create_and_bind' | 'unbind' | 'rebind' | 'reconcile'
|
||||
user_id: number
|
||||
employee_id?: string
|
||||
expected_version?: number
|
||||
new_employee?: { username: string; display_name: string; email?: string }
|
||||
reason: string
|
||||
}
|
||||
const prefix = '/iam/v2'
|
||||
const opts = { isOpenRetry: false, ignoreCancelToken: true }
|
||||
export const iamGet = (path: string, params?: Record<string, unknown>): Promise<any> =>
|
||||
request.get({ url: prefix + path, params, withCredentials: true }, opts)
|
||||
export const iamPost = (
|
||||
path: string,
|
||||
params: Record<string, unknown> = {},
|
||||
key = crypto.randomUUID()
|
||||
): Promise<any> =>
|
||||
request.post(
|
||||
{ url: prefix + path, params, headers: { 'Idempotency-Key': key }, withCredentials: true },
|
||||
opts
|
||||
)
|
||||
export const identityError = (e: any): string =>
|
||||
({
|
||||
REAUTH_REQUIRED: '请先验证当前账号密码,或通过企业微信重新登录。',
|
||||
ACCOUNT_MISMATCH: '两端账号不一致,请确认身份后重新发起。',
|
||||
NOT_LINKED: '当前账号还未关联 IAM。',
|
||||
NOT_AUTHORIZED: 'IAM 尚未授予目标应用访问权限。',
|
||||
BINDING_CONFLICT: '关联已变更,请刷新后重新确认。',
|
||||
PROTECTED_ACCOUNT_REVIEW_REQUIRED: '敏感账号需要双侧近期管理员核验,请由统一身份平台审核。',
|
||||
SERVICE_UNAVAILABLE: '统一身份服务暂时不可用,状态未确认,请稍后重试。',
|
||||
FEATURE_DISABLED: 'IAM 关联管理尚未启用。',
|
||||
FORBIDDEN: '没有当前操作权限或目标超出数据范围。',
|
||||
TRANSACTION_EXPIRED: '验证已过期或已经使用,请重新发起。'
|
||||
})[e?.error?.code as string] ||
|
||||
e?.error?.code ||
|
||||
'操作未完成,请刷新状态后重试。'
|
||||
@@ -0,0 +1,33 @@
|
||||
<template>
|
||||
<el-button v-if="enabled" text :loading="busy" @click="launch">进入甄美 ERP ↗</el-button>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { iamGet, iamPost, identityError } from '@/api/iam-v2'
|
||||
const enabled = ref(false),
|
||||
busy = ref(false)
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const status = await iamGet('/status')
|
||||
enabled.value = !!status.enabled && status.launch_enabled === true
|
||||
} catch {
|
||||
enabled.value = false
|
||||
}
|
||||
})
|
||||
async function launch() {
|
||||
const tab = window.open('about:blank', '_blank')
|
||||
if (tab) tab.opener = null
|
||||
busy.value = true
|
||||
try {
|
||||
const r = await iamPost('/launch/start')
|
||||
if (tab) tab.location.href = r.url
|
||||
else ElMessage.warning('请允许新标签页后再试。')
|
||||
} catch (e) {
|
||||
tab?.close()
|
||||
ElMessage.warning(identityError(e))
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,137 @@
|
||||
<template>
|
||||
<el-card v-if="status?.enabled || error" class="mt-4" shadow="never">
|
||||
<template #header
|
||||
><strong>统一身份 IAM</strong
|
||||
><el-button class="float-right" text @click="refresh">刷新状态</el-button></template
|
||||
>
|
||||
<el-alert v-if="error" :title="error" type="warning" :closable="false" class="mb-4" />
|
||||
<p>
|
||||
关联状态:<el-tag :type="linked ? 'success' : 'info'">{{
|
||||
linked ? '已关联' : status.binding?.state === 'revoked' ? '关联已撤销' : '未关联'
|
||||
}}</el-tag>
|
||||
</p>
|
||||
<p v-if="status.employee" class="my-3">
|
||||
IAM 员工:{{ status.employee.displayName }}({{ status.employee.username }})
|
||||
</p>
|
||||
<p class="my-3 text-gray-500">
|
||||
关联只确认同一人的身份,不会复制业务角色或自动授予其他平台权限。
|
||||
</p>
|
||||
<el-alert
|
||||
v-if="!linked && status.protected_account"
|
||||
class="mb-4"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
title="此账号属于敏感账号,请由本地管理员在 IAM 关联管理发起单人中央复核,不使用个人自助绑定。"
|
||||
/>
|
||||
<div class="flex flex-wrap gap-3">
|
||||
<el-button @click="reauthVisible = true">验证当前身份</el-button>
|
||||
<el-button @click="wecomRelogin">企业微信重新登录</el-button>
|
||||
<el-button
|
||||
v-if="!linked && !status.protected_account && status.management_enabled"
|
||||
type="primary"
|
||||
:loading="busy"
|
||||
@click="navigate('/self-link/start')"
|
||||
>关联已有 IAM 账号</el-button
|
||||
>
|
||||
<el-button
|
||||
v-if="linked && status.management_enabled && status.employee?.passwordSetupPending"
|
||||
type="primary"
|
||||
:loading="busy"
|
||||
@click="navigate('/password-setup')"
|
||||
>设置 IAM 登录密码</el-button
|
||||
>
|
||||
<el-button v-if="linked && status.launch_enabled" :loading="busy" @click="launch">进入甄美 ERP ↗</el-button>
|
||||
</div>
|
||||
<el-dialog
|
||||
v-model="reauthVisible"
|
||||
title="验证当前 ZYT 身份"
|
||||
width="420px"
|
||||
:close-on-click-modal="false"
|
||||
>
|
||||
<el-form @submit.prevent="reauth"
|
||||
><el-form-item label="当前密码"
|
||||
><el-input
|
||||
v-model="password"
|
||||
type="password"
|
||||
show-password
|
||||
autocomplete="current-password"
|
||||
@keyup.enter="reauth" /></el-form-item
|
||||
></el-form>
|
||||
<p class="text-gray-500">
|
||||
仅验证当前账号,验证有效期 5 分钟。密码不会被保存或传给 IAM。
|
||||
</p>
|
||||
<template #footer
|
||||
><el-button @click="cancelReauth">取消</el-button
|
||||
><el-button type="primary" :loading="busy" @click="reauth"
|
||||
>验证</el-button
|
||||
></template
|
||||
>
|
||||
</el-dialog>
|
||||
</el-card>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { iamGet, iamPost, identityError } from '@/api/iam-v2'
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
const status = ref<any>({ enabled: false }),
|
||||
error = ref(''),
|
||||
busy = ref(false),
|
||||
reauthVisible = ref(false),
|
||||
password = ref('')
|
||||
const linked = computed(() => status.value?.binding?.state === 'verified')
|
||||
async function refresh() {
|
||||
try {
|
||||
status.value = await iamGet('/status')
|
||||
error.value = ''
|
||||
} catch (e) {
|
||||
error.value = identityError(e)
|
||||
}
|
||||
}
|
||||
function cancelReauth() {
|
||||
reauthVisible.value = false
|
||||
password.value = ''
|
||||
}
|
||||
async function reauth() {
|
||||
busy.value = true
|
||||
try {
|
||||
await iamPost('/reauth', { password: password.value })
|
||||
reauthVisible.value = false
|
||||
await refresh()
|
||||
} catch (e) {
|
||||
error.value = identityError(e)
|
||||
} finally {
|
||||
password.value = ''
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
async function navigate(path: string) {
|
||||
busy.value = true
|
||||
try {
|
||||
const r = await iamPost(path)
|
||||
window.location.assign(r.url)
|
||||
} catch (e) {
|
||||
error.value = identityError(e)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
async function launch() {
|
||||
const tab = window.open('about:blank', '_blank')
|
||||
if (tab) tab.opener = null
|
||||
busy.value = true
|
||||
try {
|
||||
const r = await iamPost('/launch/start')
|
||||
if (tab) tab.location.href = r.url
|
||||
else error.value = '请允许浏览器打开新标签页后再试。'
|
||||
} catch (e) {
|
||||
tab?.close()
|
||||
error.value = identityError(e)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
async function wecomRelogin() {
|
||||
await useUserStore().logout()
|
||||
}
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
@@ -0,0 +1,93 @@
|
||||
<template>
|
||||
<main class="min-h-screen flex items-center justify-center bg-page p-6">
|
||||
<el-card class="w-full max-w-xl" shadow="never">
|
||||
<h1 class="text-xl font-semibold mb-4">统一身份进入甄养堂</h1>
|
||||
<p v-if="busy" class="text-gray-500">正在核验同一身份,请稍候…</p>
|
||||
<el-alert v-if="error" :title="error" type="warning" :closable="false" show-icon />
|
||||
<p class="text-gray-500 my-4">
|
||||
已有 ZYT 账号将进行一致性检查。系统不会自动替换当前已登录的人。
|
||||
</p>
|
||||
<div v-if="error" class="flex flex-wrap gap-3">
|
||||
<el-button v-if="restartUrl" type="primary" @click="back"
|
||||
>返回 IAM 重新发起</el-button
|
||||
>
|
||||
<el-button v-if="restartUrl" :loading="busy" @click="switchAccount"
|
||||
>退出当前 ZYT 身份并返回 IAM</el-button
|
||||
>
|
||||
<router-link to="/login"><el-button>使用原登录方式</el-button></router-link>
|
||||
</div>
|
||||
</el-card>
|
||||
</main>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { iamGet, iamPost, identityError } from '@/api/iam-v2'
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
import { clearAuthInfo } from '@/utils/auth'
|
||||
import feedback from '@/utils/feedback'
|
||||
const route = useRoute(),
|
||||
router = useRouter(),
|
||||
store = useUserStore()
|
||||
const busy = ref(true),
|
||||
error = ref(''),
|
||||
restartUrl = ref('')
|
||||
let handled = false
|
||||
const text = (v: unknown) => (typeof v === 'string' ? v : '')
|
||||
function back() {
|
||||
if (restartUrl.value) window.location.assign(restartUrl.value)
|
||||
}
|
||||
async function switchAccount() {
|
||||
await feedback.confirm(
|
||||
'确认退出当前浏览器的 ZYT 身份?其他平台和其他浏览器不受影响。请回 IAM 重新发起。'
|
||||
)
|
||||
busy.value = true
|
||||
try {
|
||||
await iamPost('/launch/reset')
|
||||
clearAuthInfo()
|
||||
back()
|
||||
} catch (e) {
|
||||
error.value = identityError(e)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
onMounted(async () => {
|
||||
if (handled) return
|
||||
handled = true
|
||||
const ticket = text(route.query.ticket),
|
||||
source = text(route.query.source),
|
||||
intent = text(route.query.intent),
|
||||
issue = text(route.query.iam_error)
|
||||
// Strip one-use material before any network/async work; never retain it in history.
|
||||
window.history.replaceState(window.history.state, '', window.location.pathname)
|
||||
try {
|
||||
const config = await iamGet('/launch/config', { source })
|
||||
restartUrl.value = config.restart_url || ''
|
||||
if (!config.enabled) throw { error: { code: 'FEATURE_DISABLED' } }
|
||||
if (issue) throw { error: { code: issue } }
|
||||
if (ticket) {
|
||||
const result = await store.iamLaunchLogin(ticket)
|
||||
await router.replace(
|
||||
result.is_paw === 0
|
||||
? '/change-password'
|
||||
: result.need_bind_work_wechat
|
||||
? '/bind-work-wechat'
|
||||
: '/'
|
||||
)
|
||||
} else {
|
||||
if (
|
||||
!['iam-admin', 'iam-portal'].includes(source) ||
|
||||
!/^[A-Za-z0-9_-]{32,256}$/.test(intent)
|
||||
)
|
||||
throw { error: { code: 'INVALID_REQUEST' } }
|
||||
const result = await iamPost('/launch/prepare', { source, intent })
|
||||
window.location.assign(result.url)
|
||||
}
|
||||
} catch (e) {
|
||||
error.value = identityError(e)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,723 @@
|
||||
<template>
|
||||
<div class="identity-management">
|
||||
<el-card shadow="never">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<div>
|
||||
<h2 class="text-xl font-semibold">IAM 关联管理</h2>
|
||||
<p class="text-gray-500 mt-2">
|
||||
保留历史本地账号、业务角色与数据;只管理统一身份关联。
|
||||
</p>
|
||||
</div>
|
||||
<el-button @click="reauthVisible = true">验证管理员身份</el-button>
|
||||
</div>
|
||||
<el-alert
|
||||
v-if="error"
|
||||
:title="error"
|
||||
type="warning"
|
||||
show-icon
|
||||
:closable="false"
|
||||
class="mb-4"
|
||||
/>
|
||||
<el-alert
|
||||
v-if="!enabled"
|
||||
title="IAM v2 尚未启用,原有业务与登录方式保持不变。"
|
||||
type="info"
|
||||
:closable="false"
|
||||
/>
|
||||
<el-form v-if="enabled" inline class="mt-4" @submit.prevent="reload">
|
||||
<el-form-item label="本地账号"
|
||||
><el-input
|
||||
v-model="query.q"
|
||||
placeholder="账号或姓名"
|
||||
clearable
|
||||
@keyup.enter="reload"
|
||||
/></el-form-item>
|
||||
<el-form-item label="关联状态"
|
||||
><el-select v-model="query.state" clearable class="!w-40"
|
||||
><el-option
|
||||
v-for="(label, key) in states"
|
||||
:key="key"
|
||||
:label="label"
|
||||
:value="key" /></el-select
|
||||
></el-form-item>
|
||||
<el-form-item
|
||||
><el-button type="primary" @click="reload">查询</el-button
|
||||
><el-button :disabled="!can('batch')" @click="batchVisible = true"
|
||||
>批量预检</el-button
|
||||
></el-form-item
|
||||
>
|
||||
</el-form>
|
||||
<el-table v-if="enabled" v-loading="loading" :data="rows" row-key="id">
|
||||
<el-table-column prop="id" label="ID" width="70" />
|
||||
<el-table-column prop="account" label="本地账号" min-width="140" />
|
||||
<el-table-column prop="name" label="姓名" min-width="120" />
|
||||
<el-table-column label="部门" min-width="140" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ departmentText(row) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="本地状态" width="110"
|
||||
><template #default="{ row }"
|
||||
><el-tag :type="isLocalDisabled(row) ? 'danger' : 'success'">{{
|
||||
isLocalDisabled(row) ? '停用' : row.root ? '敏感账号' : '正常'
|
||||
}}</el-tag></template
|
||||
></el-table-column
|
||||
>
|
||||
<el-table-column label="IAM 员工" min-width="180"
|
||||
><template #default="{ row }"
|
||||
>{{ row.iam.employee?.displayName || '—' }}
|
||||
<div class="text-xs text-gray-500">
|
||||
{{ row.iam.employee?.username }}
|
||||
</div></template
|
||||
></el-table-column
|
||||
>
|
||||
<el-table-column label="关联状态" width="130"
|
||||
><template #default="{ row }"
|
||||
><el-tag :type="row.iam.state === 'verified' ? 'success' : 'info'">{{
|
||||
states[row.iam.state] || row.iam.state
|
||||
}}</el-tag>
|
||||
<div class="text-xs">
|
||||
版本 {{ row.iam.binding?.version ?? '—' }}
|
||||
</div></template
|
||||
></el-table-column
|
||||
>
|
||||
<el-table-column label="应用访问状态" width="130">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="applicationAccess(row).type">{{
|
||||
applicationAccess(row).text
|
||||
}}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="最近校验时间" min-width="190">
|
||||
<template #default="{ row }">{{ checkedAtText(row.iam?.checked_at) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" min-width="210"
|
||||
><template #default="{ row }">
|
||||
<el-button
|
||||
link
|
||||
type="primary"
|
||||
:disabled="
|
||||
isLocalDisabled(row) ||
|
||||
(!!row.root && !reviewAllowed) ||
|
||||
row.iam.state === 'verified' ||
|
||||
!can(row.iam.state === 'revoked' ? 'rebind' : 'bind')
|
||||
"
|
||||
@click="open(row, 'bind')"
|
||||
>关联</el-button
|
||||
>
|
||||
<el-button
|
||||
link
|
||||
type="primary"
|
||||
:disabled="
|
||||
isLocalDisabled(row) ||
|
||||
(!!row.root && !reviewAllowed) ||
|
||||
row.iam.state === 'verified' ||
|
||||
!can('create') ||
|
||||
(row.iam.state === 'revoked' && !can('rebind'))
|
||||
"
|
||||
@click="open(row, 'create_and_bind')"
|
||||
>创建并关联</el-button
|
||||
>
|
||||
<el-dropdown @command="(kind: string) => more(row, kind)"
|
||||
><el-button link>更多</el-button
|
||||
><template #dropdown
|
||||
><el-dropdown-menu>
|
||||
<el-dropdown-item
|
||||
command="rebind"
|
||||
:disabled="
|
||||
isLocalDisabled(row) ||
|
||||
(!!row.root && !reviewAllowed) ||
|
||||
!can('rebind')
|
||||
"
|
||||
>换绑</el-dropdown-item
|
||||
>
|
||||
<el-dropdown-item
|
||||
command="unbind"
|
||||
:disabled="
|
||||
isLocalDisabled(row) ||
|
||||
(!!row.root && !reviewAllowed) ||
|
||||
!can('unbind')
|
||||
"
|
||||
>解绑</el-dropdown-item
|
||||
>
|
||||
<el-dropdown-item command="audit">审计记录</el-dropdown-item>
|
||||
</el-dropdown-menu></template
|
||||
></el-dropdown
|
||||
>
|
||||
<div v-if="isLocalDisabled(row)" class="text-xs text-gray-500 mt-1">
|
||||
本地账号已停用,关联操作不可用;审计记录仍可查看。
|
||||
</div>
|
||||
</template></el-table-column
|
||||
>
|
||||
</el-table>
|
||||
<el-pagination
|
||||
v-if="enabled"
|
||||
class="mt-4 justify-end"
|
||||
layout="total, prev, pager, next"
|
||||
:total="total"
|
||||
v-model:current-page="query.page"
|
||||
:page-size="20"
|
||||
@current-change="load"
|
||||
/>
|
||||
</el-card>
|
||||
<el-drawer
|
||||
v-model="drawer"
|
||||
:title="titles[operation.kind]"
|
||||
size="min(680px, 94vw)"
|
||||
:close-on-click-modal="false"
|
||||
>
|
||||
<el-steps :active="step" finish-status="success" align-center
|
||||
><el-step title="核对本地账号" /><el-step title="核对 IAM 身份" /><el-step
|
||||
title="确认变更"
|
||||
/></el-steps>
|
||||
<section class="mt-8">
|
||||
<template v-if="step === 0"
|
||||
><h3 class="text-lg mb-4">{{ selected?.name }} · {{ selected?.account }}</h3>
|
||||
<p>本地 ID:{{ selected?.id }}</p>
|
||||
<p class="my-3">
|
||||
当前关联:{{ selected?.iam.employee?.displayName || '未关联' }}(版本
|
||||
{{ selected?.iam.binding?.version ?? '无' }})
|
||||
</p>
|
||||
<el-alert
|
||||
title="本次操作不改变本地密码、角色、部门或历史数据;人员同名不代表同一身份。"
|
||||
type="info"
|
||||
:closable="false"
|
||||
/></template>
|
||||
<template v-if="step === 1">
|
||||
<el-form v-if="operation.kind === 'create_and_bind'" label-position="top"
|
||||
><el-form-item label="IAM 登录名"
|
||||
><el-input
|
||||
v-model="newEmployee.username"
|
||||
maxlength="64" /></el-form-item
|
||||
><el-form-item label="姓名"
|
||||
><el-input
|
||||
v-model="newEmployee.display_name"
|
||||
maxlength="100" /></el-form-item
|
||||
><el-form-item label="邮箱(可选)"
|
||||
><el-input v-model="newEmployee.email" /></el-form-item
|
||||
><el-alert
|
||||
title="使用正常员工开户流程,默认应用授权遵循 IAM 当前策略。不会生成共享初始密码;本人首次使用需设置 IAM 密码。"
|
||||
type="info"
|
||||
:closable="false"
|
||||
/></el-form>
|
||||
<template v-else-if="operation.kind !== 'unbind'"
|
||||
><el-input
|
||||
v-model="identityQuery"
|
||||
placeholder="搜索 IAM 登录名或姓名"
|
||||
@keyup.enter="searchIdentities"
|
||||
><template #append
|
||||
><el-button @click="searchIdentities">搜索</el-button></template
|
||||
></el-input
|
||||
><el-table
|
||||
class="mt-4"
|
||||
:data="identities"
|
||||
highlight-current-row
|
||||
@current-change="choose"
|
||||
><el-table-column label="选择" width="70"
|
||||
><template #default="{ row }"
|
||||
><el-radio
|
||||
:model-value="operation.employee_id"
|
||||
:value="row.id"
|
||||
@change="choose(row)"
|
||||
><span /></el-radio></template></el-table-column
|
||||
><el-table-column prop="username" label="IAM 登录名" /><el-table-column
|
||||
prop="displayName"
|
||||
label="姓名" /><el-table-column
|
||||
prop="status"
|
||||
label="状态" /></el-table
|
||||
></template>
|
||||
<el-alert
|
||||
v-else
|
||||
title="解绑后跨平台快捷登录停止,相关来源/业务会话撤销,历史数据和本地账号保留。自动开户不会恢复已撤销关联。"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
/>
|
||||
</template>
|
||||
<template v-if="step === 2"
|
||||
><el-descriptions :column="1" border
|
||||
><el-descriptions-item label="本地账号"
|
||||
>{{ selected?.account }} #{{ selected?.id }}</el-descriptions-item
|
||||
><el-descriptions-item label="变更类型">{{
|
||||
titles[operation.kind]
|
||||
}}</el-descriptions-item
|
||||
><el-descriptions-item label="原 IAM 员工">{{
|
||||
selected?.iam.employee?.username || '无'
|
||||
}}</el-descriptions-item
|
||||
><el-descriptions-item label="目标 IAM 员工">{{
|
||||
operation.kind === 'unbind'
|
||||
? '解除关联'
|
||||
: operation.kind === 'create_and_bind'
|
||||
? newEmployee.username
|
||||
: chosenIdentity?.username
|
||||
}}</el-descriptions-item
|
||||
><el-descriptions-item label="预期版本">{{
|
||||
operation.expected_version ?? '首次关联'
|
||||
}}</el-descriptions-item></el-descriptions
|
||||
><el-input
|
||||
class="mt-4"
|
||||
v-model="operation.reason"
|
||||
:disabled="!!submittedPayload"
|
||||
type="textarea"
|
||||
:rows="3"
|
||||
maxlength="500"
|
||||
placeholder="必填:核对方式和变更原因,将写入审计记录"
|
||||
/><el-checkbox class="mt-4" v-model="confirmed"
|
||||
>我已核对本地账号与 IAM 员工为同一人,理解会话撤销影响</el-checkbox
|
||||
></template
|
||||
>
|
||||
<el-alert
|
||||
v-if="drawerError"
|
||||
class="mt-4"
|
||||
:title="drawerError"
|
||||
type="error"
|
||||
:closable="false"
|
||||
/>
|
||||
<el-alert
|
||||
v-if="result"
|
||||
class="mt-4"
|
||||
:title="`操作 ${result.id}:${result.status}${result.error?.code ? ' · ' + identityError(result) : ''}`"
|
||||
:type="result.status === 'succeeded' ? 'success' : 'warning'"
|
||||
:closable="false"
|
||||
/>
|
||||
<div v-if="result?.reviewUrl" class="mt-4">
|
||||
<a
|
||||
:href="result.reviewUrl"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="text-primary"
|
||||
>中央复核 ↗</a
|
||||
>
|
||||
<p class="text-gray-500 mt-2">
|
||||
由中央管理员完成近期验证并批准后,重试原操作;原目标、版本和原因保持不变。
|
||||
</p>
|
||||
</div>
|
||||
<el-button
|
||||
v-if="result && result.status !== 'succeeded'"
|
||||
class="mt-4"
|
||||
@click="refreshOperation"
|
||||
>查询同一操作状态</el-button
|
||||
>
|
||||
</section>
|
||||
<template #footer
|
||||
><el-button @click="drawer = false">关闭</el-button
|
||||
><el-button v-if="step > 0" :disabled="!!submittedPayload" @click="step--"
|
||||
>上一步</el-button
|
||||
><el-button
|
||||
v-if="step < 2"
|
||||
type="primary"
|
||||
:disabled="step === 1 && !validIdentity"
|
||||
@click="step++"
|
||||
>下一步</el-button
|
||||
><el-button
|
||||
v-else
|
||||
type="primary"
|
||||
:loading="busy"
|
||||
:disabled="
|
||||
isLocalDisabled(selected) ||
|
||||
!confirmed ||
|
||||
!operation.reason.trim() ||
|
||||
result?.status === 'succeeded'
|
||||
"
|
||||
@click="submit"
|
||||
>{{
|
||||
result?.reviewUrl
|
||||
? '完成中央复核后重试原操作'
|
||||
: '确认' + titles[operation.kind]
|
||||
}}</el-button
|
||||
></template
|
||||
>
|
||||
</el-drawer>
|
||||
<el-dialog v-model="reauthVisible" title="近期管理员身份验证" width="420px"
|
||||
><el-input
|
||||
v-model="password"
|
||||
type="password"
|
||||
show-password
|
||||
placeholder="当前 ZYT 账号密码"
|
||||
autocomplete="current-password"
|
||||
@keyup.enter="reauth"
|
||||
/>
|
||||
<p class="mt-4 text-gray-500">
|
||||
有效期 5 分钟。敏感目标还需中央管理员审核,此处不会越过审核。
|
||||
</p>
|
||||
<template #footer
|
||||
><el-button type="primary" :loading="busy" @click="reauth"
|
||||
>验证</el-button
|
||||
></template
|
||||
></el-dialog
|
||||
>
|
||||
<el-drawer v-model="auditVisible" title="关联审计" size="min(760px, 94vw)"
|
||||
><el-table :data="audits"
|
||||
><el-table-column prop="occurredAt" label="时间" min-width="170" /><el-table-column
|
||||
prop="action"
|
||||
label="操作" /><el-table-column label="操作人"
|
||||
><template #default="{ row }">{{
|
||||
typeof row.actor === 'string' ? row.actor : JSON.stringify(row.actor)
|
||||
}}</template></el-table-column
|
||||
><el-table-column prop="reason" label="原因" /></el-table
|
||||
></el-drawer>
|
||||
<el-dialog
|
||||
v-model="batchVisible"
|
||||
title="批量预检与确认"
|
||||
width="min(920px, 94vw)"
|
||||
:close-on-click-modal="false"
|
||||
>
|
||||
<el-alert
|
||||
title="先预检,不会创建账号或修改绑定。仅选择 ready 项后显式确认;敏感账号与冲突项跳过。每批最多 100 条。"
|
||||
type="info"
|
||||
:closable="false"
|
||||
/>
|
||||
<el-input
|
||||
v-model="batchText"
|
||||
class="mt-4"
|
||||
type="textarea"
|
||||
:rows="7"
|
||||
placeholder='[{"kind":"bind","user_id":42,"employee_id":"员工ID","reason":"核对后历史关联"}]'
|
||||
/>
|
||||
<el-button class="mt-4" :loading="busy" @click="preflight">只读预检</el-button>
|
||||
<el-table
|
||||
v-if="preview"
|
||||
class="mt-4"
|
||||
:data="preview.items"
|
||||
@selection-change="(items: any[]) => (selectedIndexes = items.map((x) => x.index))"
|
||||
><el-table-column
|
||||
type="selection"
|
||||
:selectable="(row: any) => row.status === 'ready'" /><el-table-column
|
||||
prop="externalAccountId"
|
||||
label="本地 ID" /><el-table-column prop="status" label="状态" /><el-table-column
|
||||
prop="message"
|
||||
label="结果"
|
||||
/></el-table>
|
||||
<el-checkbox v-if="preview" v-model="batchConfirmed" class="mt-4"
|
||||
>确认仅执行已选择项目({{ selectedIndexes.length }} 条)</el-checkbox
|
||||
>
|
||||
<section v-if="job" class="mt-4">
|
||||
<h3>任务 {{ job.id }} · {{ job.status }}</h3>
|
||||
<el-table :data="job.items"
|
||||
><el-table-column prop="externalAccountId" label="本地账号" /><el-table-column
|
||||
prop="status"
|
||||
label="状态"
|
||||
/><el-table-column label="结果"
|
||||
><template #default="{ row }">{{
|
||||
row.error?.message || row.error?.code || '—'
|
||||
}}</template></el-table-column
|
||||
></el-table
|
||||
><el-button @click="refreshJob">刷新任务</el-button
|
||||
><el-button
|
||||
:disabled="
|
||||
!job.items?.some((x: any) => ['failed', 'pending'].includes(x.status))
|
||||
"
|
||||
@click="retryJob"
|
||||
>只重试失败/待处理项</el-button
|
||||
>
|
||||
</section>
|
||||
<template #footer
|
||||
><el-button @click="batchVisible = false">关闭</el-button
|
||||
><el-button
|
||||
type="primary"
|
||||
:loading="busy"
|
||||
:disabled="
|
||||
!preview?.previewId || !batchConfirmed || !selectedIndexes.length || !!job
|
||||
"
|
||||
@click="submitBatch"
|
||||
>确认执行</el-button
|
||||
></template
|
||||
>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { iamGet, iamPost, identityError, type IdentityOperation } from '@/api/iam-v2'
|
||||
const states: Record<string, string> = {
|
||||
verified: '已关联',
|
||||
unlinked: '未关联',
|
||||
revoked: '已撤销',
|
||||
pending: '待确认',
|
||||
conflict: '冲突',
|
||||
unknown: '待核验'
|
||||
}
|
||||
const titles: Record<string, string> = {
|
||||
bind: '关联',
|
||||
create_and_bind: '创建并关联',
|
||||
rebind: '换绑',
|
||||
unbind: '解绑',
|
||||
reconcile: '对账'
|
||||
}
|
||||
const enabled = ref(false),
|
||||
reviewAllowed = ref(false),
|
||||
managementEnabled = ref(false),
|
||||
caps = ref<string[]>([]),
|
||||
rows = ref<any[]>([]),
|
||||
total = ref(0),
|
||||
loading = ref(false),
|
||||
busy = ref(false),
|
||||
error = ref('')
|
||||
const query = reactive({ q: '', state: '', page: 1, pageSize: 20 })
|
||||
const drawer = ref(false),
|
||||
step = ref(0),
|
||||
selected = ref<any>(null),
|
||||
identities = ref<any[]>([]),
|
||||
identityQuery = ref(''),
|
||||
chosenIdentity = ref<any>(null),
|
||||
confirmed = ref(false),
|
||||
drawerError = ref(''),
|
||||
result = ref<any>(null)
|
||||
const submittedPayload = ref<Record<string, unknown> | null>(null)
|
||||
const operation = reactive<IdentityOperation>({ kind: 'bind', user_id: 0, reason: '' }),
|
||||
newEmployee = reactive({ username: '', display_name: '', email: '' })
|
||||
let operationKey = crypto.randomUUID(),
|
||||
batchKey = crypto.randomUUID()
|
||||
const reauthVisible = ref(false),
|
||||
password = ref(''),
|
||||
auditVisible = ref(false),
|
||||
audits = ref<any[]>([])
|
||||
const batchVisible = ref(false),
|
||||
batchText = ref(''),
|
||||
preview = ref<any>(null),
|
||||
selectedIndexes = ref<number[]>([]),
|
||||
batchConfirmed = ref(false),
|
||||
job = ref<any>(null)
|
||||
const can = (c: string) => caps.value.includes(c) && (c === 'read' || managementEnabled.value)
|
||||
const validIdentity = computed(
|
||||
() =>
|
||||
operation.kind === 'unbind' ||
|
||||
(operation.kind === 'create_and_bind'
|
||||
? !!newEmployee.username.trim() && !!newEmployee.display_name.trim()
|
||||
: !!operation.employee_id)
|
||||
)
|
||||
function isLocalDisabled(row: any): boolean {
|
||||
return row?.disable === true || row?.disable === 1 || row?.disable === '1'
|
||||
}
|
||||
function departmentText(row: any): string {
|
||||
if (!Array.isArray(row?.dept_names)) return '未知'
|
||||
if (row.dept_names.length === 0) return '未分配'
|
||||
if (!row.dept_names.every((name: unknown) => typeof name === 'string' && name.trim()))
|
||||
return '未知'
|
||||
return row.dept_names.map((name: string) => name.trim()).join('、')
|
||||
}
|
||||
function applicationAccess(row: any): {
|
||||
text: string
|
||||
type: 'success' | 'warning' | 'info' | 'danger'
|
||||
} {
|
||||
const iam = row?.iam
|
||||
const reason = iam?.access?.reason
|
||||
if (['SERVICE_UNAVAILABLE', 'STATUS_UNAVAILABLE'].includes(reason)) {
|
||||
return { text: '服务异常', type: 'warning' }
|
||||
}
|
||||
if (reason === 'NOT_AUTHORIZED') return { text: '未授权', type: 'warning' }
|
||||
if (reason === 'ACCOUNT_DISABLED') return { text: 'IAM账号停用', type: 'danger' }
|
||||
if (reason === 'BINDING_CONFLICT') return { text: '关联冲突', type: 'warning' }
|
||||
if (reason === 'ACCOUNT_MISMATCH') return { text: '身份不匹配', type: 'warning' }
|
||||
if (
|
||||
['unlinked', 'revoked'].includes(iam?.state) ||
|
||||
['NOT_LINKED', 'LOCAL_ACCOUNT_LINK_REQUIRED', 'BINDING_REVOKED'].includes(reason)
|
||||
) {
|
||||
return { text: '未关联', type: 'info' }
|
||||
}
|
||||
if (iam?.access?.allowed === false) return { text: '未授权', type: 'warning' }
|
||||
if (iam?.state === 'verified' && iam?.access?.allowed === true) {
|
||||
return { text: '已授权', type: 'success' }
|
||||
}
|
||||
return { text: '未知', type: 'info' }
|
||||
}
|
||||
function checkedAtText(value: unknown): string {
|
||||
if (value == null || value === '' || value === 0 || value === '0') return '未校验'
|
||||
const seconds = typeof value === 'number' || typeof value === 'string' ? Number(value) : NaN
|
||||
if (!Number.isInteger(seconds) || seconds <= 0 || seconds > 253402300799) return '未知'
|
||||
return new Date(seconds * 1000).toLocaleString('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: false
|
||||
})
|
||||
}
|
||||
async function load() {
|
||||
loading.value = true
|
||||
try {
|
||||
const r = await iamGet('/accounts', query)
|
||||
rows.value = r.items
|
||||
total.value = r.total
|
||||
error.value = ''
|
||||
} catch (e) {
|
||||
error.value = identityError(e)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
function reload() {
|
||||
query.page = 1
|
||||
void load()
|
||||
}
|
||||
function open(row: any, kind: IdentityOperation['kind']) {
|
||||
if (isLocalDisabled(row)) {
|
||||
ElMessage.warning('本地账号已停用,请先启用账号后再维护关联。')
|
||||
return
|
||||
}
|
||||
if (kind === 'bind' && row.iam.state === 'revoked') kind = 'rebind'
|
||||
selected.value = row
|
||||
Object.assign(operation, {
|
||||
kind,
|
||||
user_id: row.id,
|
||||
employee_id: undefined,
|
||||
expected_version: row.iam.binding?.version,
|
||||
reason: ''
|
||||
})
|
||||
Object.assign(newEmployee, { username: '', display_name: row.name, email: '' })
|
||||
drawer.value = true
|
||||
step.value = 0
|
||||
confirmed.value = false
|
||||
drawerError.value = ''
|
||||
result.value = null
|
||||
submittedPayload.value = null
|
||||
chosenIdentity.value = null
|
||||
identities.value = []
|
||||
operationKey = crypto.randomUUID()
|
||||
}
|
||||
async function more(row: any, kind: string) {
|
||||
if (kind === 'audit') {
|
||||
try {
|
||||
audits.value = (await iamGet(`/accounts/${row.id}/audit`)).items
|
||||
auditVisible.value = true
|
||||
} catch (e) {
|
||||
error.value = identityError(e)
|
||||
}
|
||||
} else open(row, kind as IdentityOperation['kind'])
|
||||
}
|
||||
async function searchIdentities() {
|
||||
try {
|
||||
identities.value = (
|
||||
await iamGet('/identities', { q: identityQuery.value, page: 1, pageSize: 20 })
|
||||
).items
|
||||
} catch (e) {
|
||||
drawerError.value = identityError(e)
|
||||
}
|
||||
}
|
||||
function choose(row: any) {
|
||||
if (row?.status === 'active') {
|
||||
chosenIdentity.value = row
|
||||
operation.employee_id = row.id
|
||||
}
|
||||
}
|
||||
async function submit() {
|
||||
if (isLocalDisabled(selected.value)) {
|
||||
drawerError.value = '本地账号已停用,请先启用账号后再维护关联。'
|
||||
return
|
||||
}
|
||||
busy.value = true
|
||||
try {
|
||||
if (!submittedPayload.value) {
|
||||
submittedPayload.value = JSON.parse(
|
||||
JSON.stringify({
|
||||
...operation,
|
||||
...(operation.kind === 'create_and_bind'
|
||||
? { new_employee: { ...newEmployee } }
|
||||
: {})
|
||||
})
|
||||
)
|
||||
}
|
||||
result.value = await iamPost('/operations', submittedPayload.value!, operationKey)
|
||||
drawerError.value = ''
|
||||
await load()
|
||||
} catch (e) {
|
||||
drawerError.value = identityError(e)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
async function refreshOperation() {
|
||||
try {
|
||||
result.value = await iamGet(`/operations/${result.value.id}`)
|
||||
await load()
|
||||
} catch (e) {
|
||||
drawerError.value = identityError(e)
|
||||
}
|
||||
}
|
||||
async function reauth() {
|
||||
busy.value = true
|
||||
try {
|
||||
await iamPost('/reauth', { password: password.value })
|
||||
reauthVisible.value = false
|
||||
ElMessage.success('身份已验证,有效期 5 分钟')
|
||||
await load()
|
||||
} catch (e) {
|
||||
error.value = identityError(e)
|
||||
} finally {
|
||||
password.value = ''
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
async function preflight() {
|
||||
busy.value = true
|
||||
preview.value = null
|
||||
job.value = null
|
||||
batchConfirmed.value = false
|
||||
selectedIndexes.value = []
|
||||
try {
|
||||
const items = JSON.parse(batchText.value)
|
||||
if (!Array.isArray(items) || items.length < 1 || items.length > 100) throw Error('input')
|
||||
preview.value = await iamPost('/batch/preflight', { items })
|
||||
batchKey = crypto.randomUUID()
|
||||
} catch (e) {
|
||||
error.value = e instanceof SyntaxError ? '批量输入必须是 JSON 数组。' : identityError(e)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
async function submitBatch() {
|
||||
busy.value = true
|
||||
try {
|
||||
job.value = await iamPost(
|
||||
'/batch',
|
||||
{ preview_id: preview.value.previewId, indexes: selectedIndexes.value },
|
||||
batchKey
|
||||
)
|
||||
await load()
|
||||
} catch (e) {
|
||||
error.value = identityError(e)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
async function refreshJob() {
|
||||
try {
|
||||
job.value = await iamGet(`/jobs/${job.value.id}`)
|
||||
await load()
|
||||
} catch (e) {
|
||||
error.value = identityError(e)
|
||||
}
|
||||
}
|
||||
async function retryJob() {
|
||||
busy.value = true
|
||||
try {
|
||||
job.value = await iamPost(`/jobs/${job.value.id}/retry`)
|
||||
await load()
|
||||
} catch (e) {
|
||||
error.value = identityError(e)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const s = await iamGet('/status')
|
||||
enabled.value = s.enabled
|
||||
caps.value = s.management_capabilities || []
|
||||
reviewAllowed.value = s.protected_review_operator === true
|
||||
managementEnabled.value = s.management_enabled === true
|
||||
if (enabled.value && can('read')) await load()
|
||||
} catch (e) {
|
||||
error.value = identityError(e)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
<style scoped>
|
||||
.identity-management p {
|
||||
line-height: 1.7;
|
||||
}
|
||||
.identity-management :deep(.el-steps) {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
</style>
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\controller;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
use app\adminapi\service\iam\IamOidcClient;
|
||||
use app\adminapi\service\iam\v2\{IamV2Client, IamV2Source, IamV2Manager, IamV2Flow, IamV2Target};
|
||||
|
||||
/** Every endpoint authorizes itself. Never relies on legacy unregistered-route allow rules. */
|
||||
final class IamV2Controller extends BaseAdminController
|
||||
{
|
||||
public array $notNeedLogin = ['status', 'introspect', 'checkSession', 'revocation', 'launchContinue', 'selfCallback', 'passwordContinue', 'targetConfig', 'targetPrepare', 'targetCallback', 'targetExchange', 'targetReset'];
|
||||
private function invokeV2(callable $fn)
|
||||
{
|
||||
try {
|
||||
if (!IamV2Client::enabled()) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
$action = strtolower((string) $this->request->action());
|
||||
if (in_array($action, ['operation','preflight','batch','retry','selfstart','passwordsetup'], true) && !IamV2Client::feature('management')) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
if (in_array($action, ['launchstart','targetprepare','targetexchange'], true) && !IamV2Client::feature('launch')) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
$reads = ['status','accounts','identities','operationresult','audit','job','targetconfig'];
|
||||
$read = in_array(strtolower((string) $this->request->action()), $reads, true);
|
||||
if (($read && !$this->request->isGet()) || (!$read && !$this->request->isPost())) { throw new RuntimeException('METHOD_NOT_ALLOWED'); }
|
||||
return $this->data($fn())->header(['Cache-Control' => 'no-store', 'Referrer-Policy' => 'no-referrer']);
|
||||
} catch (\Throwable $e) {
|
||||
$code = preg_match('/^[A-Z_]{3,64}$/D', $e->getMessage()) ? $e->getMessage() : 'SERVICE_UNAVAILABLE';
|
||||
return $this->fail($code, ['error' => ['code' => $code]], 0, 0)->header(['Cache-Control' => 'no-store']);
|
||||
}
|
||||
}
|
||||
private function session(bool $recent = false): array
|
||||
{
|
||||
if (!$this->request->isGet()) {
|
||||
$expected = IamV2Client::origin((string) Config::get('iam.public_url'));
|
||||
if ((string) $this->request->header('origin') !== $expected) { throw new RuntimeException('INVALID_ORIGIN'); }
|
||||
}
|
||||
return IamV2Source::current((string) $this->request->header('token', ''), $recent);
|
||||
}
|
||||
private function input(): array { return (array) $this->request->post(); }
|
||||
private function requestId(): string
|
||||
{
|
||||
$key = (string) $this->request->header('idempotency-key', '');
|
||||
if (!preg_match('/^[A-Za-z0-9_-]{16,128}$/D', $key)) { throw new RuntimeException('INVALID_IDEMPOTENCY_KEY'); }
|
||||
return 'zyt-' . $key;
|
||||
}
|
||||
private function serviceAuth(): void
|
||||
{
|
||||
$expected = (string) Config::get('iam.v2_introspection_token', '');
|
||||
if (!$this->request->isPost() || strlen($expected) < 32 || !hash_equals('Bearer ' . $expected, (string) $this->request->header('authorization', ''))) { throw new RuntimeException('FORBIDDEN'); }
|
||||
}
|
||||
public function status()
|
||||
{
|
||||
if (!IamV2Client::enabled()) { return $this->data(['enabled' => false, 'management_enabled' => false, 'launch_enabled' => false]); }
|
||||
return $this->invokeV2(function () {
|
||||
$token = (string) $this->request->header('token', '');
|
||||
$legacy = Db::name('admin_session')->where('token', $token)->where('expire_time', '>', time())->find();
|
||||
if (!$legacy) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
IamV2Source::admin((int) $legacy['admin_id']);
|
||||
$fresh = false; try { $s = IamV2Source::current($token); $fresh = $s['auth_time'] >= time() - 300; } catch (\Throwable $e) { $s = null; }
|
||||
$b = (new IamV2Manager())->binding((int) $legacy['admin_id']);
|
||||
return ['enabled' => true, 'management_enabled' => IamV2Client::feature('management'), 'launch_enabled' => IamV2Client::feature('launch'), 'session_ready' => $s !== null, 'reauth_required' => !$fresh,
|
||||
'management_capabilities' => IamV2Source::capabilities((int) $legacy['admin_id']),
|
||||
'protected_review_operator' => IamV2Source::reviewOperator((int) $legacy['admin_id']),
|
||||
'protected_account' => IamV2Source::protectedAccount((int) $legacy['admin_id'])] + $b;
|
||||
});
|
||||
}
|
||||
public function reauth()
|
||||
{
|
||||
return $this->invokeV2(function () {
|
||||
if ((string) $this->request->header('origin') !== IamV2Client::origin((string) Config::get('iam.public_url'))) { throw new RuntimeException('INVALID_ORIGIN'); }
|
||||
$s = IamV2Source::reauth((string) $this->request->header('token', ''), (string) $this->request->post('password', ''));
|
||||
return ['expires_at' => $s['auth_time'] + 300];
|
||||
});
|
||||
}
|
||||
public function accounts() { return $this->invokeV2(function () { $s = $this->session(); IamV2Source::authorize($s, 'read', [], false); return (new IamV2Manager())->accounts((array) $this->request->get(), (int) $s['admin_id']); }); }
|
||||
public function identities()
|
||||
{
|
||||
return $this->invokeV2(function () {
|
||||
$s = $this->session(); IamV2Source::authorize($s, 'read', [], false);
|
||||
$q = http_build_query(['q' => mb_substr((string) $this->request->get('q', ''), 0, 64), 'page' => max(1, (int) $this->request->get('page', 1)), 'pageSize' => 20], '', '&', PHP_QUERY_RFC3986);
|
||||
return (new IamV2Client())->call('GET', '/identities?' . $q);
|
||||
});
|
||||
}
|
||||
public function operation() { return $this->invokeV2(fn() => (new IamV2Manager())->operation($this->session(true), $this->input(), $this->requestId())); }
|
||||
public function operationResult() { return $this->invokeV2(fn() => (new IamV2Manager())->result($this->session(), 'operation', (string) $this->request->param('id'))); }
|
||||
public function audit()
|
||||
{
|
||||
return $this->invokeV2(function () { $s = $this->session(); IamV2Source::authorize($s, 'read', [], false);
|
||||
IamV2Source::scope((int) $s['admin_id'], [(int) $this->request->param('id')]);
|
||||
return (new IamV2Client())->call('GET', '/audit?' . http_build_query(['externalAccountId' => (string) (int) $this->request->param('id'), 'page' => max(1, (int) $this->request->get('page', 1)), 'pageSize' => 20])); });
|
||||
}
|
||||
public function preflight() { return $this->invokeV2(fn() => (new IamV2Manager())->preflight($this->session(true), (array) $this->request->post('items', []))); }
|
||||
public function batch() { return $this->invokeV2(fn() => (new IamV2Manager())->batch($this->session(true), (string) $this->request->post('preview_id'), (array) $this->request->post('indexes', []), $this->requestId())); }
|
||||
public function job() { return $this->invokeV2(fn() => (new IamV2Manager())->result($this->session(), 'job', (string) $this->request->param('id'))); }
|
||||
public function retry() { return $this->invokeV2(fn() => (new IamV2Manager())->result($this->session(true), 'job', (string) $this->request->param('id'), true, (array) $this->request->post('indexes', []))); }
|
||||
public function introspect()
|
||||
{
|
||||
return $this->serviceResult(function () { $this->serviceAuth(); $b = $this->input(); return IamV2Source::introspect((string) ($b['proof'] ?? ''), (string) ($b['purpose'] ?? ''), $b['transactionId'] ?? null); });
|
||||
}
|
||||
private function serviceResult(callable $fn)
|
||||
{
|
||||
try { if (!IamV2Client::enabled()) { throw new RuntimeException('FEATURE_DISABLED'); } if (!$this->request->isPost()) { throw new RuntimeException('METHOD_NOT_ALLOWED'); } return json($fn())->header(['Cache-Control' => 'no-store']); }
|
||||
catch (\Throwable $e) { return json(['active' => false], 403)->header(['Cache-Control' => 'no-store']); }
|
||||
}
|
||||
public function checkSession()
|
||||
{
|
||||
return $this->serviceResult(function () { $this->serviceAuth(); $b = $this->input();
|
||||
return IamV2Source::liveStatus((string) ($b['sessionId'] ?? ''), (int) ($b['sessionVersion'] ?? 0),
|
||||
(string) ($b['purpose'] ?? ''), (array) ($b['targetLocalIds'] ?? [])); });
|
||||
}
|
||||
public function launchStart()
|
||||
{
|
||||
return $this->invokeV2(function () { $s = $this->session(); (new IamV2Manager())->assertLinked((int) $s['admin_id']);
|
||||
IamV2Source::check($s['session_id'], (int) $s['version']);
|
||||
$intent = bin2hex(random_bytes(32)); IamV2Flow::put('launch', $intent, ['sessionId' => $s['session_id'], 'sessionVersion' => $s['version']]);
|
||||
setcookie('ZYT_IAM_V2_INTENT', $intent, ['expires' => time() + 300, 'path' => '/adminapi/iam/v2', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
|
||||
return ['url' => IamV2Client::origin((string) Config::get('iam.erp_url')) . '/iam/launch?source=zyt&intent=' . $intent]; });
|
||||
}
|
||||
public function launchContinue()
|
||||
{
|
||||
try {
|
||||
IamV2Source::requirePurpose('launch');
|
||||
$client = new IamV2Client(); $s = IamV2Source::check((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
$intent = (string) $this->request->get('intent', ''); $cookie = (string) ($_COOKIE['ZYT_IAM_V2_INTENT'] ?? '');
|
||||
if ($intent === '' || !hash_equals($cookie, $intent)) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$flow = IamV2Flow::take('launch', $intent, $s['session_id']); IamV2Source::check($s['session_id'], (int) $flow['sessionVersion']);
|
||||
$tx = (string) $this->request->get('transaction_id', '');
|
||||
$transaction = $client->call('GET', '/launch-transactions/' . rawurlencode($tx));
|
||||
if (($transaction['sourceApplicationId'] ?? '') !== 'zyt' || ($transaction['targetApplicationId'] ?? '') !== 'zmxy-erp') { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
(new IamV2Manager($client))->assertLinked((int) $s['admin_id']);
|
||||
$grant = $client->call('POST', '/launch-grants', ['transactionId' => $tx, 'proof' => IamV2Source::proof($s, 'launch', [(int) $s['admin_id']], [], $tx)]);
|
||||
$erpOrigin = IamV2Client::origin((string) Config::get('iam.erp_url'));
|
||||
$delivery = IamV2Client::https((string) Config::get('iam.erp_callback_url') ?: $erpOrigin . '/api/erp/iam/v2/launch/callback');
|
||||
if (!in_array($delivery, [$erpOrigin . '/api/erp/iam/v2/launch/callback', $erpOrigin . '/basic-api/api/erp/iam/v2/launch/callback'], true)) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
if (($grant['deliveryUrl'] ?? '') !== $delivery) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
return response(IamV2Flow::form($delivery, ['transaction_id' => $tx, 'grant' => $grant['grant']]))->header(['Content-Type' => 'text/html; charset=utf-8', 'Cache-Control' => 'no-store', 'Referrer-Policy' => 'strict-origin']);
|
||||
} catch (\Throwable $e) { return redirect('/admin/user/setting?iam_result=launch_failed')->header(['Cache-Control' => 'no-store']); }
|
||||
}
|
||||
private function selfConfig(): array { $c = (array) Config::get('iam'); $c['redirect_uri'] = IamV2Client::origin($c['public_url']) . '/adminapi/iam/v2/self-link/callback'; return $c; }
|
||||
public function selfStart()
|
||||
{
|
||||
return $this->invokeV2(function () { $s = $this->session(true); $a = IamV2Source::admin((int) $s['admin_id']);
|
||||
if (IamV2Source::protectedAccount((int) $a['id'])) { throw new RuntimeException('PROTECTED_ACCOUNT_REVIEW_REQUIRED'); }
|
||||
$b = (new IamV2Manager())->binding((int) $s['admin_id'], true);
|
||||
if (($b['binding']['state'] ?? '') === 'verified') { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
$state = bin2hex(random_bytes(32)); $nonce = bin2hex(random_bytes(32)); $verifier = bin2hex(random_bytes(32));
|
||||
IamV2Flow::put('self_link', $state, ['sessionId' => $s['session_id'], 'nonce' => $nonce, 'verifier' => $verifier, 'version' => $b['binding']['version'] ?? null]);
|
||||
return ['url' => (new IamOidcClient($this->selfConfig()))->authorizationUrl($state, $nonce, $verifier) . '&prompt=login&max_age=300']; });
|
||||
}
|
||||
public function selfCallback()
|
||||
{
|
||||
try {
|
||||
IamV2Source::requirePurpose('self_link');
|
||||
$central = new IamV2Client(); $s = IamV2Source::check((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
$flow = IamV2Flow::take('self_link', (string) $this->request->get('state', ''), $s['session_id']);
|
||||
$oidc = new IamOidcClient($this->selfConfig()); $oidc->exchange((string) $this->request->get('code', ''), $flow['verifier'], $flow['nonce']);
|
||||
$proof = IamV2Source::proof($s, 'self_link', [(int) $s['admin_id']], [], null, ['oidcNonce' => $flow['nonce']]);
|
||||
$body = ['idToken' => $oidc->verifiedIdToken(), 'nonce' => $flow['nonce'], 'proof' => $proof, 'externalAccountId' => (string) $s['admin_id']];
|
||||
if ($flow['version'] !== null) { $body['expectedVersion'] = (int) $flow['version']; }
|
||||
$central->call('POST', '/self-link', $body);
|
||||
(new IamV2Manager($central))->binding((int) $s['admin_id'], true);
|
||||
return redirect('/admin/user/setting?iam_result=linked')->header(['Cache-Control' => 'no-store']);
|
||||
} catch (\Throwable $e) { return redirect('/admin/user/setting?iam_result=link_failed')->header(['Cache-Control' => 'no-store']); }
|
||||
}
|
||||
public function passwordSetup()
|
||||
{
|
||||
return $this->invokeV2(function () { $s = $this->session(true); $b = (new IamV2Manager())->assertLinked((int) $s['admin_id']);
|
||||
if (!($b['employee']['passwordSetupPending'] ?? false)) { throw new RuntimeException('PASSWORD_ALREADY_SET'); }
|
||||
$result = (new IamV2Client())->call('POST', '/password-setup', ['proof' => IamV2Source::proof($s, 'password_setup', [(int) $s['admin_id']])]);
|
||||
$url = parse_url((string) ($result['url'] ?? '')); $portal = parse_url(IamV2Client::origin((string) Config::get('iam.portal_url')));
|
||||
if (!$url || ($url['scheme'] ?? '') !== 'https' || ($url['host'] ?? '') !== $portal['host'] || ($url['port'] ?? 443) !== ($portal['port'] ?? 443) || isset($url['user']) || isset($url['pass']) || ($url['path'] ?? '') !== '/portal/password-setup') { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
$intent = bin2hex(random_bytes(32)); IamV2Flow::put('password_setup', $intent, ['sessionId' => $s['session_id'], 'requestId' => $result['requestId']], 900);
|
||||
setcookie('ZYT_IAM_PASSWORD_INTENT', $intent, ['expires' => time() + 900, 'path' => '/adminapi/iam/v2', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
|
||||
return $result; });
|
||||
}
|
||||
public function passwordContinue()
|
||||
{
|
||||
try {
|
||||
IamV2Source::requirePurpose('password_setup');
|
||||
$client = new IamV2Client(); $s = IamV2Source::check((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
$f = IamV2Flow::take('password_setup', (string) ($_COOKIE['ZYT_IAM_PASSWORD_INTENT'] ?? ''), $s['session_id']);
|
||||
$id = (string) $this->request->get('request_id', ''); $state = (string) $this->request->get('state', '');
|
||||
if ($id !== $f['requestId'] || !preg_match('/^[A-Za-z0-9_-]{32,256}$/D', $state)) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$proof = IamV2Source::proof($s, 'password_setup', [(int) $s['admin_id']], [], $id, ['state' => $state]);
|
||||
$url = IamV2Client::origin((string) Config::get('iam.portal_url')) . '/portal/password-setup/authorize';
|
||||
return response(IamV2Flow::form($url, ['request_id' => $id, 'state' => $state, 'proof' => $proof]))->header(['Content-Type' => 'text/html; charset=utf-8', 'Cache-Control' => 'no-store', 'Referrer-Policy' => 'strict-origin']);
|
||||
} catch (\Throwable $e) { return redirect('/admin/user/setting?iam_result=password_failed'); }
|
||||
}
|
||||
private function targetOrigin(): void
|
||||
{
|
||||
if (!$this->request->isPost() || (string) $this->request->header('origin') !== IamV2Client::origin((string) Config::get('iam.public_url'))) { throw new RuntimeException('INVALID_ORIGIN'); }
|
||||
}
|
||||
public function targetConfig()
|
||||
{
|
||||
if (!IamV2Client::enabled()) { return $this->data(['enabled' => false, 'management_enabled' => false, 'launch_enabled' => false]); }
|
||||
return $this->invokeV2(function () {
|
||||
$source = (string) $this->request->get('source', 'iam-portal');
|
||||
return ['enabled' => IamV2Client::feature('launch'), 'global_enabled' => true, 'management_enabled' => IamV2Client::feature('management'), 'launch_enabled' => IamV2Client::feature('launch'), 'restart_url' => IamV2Client::origin((string) Config::get('iam.portal_url')) . ($source === 'iam-admin' ? '/admin' : '/portal')];
|
||||
});
|
||||
}
|
||||
public function targetPrepare()
|
||||
{
|
||||
return $this->invokeV2(function () { $this->targetOrigin();
|
||||
$out = (new IamV2Target())->prepare((string) $this->request->post('source', ''), (string) $this->request->post('intent', ''),
|
||||
(string) $this->request->header('token', ''), (string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
setcookie(IamV2Target::COOKIE, $out['browser'], ['expires' => time() + 300, 'path' => '/adminapi/iam/v2/launch', 'secure' => true, 'httponly' => true, 'samesite' => 'None']);
|
||||
return ['url' => $out['url']];
|
||||
});
|
||||
}
|
||||
public function targetCallback()
|
||||
{
|
||||
try {
|
||||
if (!$this->request->isPost()) { throw new RuntimeException('METHOD_NOT_ALLOWED'); }
|
||||
$out = (new IamV2Target())->callback((string) $this->request->post('transaction_id', ''), (string) $this->request->post('grant', ''),
|
||||
(string) ($_COOKIE[IamV2Target::COOKIE] ?? ''), (string) $this->request->header('origin', ''));
|
||||
return redirect('/admin/iam/launch?' . http_build_query($out))->header(['Cache-Control' => 'no-store', 'Referrer-Policy' => 'no-referrer']);
|
||||
} catch (\Throwable $e) {
|
||||
$code = preg_match('/^[A-Z_]{3,64}$/D', $e->getMessage()) ? $e->getMessage() : 'SERVICE_UNAVAILABLE';
|
||||
return redirect('/admin/iam/launch?iam_error=' . rawurlencode($code))->header(['Cache-Control' => 'no-store', 'Referrer-Policy' => 'no-referrer']);
|
||||
}
|
||||
}
|
||||
public function targetExchange()
|
||||
{
|
||||
return $this->invokeV2(function () { $this->targetOrigin();
|
||||
return (new IamV2Target())->exchange((string) $this->request->post('ticket', ''), (string) ($_COOKIE[IamV2Target::COOKIE] ?? ''),
|
||||
(string) $this->request->header('token', ''), (string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
});
|
||||
}
|
||||
public function targetReset()
|
||||
{
|
||||
return $this->invokeV2(function () { $this->targetOrigin();
|
||||
IamV2Source::revokeSession((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
setcookie(IamV2Source::COOKIE, '', ['expires' => 1, 'path' => '/adminapi', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
|
||||
setcookie(IamV2Target::COOKIE, '', ['expires' => 1, 'path' => '/adminapi/iam/v2/launch', 'secure' => true, 'httponly' => true, 'samesite' => 'None']);
|
||||
return ['reset' => true];
|
||||
});
|
||||
}
|
||||
public function revocation()
|
||||
{
|
||||
return $this->serviceResult(fn() => \app\adminapi\service\iam\v2\IamV2Events::accept(
|
||||
(string) $this->request->getContent(), (string) $this->request->header('x-iam-signature', ''),
|
||||
(string) $this->request->header('x-iam-event-id', ''), (string) Config::get('iam.v2_event_secret', '')));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\adminapi\controller\identity;
|
||||
|
||||
use app\adminapi\controller\BaseAdminController;
|
||||
use app\adminapi\service\IdentityHospitalSsoService;
|
||||
use app\common\service\JsonService;
|
||||
use think\exception\HttpResponseException;
|
||||
|
||||
final class HospitalSsoController extends BaseAdminController
|
||||
{
|
||||
// The service authenticates the real source DB session; exchange authenticates its private PKCE ticket.
|
||||
public array $notNeedLogin = ['issue', 'exchange'];
|
||||
|
||||
public function issue()
|
||||
{
|
||||
return $this->handoff('issue');
|
||||
}
|
||||
|
||||
public function exchange()
|
||||
{
|
||||
return $this->handoff('exchange');
|
||||
}
|
||||
|
||||
private function handoff(string $operation)
|
||||
{
|
||||
$headers = ['Cache-Control' => 'no-store', 'Referrer-Policy' => 'no-referrer'];
|
||||
if (!$this->request->isPost()) { return JsonService::fail('请使用POST请求')->code(405)->header($headers); }
|
||||
if ($this->request->get() !== []) { return JsonService::fail('请求包含不支持的字段')->header($headers); }
|
||||
$origin = (string) $this->request->header('origin', '');
|
||||
if ($operation === 'exchange' && (($origin !== '' && $origin !== $this->request->domain())
|
||||
|| $this->request->header('sec-fetch-site', '') === 'cross-site')) {
|
||||
return JsonService::fail('登录请求来源不合法')->header($headers);
|
||||
}
|
||||
try {
|
||||
$service = new IdentityHospitalSsoService();
|
||||
$result = $operation === 'issue'
|
||||
? $service->issue((string) $this->request->header('token', ''), $this->request->post())
|
||||
: $service->exchange($this->request->post());
|
||||
return JsonService::data($result)->header($headers);
|
||||
} catch (HttpResponseException $error) { return $error->getResponse()->header($headers); }
|
||||
catch (\Throwable $error) { return JsonService::fail('医院登录暂时不可用,请稍后重试')->header($headers); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\adminapi\controller\identity;
|
||||
|
||||
use app\adminapi\controller\BaseAdminController;
|
||||
use app\adminapi\service\IdentitySessionService;
|
||||
use app\adminapi\validate\LoginValidate;
|
||||
use app\common\enum\AdminTerminalEnum;
|
||||
use app\common\service\JsonService;
|
||||
|
||||
/** 独立账号后台的个人会话接口,服务内部始终核验真实数据库会话。 */
|
||||
class SessionController extends BaseAdminController
|
||||
{
|
||||
// 首次改密/待绑定企微时也必须可用;这里仅跳过旧门禁,绝不跳过服务内认证。
|
||||
public array $notNeedLogin = ['login', 'verify', 'password', 'logout'];
|
||||
|
||||
public function verify()
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
return JsonService::fail('请使用POST请求');
|
||||
}
|
||||
$params = $this->request->post();
|
||||
if (array_diff(array_keys($params), ['account', 'password']) !== []
|
||||
|| !is_string($params['account'] ?? null) || $params['account'] === '' || strlen($params['account']) > 4096
|
||||
|| str_contains($params['account'], "\0") || !is_string($params['password'] ?? null)
|
||||
|| $params['password'] === '' || strlen($params['password']) > 4096 || str_contains($params['password'], "\0")) {
|
||||
return JsonService::fail('登录参数不合法');
|
||||
}
|
||||
$params = (new LoginValidate())->post()->goCheck('verify');
|
||||
return $this->data(IdentitySessionService::verify($params));
|
||||
}
|
||||
|
||||
public function login()
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
return JsonService::fail('请使用POST请求');
|
||||
}
|
||||
// 专用集团终端只在此入口接受;不扩大普通网页登录的终端白名单。
|
||||
$terminal = $this->request->post('terminal');
|
||||
$groupSession = in_array($terminal, [AdminTerminalEnum::GROUP_IDENTITY, (string) AdminTerminalEnum::GROUP_IDENTITY], true);
|
||||
// verify 场景保留原限流并禁用调试免密;服务仍在账号锁内校验全部参数与当前密码。
|
||||
$params = (new LoginValidate())->post()->goCheck($groupSession ? 'verify' : null);
|
||||
return $this->data(IdentitySessionService::login($params));
|
||||
}
|
||||
|
||||
public function password()
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
return JsonService::fail('请使用POST请求');
|
||||
}
|
||||
IdentitySessionService::changePassword((string) $this->request->header('token', ''), $this->request->post());
|
||||
return $this->success('密码修改成功,请重新登录');
|
||||
}
|
||||
|
||||
public function logout()
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
return JsonService::fail('请使用POST请求');
|
||||
}
|
||||
$params = $this->request->post();
|
||||
if (array_diff(array_keys($params), ['all']) !== [] || !in_array($params['all'] ?? 0, [0, 1, '0', '1'], true)) {
|
||||
return JsonService::fail('退出参数不合法');
|
||||
}
|
||||
IdentitySessionService::logout((string) $this->request->header('token', ''), (int) ($params['all'] ?? 0) === 1);
|
||||
return $this->success('已退出登录');
|
||||
}
|
||||
}
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
use think\facade\Route;
|
||||
// Explicit method/path mapping; controller also fails closed for every v2 capability.
|
||||
Route::get('iam/v2/status', 'IamV2/status');
|
||||
Route::post('iam/v2/reauth', 'IamV2/reauth');
|
||||
Route::get('iam/v2/accounts', 'IamV2/accounts');
|
||||
Route::get('iam/v2/identities', 'IamV2/identities');
|
||||
Route::post('iam/v2/operations', 'IamV2/operation');
|
||||
Route::get('iam/v2/operations/:id', 'IamV2/operationResult');
|
||||
Route::get('iam/v2/accounts/:id/audit', 'IamV2/audit');
|
||||
Route::post('iam/v2/batch/preflight', 'IamV2/preflight');
|
||||
Route::post('iam/v2/batch', 'IamV2/batch');
|
||||
Route::get('iam/v2/jobs/:id', 'IamV2/job');
|
||||
Route::post('iam/v2/jobs/:id/retry', 'IamV2/retry');
|
||||
Route::post('iam/v2/proofs/introspect', 'IamV2/introspect');
|
||||
Route::post('iam/v2/sessions/check', 'IamV2/checkSession');
|
||||
Route::post('iam/v2/events/revocation', 'IamV2/revocation');
|
||||
Route::post('iam/v2/launch/start', 'IamV2/launchStart');
|
||||
Route::get('iam/v2/launch/continue', 'IamV2/launchContinue');
|
||||
Route::post('iam/v2/self-link/start', 'IamV2/selfStart');
|
||||
Route::get('iam/v2/self-link/callback', 'IamV2/selfCallback');
|
||||
Route::post('iam/v2/password-setup', 'IamV2/passwordSetup');
|
||||
Route::get('iam/v2/password-continue', 'IamV2/passwordContinue');
|
||||
|
||||
// ZYT as a target for the same person's IAM admin/portal session only.
|
||||
Route::get('iam/v2/launch/config', 'IamV2/targetConfig');
|
||||
Route::post('iam/v2/launch/prepare', 'IamV2/targetPrepare');
|
||||
Route::post('iam/v2/launch/callback', 'IamV2/targetCallback');
|
||||
Route::post('iam/v2/launch/exchange', 'IamV2/targetExchange');
|
||||
Route::post('iam/v2/launch/reset', 'IamV2/targetReset');
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\adminapi\service;
|
||||
|
||||
use app\common\cache\AdminAuthCache;
|
||||
use app\common\cache\AdminTokenCache;
|
||||
use app\common\model\auth\Admin;
|
||||
use app\common\model\auth\AdminRole;
|
||||
use app\common\model\auth\AdminSession;
|
||||
use app\common\model\auth\SystemMenu;
|
||||
use app\common\model\auth\SystemRoleMenu;
|
||||
use think\facade\Log;
|
||||
|
||||
/** 原账号变更:事务内锁账号并撤销会话,提交成功后才清缓存。 */
|
||||
final class AdminAccessSyncService
|
||||
{
|
||||
public static function ids(array $ids): array
|
||||
{
|
||||
$ids = array_values(array_unique(array_filter(array_map('intval', $ids), static fn (int $id): bool => $id > 0)));
|
||||
sort($ids, SORT_NUMERIC);
|
||||
return $ids;
|
||||
}
|
||||
|
||||
public static function roleAdminIds(array $roleIds): array
|
||||
{
|
||||
return $roleIds === [] ? [] : self::ids(AdminRole::whereIn('role_id', $roleIds)->column('admin_id'));
|
||||
}
|
||||
|
||||
/** 菜单父节点变更也影响只获授子节点的账号。 */
|
||||
public static function menuAdminIds(int $menuId): array
|
||||
{
|
||||
$menuIds = [$menuId];
|
||||
$rows = SystemMenu::field('id,pid')->select()->toArray();
|
||||
do {
|
||||
$count = count($menuIds);
|
||||
foreach ($rows as $row) {
|
||||
if (in_array((int) $row['pid'], $menuIds, true)) { $menuIds[] = (int) $row['id']; }
|
||||
}
|
||||
$menuIds = self::ids($menuIds);
|
||||
} while (count($menuIds) !== $count);
|
||||
return self::roleAdminIds(self::ids(SystemRoleMenu::whereIn('menu_id', $menuIds)->column('role_id')));
|
||||
}
|
||||
|
||||
/** 调用者必须已开启事务;与密码登录、SSO签发和续期共用账号锁。 */
|
||||
public static function revoke(array $adminIds): array
|
||||
{
|
||||
$adminIds = self::ids($adminIds);
|
||||
if ($adminIds === []) { return []; }
|
||||
Admin::whereIn('id', $adminIds)->order('id')->lock(true)->field('id')->select();
|
||||
$tokens = AdminSession::whereIn('admin_id', $adminIds)->column('token');
|
||||
AdminSession::whereIn('admin_id', $adminIds)->update(['expire_time' => time() - 1, 'update_time' => time()]);
|
||||
return $tokens;
|
||||
}
|
||||
|
||||
public static function clearCommitted(array $adminIds, array $tokens): void
|
||||
{
|
||||
// DB是有效性的准绳;缓存故障不能把已提交操作伪报失败,也不能恢复旧会话。
|
||||
foreach ($tokens as $token) {
|
||||
try { (new AdminTokenCache())->deleteAdminInfo((string) $token); }
|
||||
catch (\Throwable $error) { Log::warning('账号变更已提交,会话缓存清理失败'); }
|
||||
}
|
||||
foreach (self::ids($adminIds) as $adminId) {
|
||||
try { (new AdminAuthCache($adminId))->clearAuthCache(); }
|
||||
catch (\Throwable $error) { Log::warning('账号变更已提交,权限缓存清理失败:admin_id=' . $adminId); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\adminapi\service;
|
||||
|
||||
/** 核心账号管理接口独立于可编辑菜单的URI登记,删除菜单也不能变成免鉴权接口。 */
|
||||
final class CoreAccountPermissionPolicy
|
||||
{
|
||||
/** null=非核心接口;[]为已登录账号自己的资料或导航接口;其余为允许的原权限别名。 */
|
||||
public static function aliases(string $uri): ?array
|
||||
{
|
||||
[$controller, $action] = array_pad(explode('/', strtolower($uri), 2), 2, '');
|
||||
if (!in_array($controller, ['auth.admin', 'auth.role', 'auth.menu', 'dept.dept'], true)) { return null; }
|
||||
if (($controller === 'auth.admin' && in_array($action, ['myself', 'editself', 'bindworkwechat', 'unbindworkwechat'], true))
|
||||
|| ($controller === 'auth.menu' && $action === 'route')) { return []; }
|
||||
$aliases = [$uri];
|
||||
if ($action === 'detail') { $aliases = array_merge($aliases, [$controller . '/lists', $controller . '/edit']); }
|
||||
if ($action === 'all' || ($controller === 'dept.dept' && $action === 'leaderdept')) {
|
||||
$aliases = array_merge($aliases, [$controller . '/lists', $controller . '/add', $controller . '/edit']);
|
||||
if (in_array($controller, ['auth.role', 'dept.dept'], true)) {
|
||||
$aliases = array_merge($aliases, ['auth.admin/add', 'auth.admin/edit']);
|
||||
}
|
||||
if ($controller === 'auth.menu') { $aliases = array_merge($aliases, ['auth.role/add', 'auth.role/edit']); }
|
||||
}
|
||||
if ($controller === 'auth.menu' && $action === 'updatestatus') { $aliases[] = 'auth.menu/edit'; }
|
||||
return $aliases;
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\adminapi\service;
|
||||
|
||||
use app\adminapi\logic\LoginLogic;
|
||||
use app\adminapi\http\middleware\AuthMiddleware;
|
||||
use app\common\cache\AdminTokenCache;
|
||||
use app\common\enum\AdminTerminalEnum;
|
||||
use app\common\model\auth\Admin;
|
||||
use app\common\model\auth\AdminSession;
|
||||
use app\common\service\JsonService;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
|
||||
/** The hospital trusts its own live source session, never a caller-provided identity. */
|
||||
final class IdentityHospitalSsoService
|
||||
{
|
||||
private IdentityHospitalSsoTicketStore $tickets;
|
||||
|
||||
public function __construct(?IdentityHospitalSsoTicketStore $tickets = null)
|
||||
{
|
||||
$this->tickets = $tickets ?? new IdentityHospitalSsoTicketStore(app()->getRuntimePath() . 'identity-hospital-sso');
|
||||
}
|
||||
|
||||
public function issue(string $sourceToken, array $data): array
|
||||
{
|
||||
self::only($data, ['code_challenge', 'code_challenge_method']);
|
||||
if (($data['code_challenge_method'] ?? null) !== 'S256'
|
||||
|| !is_string($data['code_challenge'] ?? null)
|
||||
|| !preg_match('/^[A-Za-z0-9_-]{43}$/D', $data['code_challenge'])) {
|
||||
JsonService::throw('登录验证参数不合法');
|
||||
}
|
||||
if ($sourceToken === '' || strlen($sourceToken) > 512 || preg_match('/[\x00-\x20\x7f]/', $sourceToken)) {
|
||||
JsonService::throw('请先登录集团工作台', [], -1);
|
||||
}
|
||||
return Db::transaction(function () use ($sourceToken, $data): array {
|
||||
$candidate = AdminSession::where('token', $sourceToken)->findOrEmpty();
|
||||
[$admin, $session] = self::lockSource($candidate, hash('sha256', $sourceToken));
|
||||
self::ready($admin);
|
||||
// 交接源仍受原 IP 绑定保护;目标 exchange 才允许来自医院浏览器的不同 IP。
|
||||
$info = (new AdminTokenCache())->getAdminInfo($sourceToken);
|
||||
$ip = request()->ip();
|
||||
if (!$info || (int) ($info['admin_id'] ?? 0) !== (int) $admin['id']
|
||||
|| (($info['login_ip'] ?? '') !== $ip && !AuthMiddleware::isTrustedRpaServerRequest(
|
||||
(array) $info, $ip, env('wecom_rpa.server_ips', '')))) {
|
||||
JsonService::throw('ip地址发生变化,请重新登录', [], -1);
|
||||
}
|
||||
return ['ticket' => $this->tickets->issue((int) $session['id'], hash('sha256', $sourceToken), $data['code_challenge'])];
|
||||
});
|
||||
}
|
||||
|
||||
public function exchange(array $data): array
|
||||
{
|
||||
self::only($data, ['ticket', 'code_verifier']);
|
||||
if (!is_string($data['ticket'] ?? null) || !is_string($data['code_verifier'] ?? null)) {
|
||||
JsonService::throw('登录验证参数不合法');
|
||||
}
|
||||
try { $record = $this->tickets->consume($data['ticket'], $data['code_verifier']); }
|
||||
catch (\RuntimeException $error) { JsonService::throw('登录票据已失效,请重新从集团工作台进入'); }
|
||||
|
||||
$result = Db::transaction(static function () use ($record): array {
|
||||
$candidate = AdminSession::where('id', $record['session_id'])->findOrEmpty();
|
||||
[$admin] = self::lockSource($candidate, $record['token_hash']);
|
||||
self::ready($admin);
|
||||
$now = time();
|
||||
$target = AdminSession::where('admin_id', (int) $admin['id'])
|
||||
->where('terminal', AdminTerminalEnum::GROUP_HOSPITAL)->lock(true)->findOrEmpty();
|
||||
$oldToken = $target->isEmpty() ? '' : (string) $target['token'];
|
||||
$token = $oldToken;
|
||||
if ($target->isEmpty() || (int) $target['expire_time'] <= $now || (int) $admin['multipoint_login'] === 0) {
|
||||
// 原 admin_session.token 为 varchar(32),保持128位随机性且不修改业务表。
|
||||
$token = bin2hex(random_bytes(16));
|
||||
}
|
||||
$values = ['token' => $token, 'expire_time' => $now + (int) Config::get('project.admin_token.expire_duration'),
|
||||
'update_time' => $now];
|
||||
if ($target->isEmpty()) {
|
||||
AdminSession::create($values + ['admin_id' => (int) $admin['id'], 'terminal' => AdminTerminalEnum::GROUP_HOSPITAL]);
|
||||
} else { $target->save($values); }
|
||||
// Persist the independent session under the same account/source locks. Publish its cache only after commit.
|
||||
return ['token' => $token, 'old_token' => $oldToken, 'name' => (string) $admin['name'],
|
||||
'avatar' => (string) $admin['avatar']];
|
||||
});
|
||||
$cache = new AdminTokenCache();
|
||||
if ($result['old_token'] !== '' && $result['old_token'] !== $result['token']) {
|
||||
$cache->deleteAdminInfo($result['old_token']);
|
||||
}
|
||||
// This executes in the real hospital browser request, retaining the original per-token IP protection.
|
||||
$info = $cache->setAdminInfo($result['token']);
|
||||
if (!$info) { JsonService::throw('登录已失效,请重新进入', [], -1); }
|
||||
return ['name' => $result['name'], 'avatar' => $result['avatar'], 'role_name' => $info['role_name'],
|
||||
'token' => $result['token'], 'is_paw' => 1, 'need_bind_work_wechat' => false];
|
||||
}
|
||||
|
||||
private static function lockSource(AdminSession $candidate, string $tokenHash): array
|
||||
{
|
||||
if ($candidate->isEmpty()) { JsonService::throw('集团登录已失效,请重新登录', [], -1); }
|
||||
// Same order as IdentitySessionService and account changes: account row, then the exact session row.
|
||||
$admin = Admin::where('id', (int) $candidate['admin_id'])->lock(true)->findOrEmpty();
|
||||
if ($admin->isEmpty() || (int) $admin['disable'] !== 0 || !empty($admin->getData('delete_time'))) {
|
||||
JsonService::throw('集团登录已失效,请重新登录', [], -1);
|
||||
}
|
||||
$session = AdminSession::where('id', (int) $candidate['id'])->where('admin_id', (int) $admin['id'])
|
||||
->where('expire_time', '>', time())->lock(true)->findOrEmpty();
|
||||
if ($session->isEmpty() || !hash_equals($tokenHash, hash('sha256', (string) $session['token']))
|
||||
|| (int) $session['terminal'] === AdminTerminalEnum::GROUP_HOSPITAL) {
|
||||
JsonService::throw('集团登录已失效,请重新登录', [], -1);
|
||||
}
|
||||
return [$admin, $session];
|
||||
}
|
||||
|
||||
private static function ready(Admin $admin): void
|
||||
{
|
||||
if ((int) $admin['is_paw'] !== 1) { JsonService::throw('请先在集团工作台完成首次密码修改'); }
|
||||
if (LoginLogic::adminMustBindWorkWechat(['root' => (int) $admin['root'],
|
||||
'work_wechat_userid' => (string) ($admin['work_wechat_userid'] ?? '')])) {
|
||||
JsonService::throw('请先在原后台完成企业微信绑定', [], LoginLogic::CODE_NEED_BIND_WORK_WECHAT);
|
||||
}
|
||||
}
|
||||
|
||||
private static function only(array $data, array $allowed): void
|
||||
{
|
||||
if (array_diff(array_keys($data), $allowed) !== []) { JsonService::throw('请求包含不支持的字段'); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\adminapi\service;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/** Private single-server handoff tickets. Neither raw source tokens nor passwords are persisted. */
|
||||
final class IdentityHospitalSsoTicketStore
|
||||
{
|
||||
private \Closure $clock;
|
||||
|
||||
public function __construct(private string $directory, ?callable $clock = null)
|
||||
{
|
||||
$this->clock = $clock === null ? static fn (): int => time() : \Closure::fromCallable($clock);
|
||||
}
|
||||
|
||||
public function issue(int $sessionId, string $tokenHash, string $challenge): string
|
||||
{
|
||||
return $this->locked(function () use ($sessionId, $tokenHash, $challenge): string {
|
||||
foreach (array_slice(glob($this->directory . '/*.json') ?: [], 0, 200) as $path) {
|
||||
$old = $this->read($path);
|
||||
if ($old !== null && (int) ($old['expires'] ?? 0) <= ($this->clock)()) { unlink($path); }
|
||||
}
|
||||
$ticket = bin2hex(random_bytes(32));
|
||||
$record = ['session_id' => $sessionId, 'token_hash' => $tokenHash, 'challenge' => $challenge,
|
||||
'expires' => ($this->clock)() + 30];
|
||||
$path = $this->path($ticket);
|
||||
$file = fopen($path, 'x+b');
|
||||
if ($file === false) { throw new RuntimeException('Hospital handoff storage unavailable'); }
|
||||
try {
|
||||
chmod($path, 0600);
|
||||
$json = json_encode($record, JSON_THROW_ON_ERROR);
|
||||
if (fwrite($file, $json) !== strlen($json) || !fflush($file)) {
|
||||
throw new RuntimeException('Hospital handoff storage unavailable');
|
||||
}
|
||||
} catch (\Throwable $error) {
|
||||
fclose($file);
|
||||
unlink($path);
|
||||
throw $error;
|
||||
}
|
||||
fclose($file);
|
||||
return $ticket;
|
||||
});
|
||||
}
|
||||
|
||||
public function consume(string $ticket, string $verifier): array
|
||||
{
|
||||
if (!preg_match('/^[a-f0-9]{64}$/D', $ticket)
|
||||
|| !preg_match('/^[A-Za-z0-9._~-]{43,128}$/D', $verifier)) {
|
||||
throw new RuntimeException('Hospital handoff invalid');
|
||||
}
|
||||
return $this->locked(function () use ($ticket, $verifier): array {
|
||||
$path = $this->path($ticket);
|
||||
$record = $this->read($path);
|
||||
$challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
|
||||
if ($record === null || !is_int($record['expires'] ?? null) || $record['expires'] <= ($this->clock)()
|
||||
|| !is_int($record['session_id'] ?? null) || $record['session_id'] < 1
|
||||
|| !is_string($record['token_hash'] ?? null) || !preg_match('/^[a-f0-9]{64}$/D', $record['token_hash'])
|
||||
|| !is_string($record['challenge'] ?? null) || !hash_equals($record['challenge'], $challenge)) {
|
||||
throw new RuntimeException('Hospital handoff invalid');
|
||||
}
|
||||
// The global private lock covers open/read/delete, so simultaneous exchanges cannot replay.
|
||||
if (!unlink($path)) { throw new RuntimeException('Hospital handoff consumption failed'); }
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
|
||||
private function read(string $path): ?array
|
||||
{
|
||||
if (!is_file($path) || is_link($path) || filesize($path) > 4096) { return null; }
|
||||
try { $record = json_decode((string) file_get_contents($path), true, 8, JSON_THROW_ON_ERROR); }
|
||||
catch (\JsonException $error) { return null; }
|
||||
return is_array($record) ? $record : null;
|
||||
}
|
||||
|
||||
private function path(string $ticket): string
|
||||
{
|
||||
return $this->directory . '/' . hash('sha256', $ticket) . '.json';
|
||||
}
|
||||
|
||||
private function locked(callable $operation): mixed
|
||||
{
|
||||
if (is_link($this->directory) || (!is_dir($this->directory)
|
||||
&& !mkdir($this->directory, 0700, true) && !is_dir($this->directory))) {
|
||||
throw new RuntimeException('Hospital handoff storage unavailable');
|
||||
}
|
||||
chmod($this->directory, 0700);
|
||||
$path = $this->directory . '/.lock';
|
||||
if (is_link($path)) { throw new RuntimeException('Hospital handoff storage unavailable'); }
|
||||
$lock = fopen($path, 'c+b');
|
||||
if ($lock === false) { throw new RuntimeException('Hospital handoff storage unavailable'); }
|
||||
chmod($path, 0600);
|
||||
try {
|
||||
if (!flock($lock, LOCK_EX)) { throw new RuntimeException('Hospital handoff storage unavailable'); }
|
||||
return $operation();
|
||||
} finally { flock($lock, LOCK_UN); fclose($lock); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\adminapi\service;
|
||||
|
||||
use app\adminapi\logic\LoginLogic;
|
||||
use app\common\cache\AdminTokenCache;
|
||||
use app\common\enum\AdminTerminalEnum;
|
||||
use app\common\model\auth\Admin;
|
||||
use app\common\model\auth\AdminSession;
|
||||
use app\common\service\JsonService;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
|
||||
/** 共用原账号密码与原会话,不信任桥接层提供的用户编号或root标记。 */
|
||||
final class IdentitySessionService
|
||||
{
|
||||
/** 验证外部子系统的凭据,不创建、复用、刷新或注销原系统会话。 */
|
||||
public static function verify(array $params): array
|
||||
{
|
||||
if (array_diff(array_keys($params), ['account', 'password']) !== []) {
|
||||
JsonService::throw('请求包含不支持的字段');
|
||||
}
|
||||
$account = $params['account'] ?? null;
|
||||
$password = $params['password'] ?? null;
|
||||
if (!is_string($account) || $account === '' || strlen($account) > 4096 || str_contains($account, "\0")
|
||||
|| !is_string($password) || $password === '' || strlen($password) > 4096 || str_contains($password, "\0")) {
|
||||
JsonService::throw('登录参数不合法');
|
||||
}
|
||||
return Db::transaction(static function () use ($account, $password): array {
|
||||
$admin = Admin::where('account', $account)->lock(true)->findOrEmpty();
|
||||
$salt = (string) Config::get('project.unique_identification');
|
||||
if ($admin->isEmpty() || (int) $admin['disable'] !== 0
|
||||
|| !hash_equals((string) $admin['password'], create_password($password, $salt))) {
|
||||
JsonService::throw('账号或密码错误,或账号已停用', [], -1);
|
||||
}
|
||||
return ['id' => (int) $admin['id'], 'account' => (string) $admin['account'],
|
||||
'name' => (string) ($admin['name'] ?? ''), 'disable' => 0,
|
||||
'requires_password_change' => (int) ($admin['is_paw'] ?? 1) === 0,
|
||||
'requires_wecom_binding' => LoginLogic::adminMustBindWorkWechat([
|
||||
'root' => (int) ($admin['root'] ?? 0),
|
||||
'work_wechat_userid' => (string) ($admin['work_wechat_userid'] ?? ''),
|
||||
])];
|
||||
});
|
||||
}
|
||||
|
||||
/** 与个人改密共用账号行锁,绝不信任事务前验证器的密码快照或调试免密结果。 */
|
||||
public static function login(array $params): array
|
||||
{
|
||||
if (array_diff(array_keys($params), ['account', 'password', 'terminal']) !== []) {
|
||||
JsonService::throw('请求包含不支持的字段');
|
||||
}
|
||||
$account = $params['account'] ?? null;
|
||||
$password = $params['password'] ?? null;
|
||||
$terminal = $params['terminal'] ?? null;
|
||||
if (!is_string($account) || $account === '' || strlen($account) > 4096 || str_contains($account, "\0")
|
||||
|| !is_string($password) || $password === '' || strlen($password) > 4096 || str_contains($password, "\0")
|
||||
|| (!is_int($terminal) && !is_string($terminal))
|
||||
|| !in_array((string) $terminal, ['1', '2', '7', '9', (string) AdminTerminalEnum::GROUP_IDENTITY], true)) {
|
||||
JsonService::throw('登录参数不合法');
|
||||
}
|
||||
return Db::transaction(static function () use ($account, $password, $params): array {
|
||||
$admin = Admin::where('account', $account)->lock(true)->findOrEmpty();
|
||||
$salt = (string) Config::get('project.unique_identification');
|
||||
if ($admin->isEmpty() || (int) $admin['disable'] !== 0
|
||||
|| !hash_equals((string) $admin['password'], create_password($password, $salt))) {
|
||||
JsonService::throw('账号或密码错误,或账号已停用', [], -1);
|
||||
}
|
||||
// 原登录的资料更新和会话签发均在该账号锁释放前完成。
|
||||
return (new LoginLogic())->login($params);
|
||||
});
|
||||
}
|
||||
|
||||
public static function changePassword(string $token, array $params): void
|
||||
{
|
||||
if (array_diff(array_keys($params), ['old_password', 'password', 'password_confirm']) !== []) {
|
||||
JsonService::throw('请求包含不支持的字段');
|
||||
}
|
||||
$password = $params['password'] ?? null;
|
||||
if (!is_string($password) || strlen($password) < 6 || strlen($password) > 32 || str_contains($password, "\0")) {
|
||||
JsonService::throw('密码长度须在6-32字节');
|
||||
}
|
||||
if ($password !== ($params['password_confirm'] ?? null)) {
|
||||
JsonService::throw('两次输入的密码不一致');
|
||||
}
|
||||
$tokens = Db::transaction(static function () use ($token, $params, $password): array {
|
||||
[$admin] = self::lockContext($token);
|
||||
$firstPassword = (int) ($admin['is_paw'] ?? 1) === 0;
|
||||
if (!$firstPassword && LoginLogic::adminMustBindWorkWechat([
|
||||
'root' => (int) $admin['root'], 'work_wechat_userid' => (string) ($admin['work_wechat_userid'] ?? ''),
|
||||
])) {
|
||||
JsonService::throw('请先在原后台绑定企业微信', [], LoginLogic::CODE_NEED_BIND_WORK_WECHAT);
|
||||
}
|
||||
$salt = (string) Config::get('project.unique_identification');
|
||||
if (!$firstPassword) {
|
||||
$oldPassword = $params['old_password'] ?? null;
|
||||
if (!is_string($oldPassword) || strlen($oldPassword) > 1024
|
||||
|| !hash_equals((string) $admin['password'], create_password($oldPassword, $salt))) {
|
||||
JsonService::throw('当前密码错误');
|
||||
}
|
||||
}
|
||||
$id = (int) $admin['id'];
|
||||
Admin::where('id', $id)->update([
|
||||
'password' => create_password($password, $salt), 'is_paw' => 1, 'update_time' => time(),
|
||||
]);
|
||||
return self::expire($id, null);
|
||||
});
|
||||
self::clearTokens($tokens);
|
||||
}
|
||||
|
||||
public static function logout(string $token, bool $all = false): void
|
||||
{
|
||||
$tokens = Db::transaction(static function () use ($token, $all): array {
|
||||
[$admin] = self::lockContext($token);
|
||||
return self::expire((int) $admin['id'], $all ? null : $token);
|
||||
});
|
||||
self::clearTokens($tokens);
|
||||
}
|
||||
|
||||
/** 先锁账号再锁会话,避免两个会话同时改密时互相等待。 */
|
||||
private static function lockContext(string $token): array
|
||||
{
|
||||
if ($token === '' || strlen($token) > 512 || preg_match('/[\x00-\x20\x7f]/', $token)) {
|
||||
JsonService::throw('请先登录', [], -1);
|
||||
}
|
||||
$candidate = AdminSession::where('token', $token)->findOrEmpty();
|
||||
if ($candidate->isEmpty()) {
|
||||
JsonService::throw('登录已失效,请重新登录', [], -1);
|
||||
}
|
||||
$admin = Admin::where('id', (int) $candidate['admin_id'])->lock(true)->findOrEmpty();
|
||||
if ($admin->isEmpty() || (int) $admin['disable'] !== 0) {
|
||||
JsonService::throw('登录已失效,请重新登录', [], -1);
|
||||
}
|
||||
$session = AdminSession::where('admin_id', (int) $admin['id'])->where('token', $token)
|
||||
->where('expire_time', '>', time())->lock(true)->findOrEmpty();
|
||||
if ($session->isEmpty()) {
|
||||
JsonService::throw('登录已失效,请重新登录', [], -1);
|
||||
}
|
||||
return [$admin, $session];
|
||||
}
|
||||
|
||||
private static function expire(int $adminId, ?string $token): array
|
||||
{
|
||||
$query = static function () use ($adminId, $token) {
|
||||
$builder = AdminSession::where('admin_id', $adminId);
|
||||
return $token === null ? $builder : $builder->where('token', $token);
|
||||
};
|
||||
$tokens = $query()->column('token');
|
||||
$query()->update(['expire_time' => time() - 1, 'update_time' => time()]);
|
||||
return $tokens;
|
||||
}
|
||||
|
||||
private static function clearTokens(array $tokens): void
|
||||
{
|
||||
$cache = new AdminTokenCache();
|
||||
foreach ($tokens as $token) {
|
||||
$cache->deleteAdminInfo((string) $token);
|
||||
}
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Config;
|
||||
|
||||
/** Dedicated v2 application credential; never falls back to the v1 provisioning token. */
|
||||
final class IamV2Client
|
||||
{
|
||||
public function __construct(private ?array $settings = null, private $transport = null)
|
||||
{
|
||||
$this->settings ??= (array) Config::get('iam', []);
|
||||
if (!self::enabled($this->settings)) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
self::https((string) ($this->settings['api_url'] ?? ''));
|
||||
foreach (['public_url', 'erp_url'] as $field) { self::origin((string) ($this->settings[$field] ?? '')); }
|
||||
if (strlen((string) ($this->settings['v2_token'] ?? '')) < 32) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
|
||||
}
|
||||
public static function enabled(?array $settings = null): bool
|
||||
{
|
||||
$settings ??= (array) Config::get('iam', []);
|
||||
return filter_var($settings['v2_enabled'] ?? false, FILTER_VALIDATE_BOOL);
|
||||
}
|
||||
public static function feature(string $feature, ?array $settings = null): bool
|
||||
{
|
||||
$settings ??= (array) Config::get('iam', []);
|
||||
if (!in_array($feature, ['management', 'launch'], true)) { return false; }
|
||||
return self::enabled($settings) && filter_var($settings['v2_' . $feature . '_enabled'] ?? false, FILTER_VALIDATE_BOOL);
|
||||
}
|
||||
public static function https(string $url): string
|
||||
{
|
||||
$p = parse_url($url);
|
||||
if (!$p || ($p['scheme'] ?? '') !== 'https' || empty($p['host']) || isset($p['user']) || isset($p['pass'])
|
||||
|| isset($p['fragment']) || isset($p['query']) || preg_match('/[\x00-\x20\x7f\\\\]/', $url)) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
return rtrim($url, '/');
|
||||
}
|
||||
public static function origin(string $url): string
|
||||
{
|
||||
$url = self::https($url);
|
||||
if ((parse_url($url, PHP_URL_PATH) ?? '') !== '') { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
return $url;
|
||||
}
|
||||
public function call(string $method, string $path, array $body = [], ?string $key = null): array
|
||||
{
|
||||
if (!preg_match('#^/[a-zA-Z0-9/_?=&%.:-]+$#D', $path) || str_contains($path, '..')) { throw new RuntimeException('INVALID_PATH'); }
|
||||
$url = rtrim($this->settings['api_url'], '/') . '/internal/v2/applications/' . rawurlencode($this->settings['application_id'] ?? 'zyt') . $path;
|
||||
$management = preg_match('#^/(identities|operations|audit|batch|jobs)(/|[?]|$)#D', $path) === 1;
|
||||
$credential = (string) ($this->settings[$management ? 'v2_management_token' : 'v2_token'] ?? '');
|
||||
if (strlen($credential) < 32 || preg_match('/[\r\n]/', $credential)
|
||||
|| ($management && hash_equals((string) $this->settings['v2_token'], $credential))) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
|
||||
$headers = ['Accept: application/json', 'Content-Type: application/json', 'Authorization: Bearer ' . $credential];
|
||||
if ($method !== 'GET') {
|
||||
$headers[] = 'X-Request-ID: ' . bin2hex(random_bytes(16));
|
||||
$headers[] = 'Idempotency-Key: ' . ($key ?? bin2hex(random_bytes(24)));
|
||||
}
|
||||
$data = $method === 'GET' ? '' : json_encode($body, JSON_THROW_ON_ERROR);
|
||||
if ($this->transport) { $r = ($this->transport)($method, $url, $headers, $data); }
|
||||
else {
|
||||
$c = curl_init($url); $response = '';
|
||||
curl_setopt_array($c, [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers,
|
||||
CURLOPT_POSTFIELDS => $data, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false,
|
||||
CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
|
||||
CURLOPT_CONNECTTIMEOUT => 3, CURLOPT_TIMEOUT => 10,
|
||||
CURLOPT_WRITEFUNCTION => static function ($c, $chunk) use (&$response) {
|
||||
if (strlen($response) + strlen($chunk) > 2097152) { return 0; } $response .= $chunk; return strlen($chunk);
|
||||
}]);
|
||||
$ok = curl_exec($c); $r = ['status' => curl_getinfo($c, CURLINFO_RESPONSE_CODE), 'body' => $ok === false ? '' : $response]; curl_close($c);
|
||||
}
|
||||
$result = json_decode($r['body'] ?? '', true);
|
||||
if (!is_array($result)) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
|
||||
$operationEnvelope = isset($result['id']) && is_string($result['id'])
|
||||
&& in_array($result['status'] ?? '', ['pending', 'succeeded', 'failed', 'conflict'], true)
|
||||
&& preg_match('#^/(operations|jobs|batch)(/|$)#D', $path);
|
||||
if (($r['status'] ?? 0) < 200 || $r['status'] >= 300 || (isset($result['error']) && !$operationEnvelope)) {
|
||||
$code = $result['error']['code'] ?? 'SERVICE_UNAVAILABLE';
|
||||
throw new RuntimeException(preg_match('/^[A-Z_]{3,64}$/D', $code) ? $code : 'SERVICE_UNAVAILABLE');
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
use RuntimeException;
|
||||
use think\facade\Db;
|
||||
|
||||
final class IamV2Events
|
||||
{
|
||||
public static function accept(string $raw, string $signature, string $eventId, string $secret, ?callable $revoke = null, ?callable $refresh = null, ?callable $locate = null, ?callable $generation = null): array
|
||||
{
|
||||
if (strlen($raw) > 65536 || strlen($secret) < 32 || !hash_equals('sha256=' . hash_hmac('sha256', $raw, $secret), $signature)) { throw new RuntimeException('FORBIDDEN'); }
|
||||
$event = json_decode($raw, true, 32, JSON_THROW_ON_ERROR);
|
||||
if (empty($event['employeeId']) || $eventId === '' || strlen($eventId) > 128 || $eventId !== ($event['id'] ?? '') || !in_array('zyt', (array) ($event['applicationIds'] ?? []), true)) { throw new RuntimeException('INVALID_EVENT'); }
|
||||
$occurredAt = (string) ($event['occurredAt'] ?? '');
|
||||
if (!preg_match('/^\d{4}-\d{2}-\d{2}T.*(Z|[+-][0-9]{2}:[0-9]{2})$/D', $occurredAt)) { throw new RuntimeException('INVALID_EVENT'); }
|
||||
$stamp = strtotime($occurredAt);
|
||||
if (!$stamp || $stamp > time() + 60) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$customRevoke = $revoke !== null;
|
||||
$revoke ??= fn(int $id) => IamV2Manager::revoke($id);
|
||||
$refresh ??= fn(int $id) => (new IamV2Manager())->binding($id, true);
|
||||
$generation ??= $customRevoke ? fn(int $id, int $upper) => $revoke($id) : fn(int $id, int $upper) => IamV2Source::revokeGeneration($id, $upper, (string) $event['employeeId']);
|
||||
$locate ??= static function (array $event): array {
|
||||
if (($event['eventType'] ?? '') === 'binding_revoked' && isset($event['externalAccountId'])) {
|
||||
if (!is_string($event['externalAccountId']) || !preg_match('/^[1-9][0-9]{0,9}$/D', $event['externalAccountId'])) { throw new RuntimeException('INVALID_EVENT'); }
|
||||
return [(int) $event['externalAccountId']];
|
||||
}
|
||||
$reply = (new IamV2Client())->call('GET', '/bindings?' . http_build_query(['employeeId' => $event['employeeId'], 'page' => 1, 'pageSize' => 100], '', '&', PHP_QUERY_RFC3986));
|
||||
if (($reply['total'] ?? 0) > 100) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
|
||||
$ids = [];
|
||||
foreach ($reply['items'] ?? [] as $item) {
|
||||
if (($item['binding']['employeeId'] ?? '') !== $event['employeeId'] || ($item['binding']['applicationId'] ?? '') !== 'zyt') { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
$external = (string) ($item['binding']['externalAccountId'] ?? '');
|
||||
if (!preg_match('/^[1-9][0-9]{0,9}$/D', $external)) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
$ids[] = (int) $external;
|
||||
}
|
||||
return $ids;
|
||||
};
|
||||
return Db::transaction(function () use ($event, $eventId, $raw, $revoke, $refresh, $locate, $generation) {
|
||||
$existing = Db::name('iam_v2_event')->where('event_id', $eventId)->lock(true)->find();
|
||||
if ($existing) {
|
||||
if (!hash_equals($existing['digest'], hash('sha256', $raw))) { throw new RuntimeException('INVALID_EVENT'); }
|
||||
return ['accepted' => true, 'duplicate' => true];
|
||||
}
|
||||
Db::name('iam_v2_event')->insert(['event_id' => $eventId, 'digest' => hash('sha256', $raw), 'received_at' => time()]);
|
||||
$rows = Db::name('iam_v2_binding')->where('employee_id', (string) $event['employeeId'])->lock(true)->select()->toArray();
|
||||
if (!$rows && ($event['eventType'] ?? '') !== 'source_binding_revoked') {
|
||||
foreach ($locate($event) as $id) {
|
||||
$row = Db::name('iam_v2_binding')->where('admin_id', $id)->find();
|
||||
if (!$row) { $refresh($id); $row = Db::name('iam_v2_binding')->where('admin_id', $id)->find(); }
|
||||
if ($row) { $rows[] = $row; }
|
||||
}
|
||||
}
|
||||
foreach ($rows as $row) {
|
||||
$bindingEvent = ($event['eventType'] ?? '') === 'binding_revoked'
|
||||
|| in_array($event['reason'] ?? '', ['iam.v2.unbind', 'iam.v2.rebind'], true);
|
||||
// ZYT is source-only in this rollout; target-derived revocation belongs to ERP.
|
||||
if (($event['eventType'] ?? '') === 'source_binding_revoked') { continue; }
|
||||
$upper = isset($event['bindingVersion']) ? (int) $event['bindingVersion'] : null;
|
||||
if ($bindingEvent && $upper !== null && ($upper < (int) $row['version'] || $row['employee_id'] !== $event['employeeId'])) { $generation((int) $row['admin_id'], $upper); continue; }
|
||||
if (!$bindingEvent || $upper === null) {
|
||||
// Durable outbox delivery may be old. Current central state wins over a stale generic event.
|
||||
// A failed lookup rolls back event receipt, so the durable outbox can retry.
|
||||
$current = $refresh((int) $row['admin_id']);
|
||||
if (($current['binding']['state'] ?? '') === 'verified' && ($current['employee']['status'] ?? '') === 'active'
|
||||
&& ($current['access']['allowed'] ?? false)) { continue; }
|
||||
}
|
||||
$updates = ['checked_at' => 0];
|
||||
// Personnel disable/entitlement events invalidate sessions, not the binding itself.
|
||||
// A versioned binding event carries the OLD generation as its revocation upper bound.
|
||||
if ($bindingEvent && $upper !== null && $upper > 0) {
|
||||
$updates['state'] = 'revoked'; $updates['version'] = max((int) $row['version'], $upper);
|
||||
}
|
||||
Db::name('iam_v2_binding')->where('admin_id', $row['admin_id'])->update($updates);
|
||||
if ($bindingEvent && $upper !== null) { $generation((int) $row['admin_id'], $upper); }
|
||||
else { $revoke((int) $row['admin_id']); }
|
||||
}
|
||||
return ['accepted' => true];
|
||||
});
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
use RuntimeException;
|
||||
use think\facade\Db;
|
||||
|
||||
final class IamV2Flow
|
||||
{
|
||||
public static function put(string $kind, string $secret, array $payload, int $ttl = 300): void
|
||||
{
|
||||
Db::name('iam_v2_flow')->insert(['flow_key' => hash('sha256', $kind . ':' . $secret), 'kind' => $kind,
|
||||
'payload' => json_encode($payload, JSON_THROW_ON_ERROR), 'expires_at' => time() + $ttl, 'consumed' => 0]);
|
||||
}
|
||||
public static function peek(string $kind, string $secret, string $sid): array
|
||||
{
|
||||
$row = Db::name('iam_v2_flow')->where('flow_key', hash('sha256', $kind . ':' . $secret))->find();
|
||||
if (!$row || $row['expires_at'] <= time() || (int) $row['consumed'] !== 0) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$p = json_decode($row['payload'], true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($p['sessionId'] ?? '') !== $sid) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
return $p;
|
||||
}
|
||||
public static function take(string $kind, string $secret, string $sid): array
|
||||
{
|
||||
return Db::transaction(function () use ($kind, $secret, $sid) {
|
||||
$key = hash('sha256', $kind . ':' . $secret);
|
||||
$row = Db::name('iam_v2_flow')->where('flow_key', $key)->lock(true)->find();
|
||||
if (!$row || $row['expires_at'] <= time() || (int) $row['consumed'] !== 0) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$p = json_decode($row['payload'], true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($p['sessionId'] ?? '') !== $sid) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
if (Db::name('iam_v2_flow')->where('flow_key', $key)->where('consumed', 0)->update(['consumed' => 1]) !== 1) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
return $p;
|
||||
});
|
||||
}
|
||||
public static function form(string $url, array $fields): string
|
||||
{
|
||||
$nonce = bin2hex(random_bytes(18));
|
||||
$escape = fn($s) => htmlspecialchars((string) $s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||
$inputs = '';
|
||||
foreach ($fields as $name => $value) { $inputs .= '<input type="hidden" name="' . $escape($name) . '" value="' . $escape($value) . '">'; }
|
||||
$origin = parse_url($url, PHP_URL_SCHEME) . '://' . parse_url($url, PHP_URL_HOST) . (parse_url($url, PHP_URL_PORT) ? ':' . parse_url($url, PHP_URL_PORT) : '');
|
||||
return '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; base-uri \'none\'; form-action ' . $escape($origin) . '; script-src \'nonce-' . $nonce . '\'"><title>正在验证身份</title><form method="post" action="' . $escape($url) . '">' . $inputs . '<button>继续</button></form><script nonce="' . $nonce . '">document.forms[0].submit()</script>';
|
||||
}
|
||||
}
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Db;
|
||||
use think\facade\Config;
|
||||
use app\adminapi\logic\auth\AdminLogic;
|
||||
|
||||
final class IamV2Manager
|
||||
{
|
||||
public function __construct(private ?IamV2Client $client = null) { $this->client ??= new IamV2Client(); }
|
||||
public function binding(int $id, bool $fresh = false): array
|
||||
{
|
||||
$row = Db::name('iam_v2_binding')->where('admin_id', $id)->find();
|
||||
if (!$fresh && $row && $row['checked_at'] > time() - 30) {
|
||||
$cached = json_decode($row['payload'], true, 32, JSON_THROW_ON_ERROR);
|
||||
$cached['checked_at'] = (int) $row['checked_at'];
|
||||
return $cached;
|
||||
}
|
||||
$result = $this->client->call('GET', '/bindings/by-external/' . $id);
|
||||
if (($result['binding']['externalAccountId'] ?? (string) $id) !== (string) $id) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
if ($result['binding'] ?? null) {
|
||||
$b = $result['binding']; $employee = $result['employee'] ?? [];
|
||||
if (($b['applicationId'] ?? '') !== (string) Config::get('iam.application_id', 'zyt')
|
||||
|| !is_int($b['version'] ?? null) || $b['version'] < 1
|
||||
|| !in_array($b['state'] ?? '', ['verified','revoked','pending','conflict'], true)
|
||||
|| empty($employee['id']) || ($b['employeeId'] ?? '') !== $employee['id'] || empty($employee['oidcSubject'])) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
}
|
||||
$state = $result['binding']['state'] ?? 'unlinked';
|
||||
$version = (int) ($result['binding']['version'] ?? 0);
|
||||
if ($row && $row['state'] === 'revoked' && $state === 'verified' && $version <= (int) $row['version']) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
if ($row && (int) $row['version'] > $version) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
$values = ['admin_id' => $id, 'employee_id' => $result['employee']['id'] ?? '', 'subject' => $result['employee']['oidcSubject'] ?? '',
|
||||
'state' => $state, 'version' => $version, 'payload' => json_encode($result, JSON_THROW_ON_ERROR), 'checked_at' => time()];
|
||||
if ($row) { Db::name('iam_v2_binding')->where('admin_id', $id)->update($values); }
|
||||
else { Db::name('iam_v2_binding')->insert($values); }
|
||||
$changed = $row && $row['state'] === 'verified' && (($row['employee_id'] ?? '') !== ($values['employee_id'] ?? '') || (int) $row['version'] !== $version);
|
||||
if ($state === 'revoked' || (($result['employee'] ?? null) && (($result['employee']['status'] ?? '') !== 'active' || !($result['access']['allowed'] ?? false)))) {
|
||||
self::revoke($id);
|
||||
} elseif ($changed) {
|
||||
IamV2Source::revokeGeneration($id, (int) $row['version'], (string) $row['employee_id']);
|
||||
}
|
||||
$result['checked_at'] = $values['checked_at'];
|
||||
return $result;
|
||||
}
|
||||
public static function revoke(int $id): void
|
||||
{
|
||||
IamV2Source::revokeAdmin($id);
|
||||
foreach (Db::name('admin_session')->where('admin_id', $id)->column('token') as $token) { AdminLogic::expireToken($token); }
|
||||
}
|
||||
public function assertLinked(int $id): array
|
||||
{
|
||||
$b = $this->binding($id, true);
|
||||
if (($b['binding']['state'] ?? '') !== 'verified') { throw new RuntimeException('NOT_LINKED'); }
|
||||
if (($b['employee']['status'] ?? '') !== 'active' || !($b['access']['allowed'] ?? false)) { throw new RuntimeException('NOT_AUTHORIZED'); }
|
||||
return $b;
|
||||
}
|
||||
public function accounts(array $query, int $actor): array
|
||||
{
|
||||
$page = max(1, (int) ($query['page'] ?? 1)); $size = min(20, max(1, (int) ($query['pageSize'] ?? 20)));
|
||||
$db = Db::name('admin')->whereNull('delete_time');
|
||||
$visible = IamV2Source::visibleIds($actor);
|
||||
if ($visible !== null) { $db->whereIn('id', $visible ?: [0]); }
|
||||
if (($query['q'] ?? '') !== '') { $db->whereLike('account|name', '%' . mb_substr((string) $query['q'], 0, 64) . '%'); }
|
||||
if (($query['state'] ?? '') !== '') {
|
||||
$ids = Db::name('iam_v2_binding')->where('state', (string) $query['state'])->column('admin_id');
|
||||
if ($query['state'] === 'unknown') { $db->whereNotIn('id', Db::name('iam_v2_binding')->column('admin_id')); }
|
||||
else { $db->whereIn('id', $ids ?: [0]); }
|
||||
}
|
||||
$total = (clone $db)->count();
|
||||
$items = $db->field('id,account,name,disable,root')->page($page, $size)->select()->toArray();
|
||||
// Resolve department labels only for already-scoped rows, never broaden the account query.
|
||||
$departmentNames = [];
|
||||
if ($items !== []) {
|
||||
$links = Db::name('admin_dept')->whereIn('admin_id', array_column($items, 'id'))
|
||||
->field('admin_id,dept_id')->order('dept_id', 'asc')->select()->toArray();
|
||||
$ids = array_values(array_unique(array_column($links, 'dept_id')));
|
||||
$labels = $ids ? Db::name('dept')->whereIn('id', $ids)->whereNull('delete_time')->column('name', 'id') : [];
|
||||
foreach ($links as $link) {
|
||||
if (isset($labels[$link['dept_id']])) { $departmentNames[$link['admin_id']][$link['dept_id']] = (string) $labels[$link['dept_id']]; }
|
||||
}
|
||||
}
|
||||
foreach ($items as &$r) {
|
||||
$r['dept_names'] = array_values($departmentNames[$r['id']] ?? []);
|
||||
try { $r['iam'] = $this->binding((int) $r['id']); $r['iam']['state'] = $r['iam']['binding']['state'] ?? 'unlinked'; }
|
||||
catch (\Throwable $e) {
|
||||
$last = Db::name('iam_v2_binding')->where('admin_id', $r['id'])->value('checked_at');
|
||||
$reason = in_array($e->getMessage(), ['BINDING_CONFLICT','ACCOUNT_MISMATCH','ACCOUNT_DISABLED','NOT_AUTHORIZED'], true)
|
||||
? $e->getMessage() : 'SERVICE_UNAVAILABLE';
|
||||
$r['iam'] = ['state' => 'unknown', 'error' => $reason, 'access' => ['allowed' => null, 'reason' => $reason],
|
||||
'checked_at' => (int) $last > 0 ? (int) $last : null];
|
||||
}
|
||||
}
|
||||
unset($r);
|
||||
return ['items' => $items, 'total' => $total];
|
||||
}
|
||||
public static function input(array $input): array
|
||||
{
|
||||
$kind = (string) ($input['kind'] ?? '');
|
||||
if (!in_array($kind, ['bind', 'create_and_bind', 'unbind', 'rebind', 'reconcile'], true)) { throw new RuntimeException('INVALID_OPERATION'); }
|
||||
$id = (int) ($input['user_id'] ?? 0);
|
||||
if ($id < 1 || strlen(trim((string) ($input['reason'] ?? ''))) < 3) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
$out = ['kind' => $kind, 'externalAccountId' => (string) $id, 'reason' => mb_strcut(trim($input['reason']), 0, 500, 'UTF-8')];
|
||||
if (isset($input['employee_id'])) { $out['employeeId'] = (string) $input['employee_id']; }
|
||||
if (isset($input['expected_version'])) { $out['expectedVersion'] = (int) $input['expected_version']; }
|
||||
if (in_array($kind, ['unbind','rebind'], true) && !isset($out['expectedVersion'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
if ($kind === 'create_and_bind') {
|
||||
$n = $input['new_employee'] ?? [];
|
||||
$out['newEmployee'] = ['username' => (string) ($n['username'] ?? ''), 'displayName' => (string) ($n['display_name'] ?? '')];
|
||||
if (!preg_match('/^[A-Za-z0-9_.@-]{3,64}$/D', $out['newEmployee']['username']) || trim($out['newEmployee']['displayName']) === '') { throw new RuntimeException('INVALID_INPUT'); }
|
||||
if (!empty($n['email'])) {
|
||||
if (!filter_var($n['email'], FILTER_VALIDATE_EMAIL)) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
$out['newEmployee']['email'] = $n['email'];
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
public static function cap(string $kind): string { return ['create_and_bind' => 'create', 'reconcile' => 'bind'][$kind] ?? $kind; }
|
||||
public function operation(array $session, array $input, string $requestId): array
|
||||
{
|
||||
$body = self::input($input); $target = (int) $body['externalAccountId']; $cap = self::cap($body['kind']);
|
||||
IamV2Source::authorize($session, $cap, [$target], true, true);
|
||||
$current = $this->binding($target, true); $caps = ['iam:' . $cap];
|
||||
if ($body['kind'] === 'create_and_bind' && ($current['binding']['state'] ?? '') === 'revoked') {
|
||||
if (!isset($body['expectedVersion'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
IamV2Source::authorize($session, 'rebind', [$target], true, true); $caps[] = 'iam:rebind';
|
||||
}
|
||||
$body['proof'] = IamV2Source::proof($session, 'management', [$target], $caps, null, ['protectedReviewEligible' => IamV2Source::reviewOperator((int) $session['admin_id'])]);
|
||||
$op = $this->client->call('POST', '/operations', $body, $requestId);
|
||||
$op = $this->reviewLink($op);
|
||||
$this->remember('operation', (string) $op['id'], $session, [$target], $caps);
|
||||
if (($op['status'] ?? '') === 'succeeded') { $this->binding($target, true); }
|
||||
return $op;
|
||||
}
|
||||
private function reviewLink(array $operation): array
|
||||
{
|
||||
if (!isset($operation['reviewUrl'])) { return $operation; }
|
||||
$origin = IamV2Client::origin((string) Config::get('iam.portal_url'));
|
||||
$parts = parse_url((string) $operation['reviewUrl']);
|
||||
$fixed = parse_url($origin);
|
||||
if (!$parts || ($parts['scheme'] ?? '') !== 'https' || ($parts['host'] ?? '') !== $fixed['host']
|
||||
|| ($parts['port'] ?? 443) !== ($fixed['port'] ?? 443) || ($parts['path'] ?? '') !== '/admin/iam/review'
|
||||
|| isset($parts['user']) || isset($parts['pass']) || isset($parts['fragment'])) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
parse_str($parts['query'] ?? '', $query);
|
||||
if (count($query) !== 1 || ($query['request'] ?? null) !== ($operation['id'] ?? null)) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
return $operation;
|
||||
}
|
||||
public function remember(string $kind, string $id, array $session, array $targets, array $caps = []): void
|
||||
{
|
||||
$key = hash('sha256', $kind . ':' . $id);
|
||||
$existing = Db::name('iam_v2_resource')->where('resource_key', $key)->find();
|
||||
if ($existing) { if ((int) $existing['actor_id'] !== (int) $session['admin_id']) { throw new RuntimeException('FORBIDDEN'); } return; }
|
||||
Db::name('iam_v2_resource')->insert(['resource_key' => $key, 'kind' => $kind, 'external_id' => $id, 'actor_id' => $session['admin_id'],
|
||||
'payload' => json_encode(['targets' => $targets, 'capabilities' => $caps]), 'created_at' => time()]);
|
||||
}
|
||||
public function owned(string $kind, string $id, array $session): array
|
||||
{
|
||||
$r = Db::name('iam_v2_resource')->where('resource_key', hash('sha256', $kind . ':' . $id))->where('actor_id', $session['admin_id'])->find();
|
||||
if (!$r) { throw new RuntimeException('FORBIDDEN'); }
|
||||
$payload = json_decode($r['payload'], true, 32, JSON_THROW_ON_ERROR);
|
||||
IamV2Source::scope((int) $session['admin_id'], $payload['targets']);
|
||||
return $payload;
|
||||
}
|
||||
public function preflight(array $session, array $items): array
|
||||
{
|
||||
if (!$items || count($items) > 100) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
IamV2Source::authorize($session, 'batch'); $mapped = []; $targets = []; $caps = ['iam:batch']; $indexMap = []; $review = []; $itemCaps = [];
|
||||
foreach ($items as $index => $input) {
|
||||
try {
|
||||
$item = self::input($input); $id = (int) $item['externalAccountId']; $cap = self::cap($item['kind']);
|
||||
IamV2Source::authorize($session, $cap, [$id]);
|
||||
$held = ['iam:' . $cap];
|
||||
if ($item['kind'] === 'create_and_bind' && (($this->binding($id, true)['binding']['state'] ?? '') === 'revoked')) {
|
||||
if (!isset($item['expectedVersion'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
IamV2Source::authorize($session, 'rebind', [$id]); $held[] = 'iam:rebind';
|
||||
}
|
||||
$indexMap[] = (int) $index; $mapped[] = $item; $targets[] = $id; $itemCaps[] = $held; $caps = array_merge($caps, $held);
|
||||
} catch (RuntimeException $e) {
|
||||
$review[] = ['index' => (int) $index, 'externalAccountId' => (string) ($input['user_id'] ?? ''),
|
||||
'status' => $e->getMessage() === 'PROTECTED_ACCOUNT_REVIEW_REQUIRED' ? 'review' : 'invalid', 'message' => $e->getMessage()];
|
||||
}
|
||||
}
|
||||
if (!$mapped) { return ['previewId' => null, 'items' => $review, 'expiresAt' => time()]; }
|
||||
$r = $this->client->call('POST', '/batch/preflight', ['items' => $mapped,
|
||||
'proof' => IamV2Source::proof($session, 'management', $targets, array_values(array_unique($caps)))]);
|
||||
$this->remember('preview', (string) $r['previewId'], $session, $targets, $caps);
|
||||
$resource = hash('sha256', 'preview:' . $r['previewId']);
|
||||
$ready = [];
|
||||
foreach ($r['items'] as &$item) {
|
||||
$centralIndex = (int) $item['index'];
|
||||
if (!array_key_exists($centralIndex, $indexMap)) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
$item['index'] = $indexMap[$centralIndex];
|
||||
if ($item['status'] === 'ready') { $ready[] = $item['index']; }
|
||||
}
|
||||
unset($item);
|
||||
Db::name('iam_v2_resource')->where('resource_key', $resource)->update(['payload' => json_encode([
|
||||
'targets' => $targets, 'capabilities' => $caps, 'indexMap' => $indexMap, 'ready' => $ready, 'itemCaps' => $itemCaps])]);
|
||||
$r['items'] = array_merge($r['items'], $review);
|
||||
usort($r['items'], fn($a, $b) => $a['index'] <=> $b['index']); return $r;
|
||||
}
|
||||
public function batch(array $session, string $preview, array $indexes, string $key): array
|
||||
{
|
||||
$scope = $this->owned('preview', $preview, $session);
|
||||
$indexes = array_values(array_unique(array_map('intval', $indexes)));
|
||||
if (!$indexes || array_diff($indexes, $scope['ready'] ?? [])) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
$indexes = array_map(fn($i) => array_search($i, $scope['indexMap'], true), $indexes);
|
||||
$targets = array_map(fn($i) => $scope['targets'][$i], $indexes); $caps = ['iam:batch']; $itemCaps = [];
|
||||
foreach ($indexes as $i) { $itemCaps[$i] = $scope['itemCaps'][$i] ?? $scope['capabilities']; $caps = array_merge($caps, $itemCaps[$i]); }
|
||||
$caps = array_values(array_unique($caps));
|
||||
foreach ($caps as $cap) { IamV2Source::authorize($session, substr($cap, 4), $targets); }
|
||||
$r = $this->client->call('POST', '/batch', ['previewId' => $preview, 'indexes' => $indexes,
|
||||
'proof' => IamV2Source::proof($session, 'management', $targets, $caps)], $key);
|
||||
$this->remember('job', (string) $r['id'], $session, $targets, $caps);
|
||||
Db::name('iam_v2_resource')->where('resource_key', hash('sha256', 'job:' . $r['id']))->update(['payload' => json_encode([
|
||||
'targets' => $targets, 'capabilities' => $caps, 'itemCaps' => $itemCaps, 'centralIndexes' => $indexes])]);
|
||||
return $r;
|
||||
}
|
||||
/** Public retry indexes are job.items positions, not original central preview indexes. */
|
||||
public static function retrySelection(array $job, array $positions = []): array
|
||||
{
|
||||
$items = $job['items'] ?? []; $central = $job['indexes'] ?? [];
|
||||
if ($positions === []) { $positions = array_keys($items); }
|
||||
$indexes = []; $targets = []; $caps = ['iam:batch'];
|
||||
foreach (array_unique($positions) as $position) {
|
||||
if (!is_int($position) || !isset($items[$position], $central[$position])) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
$item = $items[$position];
|
||||
if (!in_array($item['status'] ?? '', ['failed', 'pending'], true)) { continue; }
|
||||
$indexes[] = $central[$position]; $targets[] = (int) $item['externalAccountId']; $caps[] = 'iam:' . self::cap($item['kind']);
|
||||
}
|
||||
return ['indexes' => $indexes, 'targets' => $targets, 'capabilities' => array_values(array_unique($caps))];
|
||||
}
|
||||
public function result(array $session, string $kind, string $id, bool $retry = false, array $indexes = []): array
|
||||
{
|
||||
$scope = $this->owned($kind, $id, $session); IamV2Source::authorize($session, 'read', [], false);
|
||||
$path = ($kind === 'job' ? '/jobs/' : '/operations/') . rawurlencode($id);
|
||||
if ($retry) {
|
||||
$job = $this->client->call('GET', $path);
|
||||
// The saved mapping prevents the central endpoint changing this operation's target set.
|
||||
if (!isset($job['indexes'])) { $job['indexes'] = $scope['centralIndexes'] ?? []; }
|
||||
$selected = self::retrySelection($job, $indexes);
|
||||
if (!$selected['indexes']) { return $job; }
|
||||
if (array_diff($selected['targets'], array_map('intval', $scope['targets']))) { throw new RuntimeException('FORBIDDEN'); }
|
||||
foreach ($selected['indexes'] as $i) { $selected['capabilities'] = array_merge($selected['capabilities'], $scope['itemCaps'][$i] ?? []); }
|
||||
$selected['capabilities'] = array_values(array_unique($selected['capabilities']));
|
||||
foreach ($selected['capabilities'] as $cap) { IamV2Source::authorize($session, substr($cap, 4), $selected['targets']); }
|
||||
$r = $this->client->call('POST', $path . '/retry', ['indexes' => $selected['indexes'],
|
||||
'proof' => IamV2Source::proof($session, 'management', $selected['targets'], $selected['capabilities'])]);
|
||||
$scope['targets'] = $selected['targets'];
|
||||
} else { $r = $this->client->call('GET', $path); }
|
||||
foreach ($scope['targets'] as $target) { $this->binding((int) $target, true); }
|
||||
return $kind === 'operation' ? $this->reviewLink($r) : $r;
|
||||
}
|
||||
}
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Db;
|
||||
use think\facade\Config;
|
||||
use app\adminapi\logic\auth\AuthLogic;
|
||||
use app\common\cache\AdminAccountSafeCache;
|
||||
|
||||
/** Browser source sessions are separate from legacy account/terminal shared business tokens. */
|
||||
final class IamV2Source
|
||||
{
|
||||
public const COOKIE = 'ZYT_IAM_V2_SESSION';
|
||||
public static function requirePurpose(string $purpose): void
|
||||
{
|
||||
$feature = in_array($purpose, ['management', 'self_link', 'password_setup'], true) ? 'management' : ($purpose === 'launch' ? 'launch' : null);
|
||||
if ($feature !== null && !IamV2Client::feature($feature)) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
}
|
||||
public static function enroll(string $token, string $method, bool $cookie = true, ?int $authTime = null): array
|
||||
{
|
||||
if (!in_array($method, ['password', 'wecom', 'oidc', 'iam_launch'], true)) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
if (in_array($method, ['oidc', 'iam_launch'], true) && $authTime !== null && ($authTime < 0 || $authTime > time() + 60)) { throw new RuntimeException('INVALID_AUTHENTICATION'); }
|
||||
$legacy = Db::name('admin_session')->where('token', $token)->where('expire_time', '>', time())->find();
|
||||
if (!$legacy) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
$admin = self::admin((int) $legacy['admin_id']);
|
||||
$old = (string) ($_COOKIE[self::COOKIE] ?? '');
|
||||
if ($old !== '') { self::revokeSession($old); }
|
||||
$binding = Db::name('iam_v2_binding')->where('admin_id', $legacy['admin_id'])->where('state', 'verified')->find();
|
||||
$sid = bin2hex(random_bytes(32));
|
||||
$row = ['session_id' => $sid, 'admin_id' => (int) $legacy['admin_id'], 'business_session_id' => $legacy['id'],
|
||||
'token_hash' => hash('sha256', $token), 'account_stamp' => self::accountStamp($admin), 'auth_method' => $method, 'auth_time' => in_array($method, ['oidc', 'iam_launch'], true) ? max(0, $authTime ?? 0) : time(),
|
||||
'version' => 1, 'revoked' => 0, 'binding_version' => (int) ($binding['version'] ?? 0), 'employee_id' => $binding['employee_id'] ?? '', 'expires_at' => min((int) $legacy['expire_time'], time() + 43200)];
|
||||
Db::name('iam_v2_source_session')->insert($row);
|
||||
if ($cookie) {
|
||||
setcookie(self::COOKIE, $sid, ['expires' => $row['expires_at'], 'path' => '/adminapi', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
|
||||
$_COOKIE[self::COOKIE] = $sid;
|
||||
}
|
||||
return $row;
|
||||
}
|
||||
private static function accountStamp(array $admin): string
|
||||
{
|
||||
return hash('sha256', json_encode([$admin['account'], $admin['password'], $admin['work_wechat_userid'] ?? '', (int) $admin['root']], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
public static function admin(int $id): array
|
||||
{
|
||||
$a = Db::name('admin')->where('id', $id)->find();
|
||||
if (!$a || (int) $a['disable'] !== 0 || !empty($a['delete_time'])) { throw new RuntimeException('ACCOUNT_DISABLED'); }
|
||||
return $a;
|
||||
}
|
||||
public static function current(string $token, bool $recent = false): array
|
||||
{
|
||||
$s = self::check((string) ($_COOKIE[self::COOKIE] ?? ''));
|
||||
if (!hash_equals($s['token_hash'], hash('sha256', $token))) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
if ($recent && $s['auth_time'] < time() - 300) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
return $s;
|
||||
}
|
||||
public static function check(string $id, ?int $version = null): array
|
||||
{
|
||||
$s = Db::name('iam_v2_source_session')->where('session_id', $id)->find();
|
||||
if (!$s || (int) $s['revoked'] !== 0 || $s['expires_at'] <= time() || ($version !== null && (int) $s['version'] !== $version)) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
$admin = self::admin((int) $s['admin_id']);
|
||||
if (!hash_equals($s['account_stamp'], self::accountStamp($admin))) { self::revokeSession($id); throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
$legacy = Db::name('admin_session')->where('id', $s['business_session_id'])->find();
|
||||
if (!$legacy || $legacy['expire_time'] <= time() || (int) $legacy['admin_id'] !== (int) $s['admin_id'] || !hash_equals($s['token_hash'], hash('sha256', $legacy['token']))) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
if ((int) ($s['binding_version'] ?? 0) > 0) {
|
||||
$binding = Db::name('iam_v2_binding')->where('admin_id', $s['admin_id'])->find();
|
||||
if ($binding && ($binding['state'] === 'revoked' || (int) $binding['version'] > (int) $s['binding_version'] || $binding['employee_id'] !== $s['employee_id'])) {
|
||||
self::revokeSession($id); throw new RuntimeException('REAUTH_REQUIRED');
|
||||
}
|
||||
}
|
||||
return $s;
|
||||
}
|
||||
/** Service callback: local-only live authorization, safe while central holds its state lock. */
|
||||
public static function liveStatus(string $id, int $version, string $purpose = '', array $targets = []): array
|
||||
{
|
||||
self::requirePurpose($purpose);
|
||||
$s = self::check($id, $version);
|
||||
$out = ['active' => true, 'actorLocalId' => (string) $s['admin_id'], 'sessionId' => $s['session_id'], 'sessionVersion' => (int) $s['version'],
|
||||
'authMethod' => $s['auth_method'], 'authTime' => (int) $s['auth_time'], 'expiresAt' => (int) $s['expires_at']];
|
||||
if ($purpose !== 'management') { return $out + ['protectedAccount' => self::protectedAccount((int) $s['admin_id'])]; }
|
||||
if ($s['auth_time'] < time() - 300) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
if (!$targets || count($targets) > 100) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
foreach ($targets as $target) {
|
||||
if (!is_string($target) || !preg_match('/^[1-9][0-9]{0,9}$/D', $target)) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
}
|
||||
$caps = self::capabilities((int) $s['admin_id']);
|
||||
if (!$caps) { throw new RuntimeException('FORBIDDEN'); }
|
||||
self::scope((int) $s['admin_id'], $targets);
|
||||
$protected = false;
|
||||
foreach ($targets as $target) { self::admin((int) $target); $protected = self::protectedAccount((int) $target) || $protected; }
|
||||
$eligible = count($targets) === 1 && self::reviewOperator((int) $s['admin_id']);
|
||||
if ($protected && !$eligible) { throw new RuntimeException('PROTECTED_ACCOUNT_REVIEW_REQUIRED'); }
|
||||
return $out + ['purpose' => 'management', 'capabilities' => array_map(fn($c) => 'iam:' . $c, $caps),
|
||||
'targetLocalIds' => $targets, 'protectedAccount' => $protected, 'protectedReviewEligible' => $eligible];
|
||||
}
|
||||
public static function reauth(string $token, string $password): array
|
||||
{
|
||||
$legacy = Db::name('admin_session')->where('token', $token)->where('expire_time', '>', time())->find();
|
||||
if (!$legacy || $password === '' || strlen($password) > 256) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
$a = self::admin((int) $legacy['admin_id']);
|
||||
$limiter = new AdminAccountSafeCache();
|
||||
if (!$limiter->isSafe()) { throw new RuntimeException('RATE_LIMITED'); }
|
||||
// Deliberately does NOT invoke LoginValidate's local-debug password bypass.
|
||||
if (!hash_equals((string) $a['password'], create_password($password, Config::get('project.unique_identification')))) {
|
||||
$limiter->record(); throw new RuntimeException('REAUTH_REQUIRED');
|
||||
}
|
||||
$limiter->relieve(); return self::enroll($token, 'password');
|
||||
}
|
||||
public static function capabilities(int $id): array
|
||||
{
|
||||
$admin = self::admin($id);
|
||||
$all = ['read', 'bind', 'create', 'unbind', 'rebind', 'batch'];
|
||||
if ((int) $admin['root'] === 1) { return $all; }
|
||||
$perms = AuthLogic::getAuthByAdminId($id);
|
||||
return array_values(array_filter($all, fn($p) => in_array('iamV2/' . $p, $perms, true)));
|
||||
}
|
||||
public static function reviewOperator(int $id): bool
|
||||
{
|
||||
$a = self::admin($id);
|
||||
if ((int) $a['root'] === 1) { return true; }
|
||||
$roles = Db::name('admin_role')->where('admin_id', $id)->column('role_id');
|
||||
return $roles && Db::name('system_role')->whereIn('id', $roles)->whereIn('name', ['管理员', '系统管理员', '超级管理员'])->whereNull('delete_time')->count() > 0;
|
||||
}
|
||||
public static function protectedAccount(int $id): bool
|
||||
{
|
||||
return self::reviewOperator($id) || count(array_intersect(self::capabilities($id), ['bind','create','unbind','rebind','batch'])) > 0;
|
||||
}
|
||||
public static function visibleIds(int $id): ?array
|
||||
{
|
||||
$a = self::admin($id);
|
||||
$a['role_id'] = Db::name('admin_role')->where('admin_id', $id)->column('role_id');
|
||||
return \app\common\service\DataScope\DataScopeService::getVisibleAdminIds($id, $a);
|
||||
}
|
||||
public static function scope(int $actor, array $targets): void
|
||||
{
|
||||
$visible = self::visibleIds($actor);
|
||||
if ($visible !== null && array_diff(array_map('intval', $targets), $visible)) { throw new RuntimeException('FORBIDDEN'); }
|
||||
}
|
||||
public static function authorize(array $session, string $capability, array $targets = [], bool $recent = true, bool $protectedReview = false): void
|
||||
{
|
||||
if (!in_array($capability, self::capabilities((int) $session['admin_id']), true)) { throw new RuntimeException('FORBIDDEN'); }
|
||||
if ($recent && $session['auth_time'] < time() - 300) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
self::scope((int) $session['admin_id'], $targets);
|
||||
foreach ($targets as $id) {
|
||||
$target = self::admin((int) $id);
|
||||
// Single-target high-privilege requests may reach central review, never bypass it.
|
||||
if (self::protectedAccount((int) $id) && !($protectedReview && count($targets) === 1 && self::reviewOperator((int) $session['admin_id']))) {
|
||||
throw new RuntimeException('PROTECTED_ACCOUNT_REVIEW_REQUIRED');
|
||||
}
|
||||
}
|
||||
}
|
||||
public static function proof(array $session, string $purpose, array $targets = [], array $capabilities = [], ?string $transaction = null, array $extra = []): string
|
||||
{
|
||||
self::requirePurpose($purpose);
|
||||
self::check($session['session_id'], (int) $session['version']);
|
||||
$secret = bin2hex(random_bytes(32));
|
||||
$payload = ['applicationId' => (string) Config::get('iam.application_id', 'zyt'), 'actorLocalId' => (string) $session['admin_id'],
|
||||
'sessionId' => $session['session_id'], 'sessionVersion' => (int) $session['version'], 'authMethod' => $session['auth_method'],
|
||||
'authTime' => (int) $session['auth_time'], 'expiresAt' => time() + 60, 'capabilities' => $capabilities,
|
||||
'targetLocalIds' => array_map('strval', $targets), 'protectedAccount' => count(array_filter($targets, fn($id) => self::protectedAccount((int) $id))) > 0, 'transactionId' => $transaction];
|
||||
$payload += array_intersect_key($extra, array_flip(['oidcNonce', 'state', 'protectedReviewEligible']));
|
||||
Db::name('iam_v2_proof')->insert(['proof_hash' => hash('sha256', $secret), 'purpose' => $purpose, 'session_id' => $session['session_id'],
|
||||
'payload' => json_encode($payload, JSON_THROW_ON_ERROR), 'expires_at' => time() + 60, 'consumed' => 0]);
|
||||
return $secret;
|
||||
}
|
||||
public static function introspect(string $proof, string $purpose, ?string $transaction = null): array
|
||||
{
|
||||
self::requirePurpose($purpose);
|
||||
// The central Go attestor serializes an absent transaction as an empty string.
|
||||
$transaction = $transaction === '' ? null : $transaction;
|
||||
return Db::transaction(function () use ($proof, $purpose, $transaction) {
|
||||
$hash = hash('sha256', $proof);
|
||||
$r = Db::name('iam_v2_proof')->where('proof_hash', $hash)->lock(true)->find();
|
||||
if (!$r || $r['purpose'] !== $purpose || $r['expires_at'] <= time() || (int) $r['consumed'] !== 0) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$p = json_decode($r['payload'], true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($p['transactionId'] ?? null) !== $transaction) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$session = self::check($p['sessionId'], (int) $p['sessionVersion']);
|
||||
$p['protectedReviewEligible'] = ($p['protectedReviewEligible'] ?? false) === true
|
||||
&& count($p['targetLocalIds']) === 1 && self::reviewOperator((int) $session['admin_id']);
|
||||
foreach ($p['capabilities'] as $cap) {
|
||||
if (!str_starts_with($cap, 'iam:')) { throw new RuntimeException('FORBIDDEN'); }
|
||||
self::authorize($session, substr($cap, 4), $p['targetLocalIds'], true, ($p['protectedReviewEligible'] ?? false) === true && count($p['targetLocalIds']) === 1);
|
||||
}
|
||||
// Target protection can change during the proof's short lifetime. Recompute it.
|
||||
$p['protectedAccount'] = count(array_filter($p['targetLocalIds'], fn($id) => self::protectedAccount((int) $id))) > 0;
|
||||
if (Db::name('iam_v2_proof')->where('proof_hash', $hash)->where('consumed', 0)->update(['consumed' => 1]) !== 1) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
return ['active' => true] + $p;
|
||||
});
|
||||
}
|
||||
public static function revokeSession(string $id): void
|
||||
{
|
||||
Db::name('iam_v2_source_session')->where('session_id', $id)->inc('version')->update(['revoked' => 1]);
|
||||
}
|
||||
public static function revokeGeneration(int $id, int $upper, ?string $employeeId = null): void
|
||||
{
|
||||
$query = Db::name('iam_v2_source_session')->where('admin_id', $id)->where('binding_version', '<=', $upper);
|
||||
if ($employeeId !== null) { $query->where(function ($q) use ($employeeId) { $q->where('employee_id', $employeeId)->whereOr('binding_version', 0); }); }
|
||||
$sessions = $query->select()->toArray();
|
||||
foreach ($sessions as $s) { self::revokeSession($s['session_id']); }
|
||||
foreach ($sessions as $s) {
|
||||
$newer = Db::name('iam_v2_source_session')->where('token_hash', $s['token_hash'])->where('revoked', 0)->where('expires_at', '>', time())->find();
|
||||
if ($newer) { continue; }
|
||||
$legacy = Db::name('admin_session')->where('id', $s['business_session_id'])->find();
|
||||
if ($legacy && hash_equals($s['token_hash'], hash('sha256', $legacy['token']))) { \app\adminapi\logic\auth\AdminLogic::expireToken($legacy['token']); }
|
||||
}
|
||||
}
|
||||
public static function revokeAdmin(int $id): void
|
||||
{
|
||||
Db::name('iam_v2_source_session')->where('admin_id', $id)->where('revoked', 0)->inc('version')->update(['revoked' => 1]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
use app\adminapi\logic\LoginLogic;
|
||||
use app\adminapi\logic\auth\AdminLogic;
|
||||
use app\adminapi\service\AdminTokenService;
|
||||
use app\adminapi\service\iam\{IamAccountProvisioner, IamOidcClient};
|
||||
use app\common\enum\AdminTerminalEnum;
|
||||
use app\common\model\auth\Admin;
|
||||
use app\common\service\FileService;
|
||||
|
||||
/** ZYT target accepts only the person's own IAM admin/portal source, never ERP. */
|
||||
final class IamV2Target
|
||||
{
|
||||
public const COOKIE = 'ZYT_IAM_V2_TARGET';
|
||||
private array $settings;
|
||||
public function __construct(private ?IamV2Client $client = null, private $resolve = null, private $login = null)
|
||||
{
|
||||
$this->settings = (array) Config::get('iam');
|
||||
if (!IamV2Client::feature('launch', $this->settings)) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
$this->client ??= new IamV2Client();
|
||||
$this->resolve ??= fn(array $result) => $this->resolveAdmin($result);
|
||||
$this->login ??= function (int $id, array $authentication): array {
|
||||
$authTime = self::authTime($authentication['authTime'] ?? null);
|
||||
$result = $this->loginVerifiedAdmin($id);
|
||||
IamV2Source::enroll($result['token'], 'iam_launch', true, $authTime);
|
||||
return $result;
|
||||
};
|
||||
}
|
||||
/** Only exchange's verified, one-time IAM ticket may reach this session issuer. */
|
||||
private function loginVerifiedAdmin(int $id): array
|
||||
{
|
||||
return Db::transaction(static function () use ($id): array {
|
||||
$admin = Admin::where('id', $id)->lock(true)->findOrEmpty();
|
||||
if ($admin->isEmpty() || (int) $admin['disable'] !== 0 || !empty($admin['delete_time'])) {
|
||||
throw new RuntimeException('ACCOUNT_DISABLED');
|
||||
}
|
||||
$admin->login_time = time();
|
||||
$admin->login_ip = request()->ip();
|
||||
$admin->save();
|
||||
$adminInfo = AdminTokenService::setToken($admin->id, AdminTerminalEnum::PC, $admin->multipoint_login);
|
||||
if (!$adminInfo || empty($adminInfo['token'])) { throw new RuntimeException('ACCOUNT_DISABLED'); }
|
||||
$avatar = $admin->avatar ?: Config::get('project.default_image.admin_avatar');
|
||||
return [
|
||||
'name' => $adminInfo['name'],
|
||||
'avatar' => FileService::getFileUrl($avatar),
|
||||
'role_name' => $adminInfo['role_name'],
|
||||
'token' => $adminInfo['token'],
|
||||
'is_paw' => $admin->is_paw ?? 1,
|
||||
'need_bind_work_wechat' => LoginLogic::adminMustBindWorkWechat([
|
||||
'root' => (int) ($admin->root ?? 0),
|
||||
'work_wechat_userid' => (string) ($admin->work_wechat_userid ?? ''),
|
||||
]),
|
||||
];
|
||||
});
|
||||
}
|
||||
public static function authTime($value): int
|
||||
{
|
||||
$time = is_int($value) ? $value : (is_string($value) ? strtotime($value) : false);
|
||||
if (!$time || $time < 0 || $time > time() + 60) { throw new RuntimeException('INVALID_AUTHENTICATION'); }
|
||||
return $time;
|
||||
}
|
||||
private function registered(string $source): string
|
||||
{
|
||||
$sources = $this->settings['v2_sources'] ?? [];
|
||||
if (!in_array($source, ['iam-admin', 'iam-portal'], true) || !is_array($sources) || !isset($sources[$source])) { throw new RuntimeException('NOT_AUTHORIZED'); }
|
||||
return IamV2Client::https((string) $sources[$source]);
|
||||
}
|
||||
public static function existing(string $token, string $sourceSession = ''): ?int
|
||||
{
|
||||
$id = null;
|
||||
if ($token !== '') {
|
||||
$legacy = Db::name('admin_session')->where('token', $token)->where('expire_time', '>', time())->find();
|
||||
if (!$legacy) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
IamV2Source::admin((int) $legacy['admin_id']); $id = (int) $legacy['admin_id'];
|
||||
}
|
||||
if ($sourceSession !== '') {
|
||||
try { $session = IamV2Source::check($sourceSession); } catch (RuntimeException $e) { $session = null; }
|
||||
if ($session) {
|
||||
if ($id !== null && $id !== (int) $session['admin_id']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$id = (int) $session['admin_id'];
|
||||
}
|
||||
}
|
||||
return $id;
|
||||
}
|
||||
public function prepare(string $source, string $intent, string $token, string $sourceSession = ''): array
|
||||
{
|
||||
$registered = $this->registered($source);
|
||||
if (!preg_match('/^[A-Za-z0-9_-]{32,256}$/D', $intent)) { throw new RuntimeException('INVALID_REQUEST'); }
|
||||
$existing = self::existing($token, $sourceSession);
|
||||
$browser = bin2hex(random_bytes(32)); $state = bin2hex(random_bytes(32)); $verifier = bin2hex(random_bytes(32));
|
||||
$tx = $this->client->call('POST', '/launch-transactions', ['sourceApplicationId' => $source, 'stateHash' => hash('sha256', $state),
|
||||
'codeChallenge' => rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=')]);
|
||||
$id = $tx['transactionId'] ?? '';
|
||||
if (!is_string($id) || !preg_match('/^[A-Za-z0-9_-]{1,128}$/D', $id)) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
$actual = parse_url((string) ($tx['sourceContinueUrl'] ?? '')); $fixed = parse_url($registered);
|
||||
if (!$actual || ($actual['scheme'] ?? '') !== $fixed['scheme'] || ($actual['host'] ?? '') !== $fixed['host']
|
||||
|| ($actual['port'] ?? 443) !== ($fixed['port'] ?? 443) || ($actual['path'] ?? '') !== ($fixed['path'] ?? '')
|
||||
|| isset($actual['user']) || isset($actual['pass']) || isset($actual['fragment'])) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
parse_str($actual['query'] ?? '', $query);
|
||||
if (count($query) !== 1 || ($query['transaction_id'] ?? null) !== $id) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
IamV2Flow::put('target_launch', $id, ['sessionId' => hash('sha256', $browser), 'source' => $source, 'verifier' => $verifier,
|
||||
'stateHash' => hash('sha256', $state), 'expectedAdminId' => $existing]);
|
||||
return ['url' => $registered . '?' . http_build_query(['transaction_id' => $id, 'intent' => $intent], '', '&', PHP_QUERY_RFC3986), 'browser' => $browser];
|
||||
}
|
||||
public function callback(string $transaction, string $grant, string $browser, string $origin): array
|
||||
{
|
||||
if (!preg_match('/^[a-f0-9]{64}$/D', $browser) || !preg_match('/^[A-Za-z0-9_-]{43}$/D', $grant)) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$flow = IamV2Flow::peek('target_launch', $transaction, hash('sha256', $browser));
|
||||
$source = parse_url($this->registered($flow['source']));
|
||||
$expectedOrigin = $source['scheme'] . '://' . $source['host'] . (isset($source['port']) ? ':' . $source['port'] : '');
|
||||
if ($origin !== $expectedOrigin) { throw new RuntimeException('INVALID_ORIGIN'); }
|
||||
IamV2Flow::take('target_launch', $transaction, hash('sha256', $browser));
|
||||
$result = $this->client->call('POST', '/launch-grants/exchange', ['transactionId' => $transaction, 'grant' => $grant, 'codeVerifier' => $flow['verifier']]);
|
||||
$employee = $result['employee'] ?? []; $auth = $result['authentication'] ?? [];
|
||||
if (($employee['status'] ?? '') !== 'active' || !is_string($employee['oidcSubject'] ?? null) || $employee['oidcSubject'] === ''
|
||||
|| empty($employee['id']) || !($result['access']['allowed'] ?? false) || ($auth['sourceApplicationId'] ?? '') !== $flow['source']
|
||||
|| empty($auth['sessionId']) || !is_string($auth['authMethod'] ?? null) || $auth['authMethod'] === '' || !is_int($auth['sessionVersion'] ?? null) || $auth['sessionVersion'] < 1) { throw new RuntimeException('NOT_AUTHORIZED'); }
|
||||
self::authTime($auth['authTime'] ?? null);
|
||||
if ($flow['expectedAdminId'] !== null && (string) ($result['binding']['externalAccountId'] ?? '') !== (string) $flow['expectedAdminId']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$id = (int) ($this->resolve)($result);
|
||||
if ($id < 1 || ($flow['expectedAdminId'] !== null && $id !== (int) $flow['expectedAdminId'])) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
IamV2Source::admin($id);
|
||||
$current = (new IamV2Manager($this->client))->assertLinked($id);
|
||||
if (($current['employee']['id'] ?? '') !== $employee['id'] || ($current['employee']['oidcSubject'] ?? '') !== $employee['oidcSubject']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$ticket = bin2hex(random_bytes(32));
|
||||
IamV2Flow::put('target_ticket', $ticket, ['sessionId' => hash('sha256', $browser), 'adminId' => $id, 'expectedAdminId' => $flow['expectedAdminId'],
|
||||
'employeeId' => $employee['id'], 'bindingVersion' => (int) $current['binding']['version'], 'source' => $flow['source'], 'authentication' => $auth], 60);
|
||||
return ['ticket' => $ticket, 'source' => $flow['source']];
|
||||
}
|
||||
private function resolveAdmin(array $result): int
|
||||
{
|
||||
$employee = $result['employee']; $subject = $employee['oidcSubject'];
|
||||
$client = new IamOidcClient($this->settings); $context = $client->provisioning($subject);
|
||||
if (($context['employee']['id'] ?? '') !== $employee['id']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$binding = $result['binding'] ?? null;
|
||||
if ($binding && (($binding['applicationId'] ?? '') !== 'zyt' || ($binding['state'] ?? '') !== 'verified'
|
||||
|| (string) ($context['externalAccountId'] ?? '') !== (string) $binding['externalAccountId']
|
||||
|| (int) ($context['bindingVersion'] ?? 0) !== (int) $binding['version'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
if (!$binding && ($context['externalAccountId'] ?? '') !== '') { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
$id = (new IamAccountProvisioner())->resolve($client, $this->settings, $subject);
|
||||
$current = (new IamV2Manager($this->client))->assertLinked($id);
|
||||
if (($current['employee']['id'] ?? '') !== $employee['id'] || ($current['employee']['oidcSubject'] ?? '') !== $subject
|
||||
|| ($binding && (int) $current['binding']['version'] !== (int) $binding['version'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
return $id;
|
||||
}
|
||||
public function exchange(string $ticket, string $browser, string $token, string $sourceSession = ''): array
|
||||
{
|
||||
$flow = IamV2Flow::peek('target_ticket', $ticket, hash('sha256', $browser));
|
||||
$existing = self::existing($token, $sourceSession);
|
||||
if (($flow['expectedAdminId'] !== null && $existing !== (int) $flow['expectedAdminId']) || ($existing !== null && $existing !== (int) $flow['adminId'])) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$current = (new IamV2Manager($this->client))->assertLinked((int) $flow['adminId']);
|
||||
if (($current['employee']['id'] ?? '') !== $flow['employeeId']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
if ((int) $current['binding']['version'] !== (int) $flow['bindingVersion']) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
IamV2Flow::take('target_ticket', $ticket, hash('sha256', $browser));
|
||||
$result = ($this->login)((int) $flow['adminId'], $flow['authentication']);
|
||||
$hash = hash('sha256', $result['token']);
|
||||
$values = ['token_hash' => $hash, 'admin_id' => (int) $flow['adminId'], 'employee_id' => $flow['employeeId'],
|
||||
'source_application_id' => $flow['source'], 'source_binding_version' => (int) ($flow['authentication']['sourceBindingVersion'] ?? 0), 'checked_at' => time()];
|
||||
$old = Db::name('iam_v2_target_session')->where('token_hash', $hash)->find();
|
||||
if ($old) { Db::name('iam_v2_target_session')->where('token_hash', $hash)->update($values); }
|
||||
else { Db::name('iam_v2_target_session')->insert($values); }
|
||||
return $result;
|
||||
}
|
||||
public static function compensate(string $token): void
|
||||
{
|
||||
$hash = hash('sha256', $token); $row = Db::name('iam_v2_target_session')->where('token_hash', $hash)->find();
|
||||
if (!$row || $row['checked_at'] > time() - 30) { return; }
|
||||
$query = http_build_query(['employeeId' => $row['employee_id'], 'sourceApplicationId' => $row['source_application_id'],
|
||||
'sourceBindingVersion' => (int) $row['source_binding_version']], '', '&', PHP_QUERY_RFC3986);
|
||||
$check = (new IamV2Client())->call('GET', '/launch-authorizations/check?' . $query);
|
||||
if (!($check['allowed'] ?? false)) {
|
||||
Db::name('iam_v2_source_session')->where('token_hash', $hash)->where('revoked', 0)->inc('version')->update(['revoked' => 1]);
|
||||
AdminLogic::expireToken($token); throw new RuntimeException('NOT_AUTHORIZED');
|
||||
}
|
||||
Db::name('iam_v2_target_session')->where('token_hash', $hash)->update(['checked_at' => time()]);
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service;
|
||||
|
||||
use app\common\model\auth\SystemMenu;
|
||||
|
||||
/** 菜单授权只在自身与完整祖先链均存在、启用且无环时生效;is_show不参与接口授权。 */
|
||||
final class ActiveMenuPermissions
|
||||
{
|
||||
public static function ids(): array
|
||||
{
|
||||
$rows = SystemMenu::field('id,pid,is_disable')->select()->toArray();
|
||||
$byId = [];
|
||||
foreach ($rows as $row) { $byId[(int) $row['id']] = $row; }
|
||||
$enabled = [];
|
||||
foreach ($byId as $id => $row) {
|
||||
$current = $id;
|
||||
$visited = [];
|
||||
while ($current > 0) {
|
||||
if (isset($visited[$current]) || !isset($byId[$current]) || (int) $byId[$current]['is_disable'] !== 0) { continue 2; }
|
||||
$visited[$current] = true;
|
||||
$current = (int) $byId[$current]['pid'];
|
||||
}
|
||||
$enabled[] = $id;
|
||||
}
|
||||
return $enabled;
|
||||
}
|
||||
|
||||
public static function has(string $permission): bool
|
||||
{
|
||||
return SystemMenu::whereIn('id', self::ids())->where('perms', $permission)->count() > 0;
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
-- Additive only. Preserve all seven tables and the legacy iam_local_identity ledger on rollback.
|
||||
-- Apply with configured table prefix (default zyt_). No existing roles/accounts are changed.
|
||||
CREATE TABLE IF NOT EXISTS zyt_iam_v2_source_session (
|
||||
session_id CHAR(64) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
|
||||
admin_id INT UNSIGNED NOT NULL, business_session_id INT UNSIGNED NOT NULL,
|
||||
token_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||
account_stamp CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||
auth_method VARCHAR(16) NOT NULL, auth_time INT UNSIGNED NOT NULL,
|
||||
version INT UNSIGNED NOT NULL DEFAULT 1, revoked TINYINT NOT NULL DEFAULT 0,
|
||||
binding_version BIGINT UNSIGNED NOT NULL DEFAULT 0, employee_id VARCHAR(128) NOT NULL DEFAULT '',
|
||||
expires_at INT UNSIGNED NOT NULL, INDEX idx_admin (admin_id), INDEX idx_expiry (expires_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS zyt_iam_v2_proof (
|
||||
proof_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
|
||||
purpose VARCHAR(32) NOT NULL, session_id CHAR(64) NOT NULL, payload TEXT NOT NULL,
|
||||
expires_at INT UNSIGNED NOT NULL, consumed TINYINT NOT NULL DEFAULT 0, INDEX idx_expiry(expires_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS zyt_iam_v2_binding (
|
||||
admin_id INT UNSIGNED PRIMARY KEY, employee_id VARCHAR(128) NOT NULL DEFAULT '',
|
||||
subject VARCHAR(255) NOT NULL DEFAULT '', state VARCHAR(32) NOT NULL,
|
||||
version BIGINT UNSIGNED NOT NULL DEFAULT 0, payload MEDIUMTEXT NOT NULL,
|
||||
checked_at INT UNSIGNED NOT NULL DEFAULT 0, INDEX idx_employee(employee_id), INDEX idx_subject(subject)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS zyt_iam_v2_resource (
|
||||
resource_key CHAR(64) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
|
||||
kind VARCHAR(32) NOT NULL, external_id VARCHAR(128) NOT NULL, actor_id INT UNSIGNED NOT NULL,
|
||||
payload MEDIUMTEXT NOT NULL, created_at INT UNSIGNED NOT NULL, INDEX idx_actor(actor_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS zyt_iam_v2_flow (
|
||||
flow_key CHAR(64) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
|
||||
kind VARCHAR(32) NOT NULL, payload TEXT NOT NULL, expires_at INT UNSIGNED NOT NULL,
|
||||
consumed TINYINT NOT NULL DEFAULT 0, INDEX idx_expiry(expires_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS zyt_iam_v2_event (
|
||||
event_id VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY, digest CHAR(64) NOT NULL, received_at INT UNSIGNED NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS zyt_iam_v2_target_session (
|
||||
token_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
|
||||
admin_id INT UNSIGNED NOT NULL, employee_id VARCHAR(128) NOT NULL,
|
||||
source_application_id VARCHAR(64) NOT NULL, source_binding_version BIGINT UNSIGNED NOT NULL DEFAULT 0,
|
||||
checked_at INT UNSIGNED NOT NULL DEFAULT 0, INDEX idx_admin(admin_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
START TRANSACTION;
|
||||
SET @iam_parent := (SELECT pid FROM zyt_system_menu WHERE component='permission/admin/index' LIMIT 1);
|
||||
INSERT INTO zyt_system_menu (pid,type,name,icon,sort,perms,paths,component,selected,params,is_cache,is_show,is_disable,create_time,update_time)
|
||||
SELECT COALESCE(@iam_parent,0),'C','IAM关联管理','el-icon-Connection',85,'iamV2/read','identity-management','permission/identity/index','','',0,1,0,UNIX_TIMESTAMP(),UNIX_TIMESTAMP()
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM zyt_system_menu WHERE perms='iamV2/read');
|
||||
SET @iam_menu := (SELECT id FROM zyt_system_menu WHERE perms='iamV2/read' LIMIT 1);
|
||||
INSERT INTO zyt_system_menu (pid,type,name,icon,sort,perms,paths,component,selected,params,is_cache,is_show,is_disable,create_time,update_time)
|
||||
SELECT @iam_menu,'A','绑定IAM','',0,'iamV2/bind','','','','',0,1,0,UNIX_TIMESTAMP(),UNIX_TIMESTAMP()
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM zyt_system_menu WHERE perms='iamV2/bind');
|
||||
INSERT INTO zyt_system_menu (pid,type,name,icon,sort,perms,paths,component,selected,params,is_cache,is_show,is_disable,create_time,update_time)
|
||||
SELECT @iam_menu,'A','创建并关联IAM','',0,'iamV2/create','','','','',0,1,0,UNIX_TIMESTAMP(),UNIX_TIMESTAMP()
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM zyt_system_menu WHERE perms='iamV2/create');
|
||||
INSERT INTO zyt_system_menu (pid,type,name,icon,sort,perms,paths,component,selected,params,is_cache,is_show,is_disable,create_time,update_time)
|
||||
SELECT @iam_menu,'A','解除IAM关联','',0,'iamV2/unbind','','','','',0,1,0,UNIX_TIMESTAMP(),UNIX_TIMESTAMP()
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM zyt_system_menu WHERE perms='iamV2/unbind');
|
||||
INSERT INTO zyt_system_menu (pid,type,name,icon,sort,perms,paths,component,selected,params,is_cache,is_show,is_disable,create_time,update_time)
|
||||
SELECT @iam_menu,'A','更换IAM关联','',0,'iamV2/rebind','','','','',0,1,0,UNIX_TIMESTAMP(),UNIX_TIMESTAMP()
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM zyt_system_menu WHERE perms='iamV2/rebind');
|
||||
INSERT INTO zyt_system_menu (pid,type,name,icon,sort,perms,paths,component,selected,params,is_cache,is_show,is_disable,create_time,update_time)
|
||||
SELECT @iam_menu,'A','批量IAM任务','',0,'iamV2/batch','','','','',0,1,0,UNIX_TIMESTAMP(),UNIX_TIMESTAMP()
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM zyt_system_menu WHERE perms='iamV2/batch');
|
||||
COMMIT;
|
||||
-- Deliberately no system_role_menu grants: assign capabilities explicitly after review.
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
import r from"./error-0aMTVVqc.js";import{f as p,ak as i,I as m,a as e,aN as s,J as o}from"./@vue/runtime-core-C6bnekPw.js";import"./element-plus-8nruJdow.js";import"./@vue/runtime-dom-DDAG46FW.js";import"./lodash-D3kF6u-c.js";import"./@vue/shared-mAAVTE9n.js";import"./@vue/reactivity-DiY1c2vO.js";import"./@element-plus/icons-vue-CbYn5zW9.js";import"./lodash-es-C2A-Pj28.js";import"./@popperjs/core-C5az9QE8.js";import"./dayjs-DG77mNTn.js";import"./@ctrl/tinycolor-BuyEbX8F.js";import"./async-validator-CFA_igpM.js";import"./normalize-wheel-es-BQoi3Ox2.js";import"./vue-router-QlpZ4wdW.js";import"./index-XBs6Ys9P.js";import"./jspdf-BsthCvR5.js";import"./@babel/runtime-BanGtE2-.js";import"./fflate-_ayOYiT1.js";import"./pinia-B8cvXbiZ.js";import"./axios-C80V62Fs.js";import"./@vueuse/core-1S4fJlii.js";import"./@vueuse/shared-Cl3lVqjz.js";import"./css-color-function-DI01JAaZ.js";import"./balanced-match-BdS7OldZ.js";import"./color-B2zxaWkI.js";import"./clone-DBZ6_OiU.js";import"./color-convert-OrFsTA_V.js";import"./color-name-Dju3oUBS.js";import"./color-string-pUQDDJII.js";import"./ms-CzQ2E3wO.js";import"./vue-clipboard3-DByT_rEQ.js";import"./clipboard-CHgxszqY.js";import"./echarts-CNLwa9wG.js";import"./tslib-BDyQ-Jie.js";import"./zrender-DRNXw7y3.js";import"./highlight.js-Bxt7hFFy.js";import"./@highlightjs/vue-plugin-C4onkBvW.js";const a="/admin/assets/no_perms-jDxcYpYC.png",n={class:"error404"},W=p({__name:"403",setup(c){return(_,t)=>(i(),m("div",n,[e(r,{code:"403",title:"您的账号权限不足,请联系管理员添加权限!","show-btn":!1},{content:s(()=>[...t[0]||(t[0]=[o("div",{class:"flex justify-center"},[o("img",{class:"w-[150px] h-[150px]",src:a,alt:""})],-1)])]),_:1})]))}});export{W as default};
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
import r from"./error-MSl4Z8Dq.js";import{f as p,ak as i,I as m,a as e,aN as s,J as o}from"./@vue/runtime-core-C6bnekPw.js";import"./element-plus-8nruJdow.js";import"./@vue/runtime-dom-DDAG46FW.js";import"./lodash-D3kF6u-c.js";import"./@vue/shared-mAAVTE9n.js";import"./@vue/reactivity-DiY1c2vO.js";import"./@element-plus/icons-vue-CbYn5zW9.js";import"./lodash-es-C2A-Pj28.js";import"./@popperjs/core-C5az9QE8.js";import"./dayjs-DG77mNTn.js";import"./@ctrl/tinycolor-BuyEbX8F.js";import"./async-validator-CFA_igpM.js";import"./normalize-wheel-es-BQoi3Ox2.js";import"./vue-router-QlpZ4wdW.js";import"./index-CxCSQGvq.js";import"./jspdf-BsthCvR5.js";import"./@babel/runtime-BanGtE2-.js";import"./fflate-_ayOYiT1.js";import"./pinia-B8cvXbiZ.js";import"./axios-C80V62Fs.js";import"./@vueuse/core-1S4fJlii.js";import"./@vueuse/shared-Cl3lVqjz.js";import"./css-color-function-DI01JAaZ.js";import"./balanced-match-BdS7OldZ.js";import"./color-B2zxaWkI.js";import"./clone-DBZ6_OiU.js";import"./color-convert-OrFsTA_V.js";import"./color-name-Dju3oUBS.js";import"./color-string-pUQDDJII.js";import"./ms-CzQ2E3wO.js";import"./vue-clipboard3-DByT_rEQ.js";import"./clipboard-CHgxszqY.js";import"./echarts-CNLwa9wG.js";import"./tslib-BDyQ-Jie.js";import"./zrender-DRNXw7y3.js";import"./highlight.js-Bxt7hFFy.js";import"./@highlightjs/vue-plugin-C4onkBvW.js";const a="/admin/assets/no_perms-jDxcYpYC.png",n={class:"error404"},W=p({__name:"403",setup(c){return(_,t)=>(i(),m("div",n,[e(r,{code:"403",title:"您的账号权限不足,请联系管理员添加权限!","show-btn":!1},{content:s(()=>[...t[0]||(t[0]=[o("div",{class:"flex justify-center"},[o("img",{class:"w-[150px] h-[150px]",src:a,alt:""})],-1)])]),_:1})]))}});export{W as default};
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
import o from"./error-0aMTVVqc.js";import{f as r,ak as t,I as m,a as p}from"./@vue/runtime-core-C6bnekPw.js";import"./element-plus-8nruJdow.js";import"./@vue/runtime-dom-DDAG46FW.js";import"./lodash-D3kF6u-c.js";import"./@vue/shared-mAAVTE9n.js";import"./@vue/reactivity-DiY1c2vO.js";import"./@element-plus/icons-vue-CbYn5zW9.js";import"./lodash-es-C2A-Pj28.js";import"./@popperjs/core-C5az9QE8.js";import"./dayjs-DG77mNTn.js";import"./@ctrl/tinycolor-BuyEbX8F.js";import"./async-validator-CFA_igpM.js";import"./normalize-wheel-es-BQoi3Ox2.js";import"./vue-router-QlpZ4wdW.js";import"./index-XBs6Ys9P.js";import"./jspdf-BsthCvR5.js";import"./@babel/runtime-BanGtE2-.js";import"./fflate-_ayOYiT1.js";import"./pinia-B8cvXbiZ.js";import"./axios-C80V62Fs.js";import"./@vueuse/core-1S4fJlii.js";import"./@vueuse/shared-Cl3lVqjz.js";import"./css-color-function-DI01JAaZ.js";import"./balanced-match-BdS7OldZ.js";import"./color-B2zxaWkI.js";import"./clone-DBZ6_OiU.js";import"./color-convert-OrFsTA_V.js";import"./color-name-Dju3oUBS.js";import"./color-string-pUQDDJII.js";import"./ms-CzQ2E3wO.js";import"./vue-clipboard3-DByT_rEQ.js";import"./clipboard-CHgxszqY.js";import"./echarts-CNLwa9wG.js";import"./tslib-BDyQ-Jie.js";import"./zrender-DRNXw7y3.js";import"./highlight.js-Bxt7hFFy.js";import"./@highlightjs/vue-plugin-C4onkBvW.js";const i={class:"error404"},T=r({__name:"404",setup(e){return(a,s)=>(t(),m("div",i,[p(o,{code:"404",title:"哎呀,出错了!您访问的页面不存在…"})]))}});export{T as default};
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
import o from"./error-MSl4Z8Dq.js";import{f as r,ak as t,I as m,a as p}from"./@vue/runtime-core-C6bnekPw.js";import"./element-plus-8nruJdow.js";import"./@vue/runtime-dom-DDAG46FW.js";import"./lodash-D3kF6u-c.js";import"./@vue/shared-mAAVTE9n.js";import"./@vue/reactivity-DiY1c2vO.js";import"./@element-plus/icons-vue-CbYn5zW9.js";import"./lodash-es-C2A-Pj28.js";import"./@popperjs/core-C5az9QE8.js";import"./dayjs-DG77mNTn.js";import"./@ctrl/tinycolor-BuyEbX8F.js";import"./async-validator-CFA_igpM.js";import"./normalize-wheel-es-BQoi3Ox2.js";import"./vue-router-QlpZ4wdW.js";import"./index-CxCSQGvq.js";import"./jspdf-BsthCvR5.js";import"./@babel/runtime-BanGtE2-.js";import"./fflate-_ayOYiT1.js";import"./pinia-B8cvXbiZ.js";import"./axios-C80V62Fs.js";import"./@vueuse/core-1S4fJlii.js";import"./@vueuse/shared-Cl3lVqjz.js";import"./css-color-function-DI01JAaZ.js";import"./balanced-match-BdS7OldZ.js";import"./color-B2zxaWkI.js";import"./clone-DBZ6_OiU.js";import"./color-convert-OrFsTA_V.js";import"./color-name-Dju3oUBS.js";import"./color-string-pUQDDJII.js";import"./ms-CzQ2E3wO.js";import"./vue-clipboard3-DByT_rEQ.js";import"./clipboard-CHgxszqY.js";import"./echarts-CNLwa9wG.js";import"./tslib-BDyQ-Jie.js";import"./zrender-DRNXw7y3.js";import"./highlight.js-Bxt7hFFy.js";import"./@highlightjs/vue-plugin-C4onkBvW.js";const i={class:"error404"},T=r({__name:"404",setup(e){return(a,s)=>(t(),m("div",i,[p(o,{code:"404",title:"哎呀,出错了!您访问的页面不存在…"})]))}});export{T as default};
|
||||
@@ -0,0 +1 @@
|
||||
function a(e){"@babel/helpers - typeof";return a=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a(e)}function c(e,t,r,n,f,y,i){try{var u=e[y](i),o=u.value}catch(l){return void r(l)}u.done?t(o):Promise.resolve(o).then(n,f)}function p(e){return function(){var t=this,r=arguments;return new Promise(function(n,f){var y=e.apply(t,r);function i(o){c(y,n,f,i,u,"next",o)}function u(o){c(y,n,f,i,u,"throw",o)}i(void 0)})}}function b(e,t){if(a(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(a(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function m(e){var t=b(e,"string");return a(t)=="symbol"?t:t+""}function s(e,t,r){return(t=m(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}export{a as _,p as a,s as b};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
import{H as u}from"../highlight.js-Bxt7hFFy.js";import{f as c,i as g,w as s,A as n}from"../@vue/runtime-core-C6bnekPw.js";import{n as h}from"../@vue/reactivity-DiY1c2vO.js";var i=c({props:{code:{type:String,required:!0},language:{type:String,default:""},autodetect:{type:Boolean,default:!0},ignoreIllegals:{type:Boolean,default:!0}},setup:function(e){var t=h(e.language);s((function(){return e.language}),(function(a){t.value=a}));var r=n((function(){return e.autodetect||!t.value})),o=n((function(){return!r.value&&!u.getLanguage(t.value)}));return{className:n((function(){return o.value?"":"hljs "+t.value})),highlightedCode:n((function(){var a;if(o.value)return console.warn('The language "'+t.value+'" you specified could not be found.'),e.code.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");if(r.value){var l=u.highlightAuto(e.code);return t.value=(a=l.language)!==null&&a!==void 0?a:"",l.value}return(l=u.highlight(e.code,{language:t.value,ignoreIllegals:e.ignoreIllegals})).value}))}},render:function(){return g("pre",{},[g("code",{class:this.className,innerHTML:this.highlightedCode})])}}),v={install:function(e){e.component("highlightjs",i)},component:i};export{v as o};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
import"./uikit-base-component-vue3-YgTqL4da.js";import{A as r}from"../tuikit-atomicx-vue3-Dln8Zi6e.js";import{f as s,ak as c,I as l,aq as m,G as u,at as i,H as p,A as d}from"../@vue/runtime-core-C6bnekPw.js";import{y as v}from"../@vue/reactivity-DiY1c2vO.js";import"./chat-uikit-engine-zx802ozq.js";const _=(t,o)=>{const a=t.__vccOpts||t;for(const[e,n]of o)a[e]=n;return a},f={key:0,class:"chat"},h=s({name:"Chat",__name:"Chat",props:{PlaceholderEmpty:{default:null}},setup(t){const{activeConversation:o}=r(),a=d(()=>{var e;return!((e=o.value)!=null&&e.conversationID)});return(e,n)=>v(o)?(c(),l("div",f,[m(e.$slots,"default",{},void 0,!0)])):a.value&&t.PlaceholderEmpty?(c(),u(i(t.PlaceholderEmpty),{key:1})):p("",!0)}}),A=_(h,[["__scopeId","data-v-1c9c77cd"]]);typeof window<"u"&&(window.__CHAT_ATOMICX_VUE3__={name:"@tencentcloud/chat-uikit-vue3",version:"4.5.4"},console.log("[@tencentcloud/chat-uikit-vue3] v4.5.4"));export{A as E};
|
||||
@@ -0,0 +1 @@
|
||||
.chat[data-v-1c9c77cd]{display:flex;flex-direction:column;min-width:0}.uikit-chat-header[data-v-a0c42ddc]{padding:14px 10px;height:64px;display:flex;justify-content:center;background-color:var(--bg-color-operate)}.uikit-chat-header__container[data-v-a0c42ddc]{padding:0 10px;flex-direction:row;align-items:center;justify-content:space-between}.uikit-chat-header__left[data-v-a0c42ddc]{flex:1 1 auto;display:flex;flex-direction:row;align-items:center}.uikit-chat-header__avatar[data-v-a0c42ddc]{margin-right:12px}.uikit-chat-header__info[data-v-a0c42ddc]{flex:1;display:flex;flex-direction:column;justify-content:center}.uikit-chat-header__title[data-v-a0c42ddc]{display:block;margin:0;font-size:16px;font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text-color-primary)}.uikit-chat-header__typing-indicator[data-v-a0c42ddc]{font-size:12px;color:var(--text-color-secondary)}.uikit-chat-header__live[data-v-a0c42ddc]{margin-top:4px;font-size:12px;color:var(--text-color-secondary)}/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}main{display:block}h1{font-size:2em;margin:.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent}abbr[title]{border-bottom:none;text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}button,[type=button],[type=reset],[type=submit]{-webkit-appearance:button}button::-moz-focus-inner,[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner{border-style:none;padding:0}button:-moz-focusring,[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:.35em .75em .625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}template{display:none}[hidden]{display:none}:root{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}*,*:after,*:before{box-sizing:border-box}ul,li{list-style:none;padding:0;margin:0}picture,img,video,canvas,svg{display:block;max-width:100%}img{max-width:100%;height:auto;vertical-align:middle;image-rendering:-webkit-optimize-contrast;aspect-ratio:attr(width)/attr(height);display:inline-block;-webkit-user-drag:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}img:not([src],[srcset]){visibility:hidden}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+6
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
import{C as A,F as C,a as w,L as h,q as D,J as R,H as g,u as k,n as W}from"../@vue/reactivity-DiY1c2vO.js";import{w as b,b as x,n as L,g as F,$ as M,a5 as P}from"../@vue/runtime-core-C6bnekPw.js";function J(e){return A()?(C(e),!0):!1}const d=new WeakMap,z=(...e)=>{var t;const r=e[0],n=(t=F())==null?void 0:t.proxy;if(n==null&&!M())throw new Error("injectLocal must be called in setup");return n&&d.has(n)&&r in d.get(n)?d.get(n)[r]:P(...e)},B=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const K=e=>typeof e<"u",I=Object.prototype.toString,Q=e=>I.call(e)==="[object Object]",m=()=>{};function j(e,t){function r(...n){return new Promise((a,o)=>{Promise.resolve(e(()=>t.apply(this,n),{fn:t,thisArg:this,args:n})).then(a).catch(o)})}return r}const S=e=>e();function V(...e){let t=0,r,n=!0,a=m,o,s,i,u,c;!w(e[0])&&typeof e[0]=="object"?{delay:s,trailing:i=!0,leading:u=!0,rejectOnCancel:c=!1}=e[0]:[s,i=!0,u=!0,c=!1]=e;const f=()=>{r&&(clearTimeout(r),r=void 0,a(),a=m)};return O=>{const l=h(s),v=Date.now()-t,p=()=>o=O();return f(),l<=0?(t=Date.now(),p()):(v>l&&(u||!n)?(t=Date.now(),p()):i&&(o=new Promise((y,T)=>{a=c?T:y,r=setTimeout(()=>{t=Date.now(),n=!0,y(p()),f()},Math.max(0,l-v))})),!u&&!r&&(r=setTimeout(()=>n=!0,l)),n=!1,o)}}function E(e=S,t={}){const{initialState:r="active"}=t,n=N(r==="active");function a(){n.value=!1}function o(){n.value=!0}const s=(...i)=>{n.value&&e(...i)};return{isActive:g(n),pause:a,resume:o,eventFilter:s}}function U(e){return e.endsWith("rem")?Number.parseFloat(e)*16:Number.parseFloat(e)}function G(e){return F()}function X(e){return Array.isArray(e)?e:[e]}function N(...e){if(e.length!==1)return R(...e);const t=e[0];return typeof t=="function"?g(k(()=>({get:t,set:m}))):W(t)}function Y(e,t=200,r=!1,n=!0,a=!1){return j(V(t,r,n,a),e)}function _(e,t,r={}){const{eventFilter:n=S,...a}=r;return b(e,j(n,t),a)}function Z(e,t,r={}){const{eventFilter:n,initialState:a="active",...o}=r,{eventFilter:s,pause:i,resume:u,isActive:c}=E(n,{initialState:a});return{stop:_(e,t,{...o,eventFilter:s}),pause:i,resume:u,isActive:c}}function ee(e,t=!0,r){G()?x(e,r):t?e():L(e)}function te(e=!1,t={}){const{truthyValue:r=!0,falsyValue:n=!1}=t,a=w(e),o=D(e);function s(i){if(arguments.length)return o.value=i,o.value;{const u=h(r);return o.value=o.value===u?h(n):u,o.value}}return a?s:[o,s]}function ne(e,t,r){return b(e,t,{...r,immediate:!0})}export{N as a,ee as b,Q as c,X as d,Z as e,z as f,K as g,Y as h,B as i,U as p,J as t,te as u,ne as w};
|
||||
+185
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
|
||||
import{i as C,Q as y,a as E}from"./editor-Cyf37SuL.js";import{ak as g,I as h,f as w,b as P,w as O,aJ as b}from"../@vue/runtime-core-C6bnekPw.js";import{n as d,t as $,q as F}from"../@vue/reactivity-DiY1c2vO.js";var B=Object.defineProperty,D=Object.defineProperties,j=Object.getOwnPropertyDescriptors,m=Object.getOwnPropertySymbols,H=Object.prototype.hasOwnProperty,S=Object.prototype.propertyIsEnumerable,_=(e,t,o)=>t in e?B(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,A=(e,t)=>{for(var o in t||(t={}))H.call(t,o)&&_(e,o,t[o]);if(m)for(var o of m(t))S.call(t,o)&&_(e,o,t[o]);return e},M=(e,t)=>D(e,j(t));function u(e){let t=`请使用 '@${e}' 事件,不要放在 props 中`;return t+=`
|
||||
Please use '@${e}' event instead of props`,t}var v=(e,t)=>{for(const[o,a]of t)e[o]=a;return e};const V=w({props:{mode:{type:String,default:"default"},defaultContent:{type:Array,default:[]},defaultHtml:{type:String,default:""},defaultConfig:{type:Object,default:{}},modelValue:{type:String,default:""}},setup(e,t){const o=d(null),a=F(null),i=d(""),s=()=>{if(!o.value)return;const f=$(e.defaultContent);C({selector:o.value,mode:e.mode,content:f||[],html:e.defaultHtml||e.modelValue||"",config:M(A({},e.defaultConfig),{onCreated(r){if(a.value=r,t.emit("onCreated",r),e.defaultConfig.onCreated){const n=u("onCreated");throw new Error(n)}},onChange(r){const n=r.getHtml();if(i.value=n,t.emit("update:modelValue",n),t.emit("onChange",r),e.defaultConfig.onChange){const l=u("onChange");throw new Error(l)}},onDestroyed(r){if(t.emit("onDestroyed",r),e.defaultConfig.onDestroyed){const n=u("onDestroyed");throw new Error(n)}},onMaxLength(r){if(t.emit("onMaxLength",r),e.defaultConfig.onMaxLength){const n=u("onMaxLength");throw new Error(n)}},onFocus(r){if(t.emit("onFocus",r),e.defaultConfig.onFocus){const n=u("onFocus");throw new Error(n)}},onBlur(r){if(t.emit("onBlur",r),e.defaultConfig.onBlur){const n=u("onBlur");throw new Error(n)}},customAlert(r,n){if(t.emit("customAlert",r,n),e.defaultConfig.customAlert){const l=u("customAlert");throw new Error(l)}},customPaste:(r,n)=>{if(e.defaultConfig.customPaste){const c=u("customPaste");throw new Error(c)}let l;return t.emit("customPaste",r,n,c=>{l=c}),l}})})};function p(f){const r=a.value;r!=null&&r.setHtml(f)}return P(()=>{s()}),O(()=>e.modelValue,f=>{f!==i.value&&p(f)}),{box:o}}}),I={ref:"box",style:{height:"100%"}};function L(e,t,o,a,i,s){return g(),h("div",I,null,512)}var J=v(V,[["render",L]]);const T=w({props:{editor:{type:Object},mode:{type:String,default:"default"},defaultConfig:{type:Object,default:{}}},setup(e){const t=d(null),o=a=>{if(t.value){if(a==null)throw new Error("Not found instance of Editor when create <Toolbar/> component");y.getToolbar(a)||E({editor:a,selector:t.value||"<div></div>",mode:e.mode,config:e.defaultConfig})}};return b(()=>{const{editor:a}=e;a!=null&&o(a)}),{selector:t}}}),R={ref:"selector"};function k(e,t,o,a,i,s){return g(),h("div",R,null,512)}var N=v(T,[["render",k]]);export{J as E,N as T};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
.watch-state[data-v-8c719418]{min-height:200px;display:flex;align-items:center;justify-content:center;color:var(--el-text-color-secondary);font-size:14px}.watch-error[data-v-8c719418]{color:var(--el-color-danger)}.watch-grid[data-v-8c719418]{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:12px;min-height:220px}.watch-tile[data-v-8c719418]{background:#0f0f0f;border-radius:8px;overflow:hidden;aspect-ratio:16 / 10;display:flex;flex-direction:column}.watch-tile-cap[data-v-8c719418]{padding:6px 10px;font-size:12px;color:#e5e5e5;background:#0000008c}.watch-tile-view[data-v-8c719418]{flex:1;min-height:0;position:relative}.watch-hint[data-v-8c719418]{float:left;line-height:32px;font-size:12px;color:var(--el-text-color-secondary)}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
import{d as V,R as D,P as L,Q as O,O as P,W as T}from"./element-plus-8nruJdow.js";import{ao as z}from"./tcm-BFeJYLDf.js";import{f as F,b as M,w as R,ak as a,I as n,a as i,aN as s,O as m,H as w,aP as j,G as g,F as A,J as H}from"./@vue/runtime-core-C6bnekPw.js";import{y as d,n as k}from"./@vue/reactivity-DiY1c2vO.js";import{Q as c}from"./@vue/shared-mAAVTE9n.js";import{_ as Q}from"./index-XBs6Ys9P.js";import"./@vue/runtime-dom-DDAG46FW.js";import"./lodash-D3kF6u-c.js";import"./@element-plus/icons-vue-CbYn5zW9.js";import"./lodash-es-C2A-Pj28.js";import"./@popperjs/core-C5az9QE8.js";import"./dayjs-DG77mNTn.js";import"./@ctrl/tinycolor-BuyEbX8F.js";import"./async-validator-CFA_igpM.js";import"./normalize-wheel-es-BQoi3Ox2.js";import"./jspdf-BsthCvR5.js";import"./@babel/runtime-BanGtE2-.js";import"./fflate-_ayOYiT1.js";import"./vue-router-QlpZ4wdW.js";import"./pinia-B8cvXbiZ.js";import"./axios-C80V62Fs.js";import"./@vueuse/core-1S4fJlii.js";import"./@vueuse/shared-Cl3lVqjz.js";import"./css-color-function-DI01JAaZ.js";import"./balanced-match-BdS7OldZ.js";import"./color-B2zxaWkI.js";import"./clone-DBZ6_OiU.js";import"./color-convert-OrFsTA_V.js";import"./color-name-Dju3oUBS.js";import"./color-string-pUQDDJII.js";import"./ms-CzQ2E3wO.js";import"./vue-clipboard3-DByT_rEQ.js";import"./clipboard-CHgxszqY.js";import"./echarts-CNLwa9wG.js";import"./tslib-BDyQ-Jie.js";import"./zrender-DRNXw7y3.js";import"./highlight.js-Bxt7hFFy.js";import"./@highlightjs/vue-plugin-C4onkBvW.js";const G={class:"case-record-list"},J={key:0,class:"mb-3 flex justify-end"},W={key:0},Y={key:1,class:"text-gray-400"},q={class:"void-detail text-xs text-gray-500 mt-1"},K=F({__name:"CaseRecordList",props:{diagnosisId:{type:Number,default:0},readOnly:{type:Boolean,default:!1}},emits:["view","openPrescription"],setup(y,{expose:x,emit:C}){const _=y,h=C,l=k([]),p=k(!1),u=async()=>{if(_.diagnosisId){p.value=!0;try{const e=await z({diagnosis_id:_.diagnosisId});l.value=Array.isArray(e)?e:[]}catch(e){console.error("获取病历记录失败:",e),l.value=[]}finally{p.value=!1}}},S=e=>{if(!e)return"";const t=new Date(e*1e3);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`},$=e=>{h("view",e)},B=()=>{h("openPrescription")};return M(()=>{u()}),R(()=>_.diagnosisId,()=>{u()}),x({refresh:u}),(e,t)=>{const b=V,r=L,v=O,E=P,I=T,N=D;return a(),n("div",G,[y.readOnly?w("",!0):(a(),n("div",J,[i(b,{type:"primary",size:"small",onClick:B},{default:s(()=>[...t[0]||(t[0]=[m("开方",-1)])]),_:1})])),j((a(),g(E,{data:d(l),border:""},{default:s(()=>[i(r,{prop:"prescription_date",label:"就诊日期",width:"120"}),i(r,{prop:"visit_no",label:"门诊号",width:"120"}),i(r,{prop:"clinical_diagnosis",label:"临床诊断","min-width":"160","show-overflow-tooltip":""}),i(r,{label:"处方摘要","min-width":"180"},{default:s(({row:o})=>[o.herbs&&o.herbs.length?(a(),n("span",W,c(o.herbs.slice(0,3).map(f=>`${f.name}${f.dosage}克`).join("、"))+c(o.herbs.length>3?"...":""),1)):(a(),n("span",Y,"—"))]),_:1}),i(r,{prop:"doctor_name",label:"医师",width:"90","show-overflow-tooltip":""}),i(r,{label:"状态",width:"140",align:"center"},{default:s(({row:o})=>[o.void_status===1?(a(),n(A,{key:0},[i(v,{type:"danger",size:"small"},{default:s(()=>[...t[1]||(t[1]=[m("已作废",-1)])]),_:1}),H("div",q,c(o.void_by_name||"—")+" "+c(S(o.void_time)),1)],64)):(a(),g(v,{key:1,type:"success",size:"small"},{default:s(()=>[...t[2]||(t[2]=[m("正常",-1)])]),_:1}))]),_:1}),i(r,{label:"操作",width:"120",fixed:"right"},{default:s(({row:o})=>[i(b,{link:"",type:"primary",size:"small",onClick:f=>$(o)},{default:s(()=>[...t[3]||(t[3]=[m(" 查看 ",-1)])]),_:1},8,["onClick"])]),_:1})]),_:1},8,["data"])),[[N,d(p)]]),!d(p)&&d(l).length===0?(a(),g(I,{key:1,description:"暂无病历记录,开方后会自动显示",class:"mt-4"})):w("",!0)])}}}),Pt=Q(K,[["__scopeId","data-v-043d2738"]]);export{Pt as default};
|
||||
@@ -0,0 +1 @@
|
||||
import{d as V,R as D,P as L,Q as O,O as P,W as T}from"./element-plus-8nruJdow.js";import{ao as z}from"./tcm-BCsm1G3I.js";import{f as F,b as M,w as R,ak as a,I as n,a as i,aN as s,O as m,H as w,aP as j,G as g,F as A,J as H}from"./@vue/runtime-core-C6bnekPw.js";import{y as d,n as k}from"./@vue/reactivity-DiY1c2vO.js";import{Q as c}from"./@vue/shared-mAAVTE9n.js";import{_ as Q}from"./index-CxCSQGvq.js";import"./@vue/runtime-dom-DDAG46FW.js";import"./lodash-D3kF6u-c.js";import"./@element-plus/icons-vue-CbYn5zW9.js";import"./lodash-es-C2A-Pj28.js";import"./@popperjs/core-C5az9QE8.js";import"./dayjs-DG77mNTn.js";import"./@ctrl/tinycolor-BuyEbX8F.js";import"./async-validator-CFA_igpM.js";import"./normalize-wheel-es-BQoi3Ox2.js";import"./jspdf-BsthCvR5.js";import"./@babel/runtime-BanGtE2-.js";import"./fflate-_ayOYiT1.js";import"./vue-router-QlpZ4wdW.js";import"./pinia-B8cvXbiZ.js";import"./axios-C80V62Fs.js";import"./@vueuse/core-1S4fJlii.js";import"./@vueuse/shared-Cl3lVqjz.js";import"./css-color-function-DI01JAaZ.js";import"./balanced-match-BdS7OldZ.js";import"./color-B2zxaWkI.js";import"./clone-DBZ6_OiU.js";import"./color-convert-OrFsTA_V.js";import"./color-name-Dju3oUBS.js";import"./color-string-pUQDDJII.js";import"./ms-CzQ2E3wO.js";import"./vue-clipboard3-DByT_rEQ.js";import"./clipboard-CHgxszqY.js";import"./echarts-CNLwa9wG.js";import"./tslib-BDyQ-Jie.js";import"./zrender-DRNXw7y3.js";import"./highlight.js-Bxt7hFFy.js";import"./@highlightjs/vue-plugin-C4onkBvW.js";const G={class:"case-record-list"},J={key:0,class:"mb-3 flex justify-end"},W={key:0},Y={key:1,class:"text-gray-400"},q={class:"void-detail text-xs text-gray-500 mt-1"},K=F({__name:"CaseRecordList",props:{diagnosisId:{type:Number,default:0},readOnly:{type:Boolean,default:!1}},emits:["view","openPrescription"],setup(y,{expose:x,emit:C}){const _=y,h=C,l=k([]),p=k(!1),u=async()=>{if(_.diagnosisId){p.value=!0;try{const e=await z({diagnosis_id:_.diagnosisId});l.value=Array.isArray(e)?e:[]}catch(e){console.error("获取病历记录失败:",e),l.value=[]}finally{p.value=!1}}},S=e=>{if(!e)return"";const t=new Date(e*1e3);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`},$=e=>{h("view",e)},B=()=>{h("openPrescription")};return M(()=>{u()}),R(()=>_.diagnosisId,()=>{u()}),x({refresh:u}),(e,t)=>{const b=V,r=L,v=O,E=P,I=T,N=D;return a(),n("div",G,[y.readOnly?w("",!0):(a(),n("div",J,[i(b,{type:"primary",size:"small",onClick:B},{default:s(()=>[...t[0]||(t[0]=[m("开方",-1)])]),_:1})])),j((a(),g(E,{data:d(l),border:""},{default:s(()=>[i(r,{prop:"prescription_date",label:"就诊日期",width:"120"}),i(r,{prop:"visit_no",label:"门诊号",width:"120"}),i(r,{prop:"clinical_diagnosis",label:"临床诊断","min-width":"160","show-overflow-tooltip":""}),i(r,{label:"处方摘要","min-width":"180"},{default:s(({row:o})=>[o.herbs&&o.herbs.length?(a(),n("span",W,c(o.herbs.slice(0,3).map(f=>`${f.name}${f.dosage}克`).join("、"))+c(o.herbs.length>3?"...":""),1)):(a(),n("span",Y,"—"))]),_:1}),i(r,{prop:"doctor_name",label:"医师",width:"90","show-overflow-tooltip":""}),i(r,{label:"状态",width:"140",align:"center"},{default:s(({row:o})=>[o.void_status===1?(a(),n(A,{key:0},[i(v,{type:"danger",size:"small"},{default:s(()=>[...t[1]||(t[1]=[m("已作废",-1)])]),_:1}),H("div",q,c(o.void_by_name||"—")+" "+c(S(o.void_time)),1)],64)):(a(),g(v,{key:1,type:"success",size:"small"},{default:s(()=>[...t[2]||(t[2]=[m("正常",-1)])]),_:1}))]),_:1}),i(r,{label:"操作",width:"120",fixed:"right"},{default:s(({row:o})=>[i(b,{link:"",type:"primary",size:"small",onClick:f=>$(o)},{default:s(()=>[...t[3]||(t[3]=[m(" 查看 ",-1)])]),_:1},8,["onClick"])]),_:1})]),_:1},8,["data"])),[[N,d(p)]]),!d(p)&&d(l).length===0?(a(),g(I,{key:1,description:"暂无病历记录,开方后会自动显示",class:"mt-4"})):w("",!0)])}}}),Pt=Q(K,[["__scopeId","data-v-043d2738"]]);export{Pt as default};
|
||||
+2
File diff suppressed because one or more lines are too long
+2
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
.consultation-transcripts[data-v-e51f1814]{padding:4px 0 16px}.transcript-toolbar[data-v-e51f1814],.transcript-detail-header[data-v-e51f1814]{display:flex;align-items:flex-start;justify-content:space-between;gap:16px}.transcript-toolbar[data-v-e51f1814]{margin-bottom:20px}.transcript-toolbar h3[data-v-e51f1814],.transcript-detail h4[data-v-e51f1814]{margin:0;color:var(--el-text-color-primary);font-weight:600}.transcript-toolbar h3[data-v-e51f1814]{font-size:18px}.transcript-toolbar p[data-v-e51f1814],.transcript-detail-header p[data-v-e51f1814]{margin:7px 0 0;color:var(--el-text-color-secondary);line-height:1.7;font-size:13px}.transcript-error[data-v-e51f1814]{margin-bottom:16px}.transcript-body[data-v-e51f1814]{display:flex;min-height:360px;border-top:1px solid var(--el-border-color-lighter)}.transcript-sessions[data-v-e51f1814]{flex:0 0 282px;min-width:0;padding:18px 18px 0 0;border-right:1px solid var(--el-border-color-lighter)}.session-count[data-v-e51f1814]{margin:12px 0 8px;color:var(--el-text-color-secondary);font-size:12px}.session-list[data-v-e51f1814]{display:flex;flex-direction:column;gap:8px;max-height:580px;overflow-y:auto;margin-bottom:12px}.session-item[data-v-e51f1814]{display:flex;flex-direction:column;align-items:flex-start;gap:8px;width:100%;padding:13px 12px;border:1px solid var(--el-border-color-lighter);border-radius:7px;background:var(--el-bg-color);text-align:left;cursor:pointer;font:inherit}.session-item[data-v-e51f1814]:hover,.session-item.selected[data-v-e51f1814]{border-color:var(--el-color-primary);background:var(--el-color-primary-light-9)}.session-item[data-v-e51f1814]:focus-visible{outline:2px solid var(--el-color-primary);outline-offset:-2px}.session-time[data-v-e51f1814]{color:var(--el-text-color-primary);font-size:14px;font-weight:600}.session-meta[data-v-e51f1814],.session-preview[data-v-e51f1814]{color:var(--el-text-color-secondary);font-size:12px;line-height:1.6}.session-preview[data-v-e51f1814]{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;overflow-wrap:anywhere}.transcript-detail[data-v-e51f1814]{flex:1;min-width:0;padding:20px 0 0 24px}.transcript-detail h4[data-v-e51f1814]{font-size:16px;line-height:1.7}.transcript-status[data-v-e51f1814]{display:flex;align-items:center;flex-wrap:wrap;gap:12px;margin:16px 0;color:var(--el-text-color-secondary);font-size:13px}.transcript-note[data-v-e51f1814]{padding:10px 12px;background:var(--el-color-warning-light-9);color:var(--el-color-warning-dark-2);font-size:13px;line-height:1.7}.transcript-text[data-v-e51f1814]{margin:0;padding:20px 0;color:var(--el-text-color-primary);white-space:pre-wrap;overflow-wrap:anywhere;font:inherit;font-size:15px;line-height:2;-webkit-user-select:text;-moz-user-select:text;user-select:text}.transcript-empty[data-v-e51f1814]{flex:1}@media(max-width:900px){.transcript-body[data-v-e51f1814]{flex-direction:column}.transcript-sessions[data-v-e51f1814]{flex-basis:auto;padding:16px 0;border-right:0;border-bottom:1px solid var(--el-border-color-lighter)}.session-list[data-v-e51f1814]{max-height:300px}.transcript-detail[data-v-e51f1814]{padding:20px 0 0}.transcript-detail-header[data-v-e51f1814]{flex-wrap:wrap}}
|
||||
+1
@@ -0,0 +1 @@
|
||||
.daily-matrix[data-v-2663c148]{padding:16px}.daily-matrix__toolbar[data-v-2663c148]{display:flex;justify-content:space-between;gap:12px;align-items:center;flex-wrap:wrap;margin-bottom:12px}.daily-matrix__toolbar-left[data-v-2663c148],.daily-matrix__toolbar-right[data-v-2663c148]{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.daily-matrix__table[data-v-2663c148],.daily-matrix__table-wrap[data-v-2663c148]{width:100%}.daily-matrix__hint[data-v-2663c148],.daily-matrix__time-evidence[data-v-2663c148]{color:var(--el-text-color-secondary);font-size:12px;line-height:1.6;margin:0 0 12px;overflow-wrap:anywhere}.daily-matrix__record-count[data-v-2663c148]{color:var(--el-color-primary);font-size:11px;white-space:nowrap}.daily-matrix__detail-section+.daily-matrix__detail-section[data-v-2663c148]{margin-top:24px}.daily-matrix__detail-heading[data-v-2663c148]{display:flex;justify-content:space-between;align-items:center;gap:12px}.daily-matrix__detail-heading h3[data-v-2663c148]{margin:0 0 8px}.daily-matrix__detail-heading small[data-v-2663c148]{color:var(--el-text-color-secondary);font-weight:400}.daily-matrix__detail-record[data-v-2663c148]{border:1px solid var(--el-border-color);border-radius:8px;padding:12px;margin-bottom:12px}.daily-matrix__detail-tags[data-v-2663c148]{display:flex;gap:8px;flex-wrap:wrap;margin:8px 0}.daily-matrix__detail-fields[data-v-2663c148]{display:grid;grid-template-columns:96px minmax(0,1fr);gap:8px;margin:12px 0 0}.daily-matrix__detail-fields dt[data-v-2663c148]{color:var(--el-text-color-secondary)}.daily-matrix__detail-fields dd[data-v-2663c148]{margin:0;white-space:pre-wrap;overflow-wrap:anywhere}.daily-matrix__detail-images[data-v-2663c148]{display:flex;flex-wrap:wrap;gap:8px;margin-top:8px}.daily-matrix__detail-images .el-image[data-v-2663c148]{width:64px;height:64px;border-radius:4px}.daily-matrix__chart[data-v-2663c148]{margin-top:16px;padding:16px 18px;border:1px solid var(--el-border-color-lighter);border-radius:10px;background:linear-gradient(180deg,#fff,#f8fafc)}.daily-matrix__chart-canvas[data-v-2663c148]{height:280px;width:100%}.daily-matrix__cell[data-v-2663c148]{min-height:32px;display:inline-flex;align-items:center;justify-content:center;gap:2px;width:100%;color:var(--el-text-color-regular)}.daily-matrix__cell.is-clickable[data-v-2663c148]{cursor:pointer}.daily-matrix__cell.is-empty[data-v-2663c148]{color:var(--el-text-color-placeholder)}.daily-matrix__cell.is-high[data-v-2663c148]{color:#dc2626;font-weight:700}.daily-matrix__cell.is-patient-self[data-v-2663c148]{position:relative;background:linear-gradient(180deg,#8b5cf60a,#8b5cf61a);border-radius:4px}.daily-matrix__cell-up[data-v-2663c148]{color:#dc2626;font-size:13px}.daily-matrix__cell-patient[data-v-2663c148]{display:inline-block;margin-left:4px;padding:1px 6px;font-size:11px;font-weight:600;color:#6d28d9;background:#ede9fe;border:1px solid #ddd6fe;border-radius:999px;line-height:1.2;letter-spacing:.5px;white-space:nowrap}.daily-matrix__legend[data-v-2663c148]{display:inline-flex;align-items:center;gap:6px;margin-right:12px;padding:2px 10px 2px 6px;background:#f8f6ff;border:1px dashed #ddd6fe;border-radius:999px}.daily-matrix__legend-text[data-v-2663c148]{font-size:12px;color:#6d28d9;font-weight:500}.daily-matrix__todo[data-v-2663c148]{margin-top:16px}.daily-matrix__section-title[data-v-2663c148]{font-size:14px;font-weight:600;margin-bottom:12px;color:var(--el-text-color-primary)}.daily-matrix__tracking-existing[data-v-2663c148]{width:100%;max-height:180px;overflow:auto;padding:8px 10px;border:1px solid var(--el-border-color);border-radius:6px;background:var(--el-fill-color-light)}.daily-matrix__tracking-line[data-v-2663c148]{font-size:12.5px;line-height:1.6;color:var(--el-text-color-regular);word-break:break-word}.daily-matrix__tracking-preview[data-v-2663c148]{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px;width:100%;text-align:left}.daily-matrix__tracking-tooltip[data-v-2663c148]{max-width:320px}.daily-matrix__tracking-tooltip-line[data-v-2663c148]{font-size:12.5px;line-height:1.6;word-break:break-word}@media(max-width:768px){.daily-matrix[data-v-2663c148],.daily-matrix__chart[data-v-2663c148]{padding:12px}.daily-matrix__chart-canvas[data-v-2663c148]{height:240px}}
|
||||
+2
File diff suppressed because one or more lines are too long
+2
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
.diagnosis-todo-list .toolbar[data-v-e71c3261]{display:flex;align-items:center;flex-wrap:wrap;gap:8px;margin-bottom:12px}.diagnosis-todo-list .todo-table[data-v-e71c3261]{width:100%}.diagnosis-todo-list .pagination-wrap[data-v-e71c3261]{margin-top:12px;display:flex;justify-content:flex-end}.diagnosis-todo-list .text-danger[data-v-e71c3261]{color:var(--el-color-danger)}.diagnosis-todo-list .text-muted[data-v-e71c3261]{color:var(--el-text-color-placeholder)}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
import{_ as o}from"./GancaoSubmissionReconcileButton.vue_vue_type_script_setup_true_lang-CNaRO1Pw.js";import"./element-plus-8nruJdow.js";import"./@vue/runtime-dom-DDAG46FW.js";import"./lodash-D3kF6u-c.js";import"./@vue/runtime-core-C6bnekPw.js";import"./@vue/reactivity-DiY1c2vO.js";import"./@vue/shared-mAAVTE9n.js";import"./@element-plus/icons-vue-CbYn5zW9.js";import"./lodash-es-C2A-Pj28.js";import"./@popperjs/core-C5az9QE8.js";import"./dayjs-DG77mNTn.js";import"./@ctrl/tinycolor-BuyEbX8F.js";import"./async-validator-CFA_igpM.js";import"./normalize-wheel-es-BQoi3Ox2.js";import"./tcm-BFeJYLDf.js";import"./index-XBs6Ys9P.js";import"./jspdf-BsthCvR5.js";import"./@babel/runtime-BanGtE2-.js";import"./fflate-_ayOYiT1.js";import"./vue-router-QlpZ4wdW.js";import"./pinia-B8cvXbiZ.js";import"./axios-C80V62Fs.js";import"./@vueuse/core-1S4fJlii.js";import"./@vueuse/shared-Cl3lVqjz.js";import"./css-color-function-DI01JAaZ.js";import"./balanced-match-BdS7OldZ.js";import"./color-B2zxaWkI.js";import"./clone-DBZ6_OiU.js";import"./color-convert-OrFsTA_V.js";import"./color-name-Dju3oUBS.js";import"./color-string-pUQDDJII.js";import"./ms-CzQ2E3wO.js";import"./vue-clipboard3-DByT_rEQ.js";import"./clipboard-CHgxszqY.js";import"./echarts-CNLwa9wG.js";import"./tslib-BDyQ-Jie.js";import"./zrender-DRNXw7y3.js";import"./highlight.js-Bxt7hFFy.js";import"./@highlightjs/vue-plugin-C4onkBvW.js";export{o as default};
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as o}from"./GancaoSubmissionReconcileButton.vue_vue_type_script_setup_true_lang-E9Q9rJ_a.js";import"./element-plus-8nruJdow.js";import"./@vue/runtime-dom-DDAG46FW.js";import"./lodash-D3kF6u-c.js";import"./@vue/runtime-core-C6bnekPw.js";import"./@vue/reactivity-DiY1c2vO.js";import"./@vue/shared-mAAVTE9n.js";import"./@element-plus/icons-vue-CbYn5zW9.js";import"./lodash-es-C2A-Pj28.js";import"./@popperjs/core-C5az9QE8.js";import"./dayjs-DG77mNTn.js";import"./@ctrl/tinycolor-BuyEbX8F.js";import"./async-validator-CFA_igpM.js";import"./normalize-wheel-es-BQoi3Ox2.js";import"./tcm-BCsm1G3I.js";import"./index-CxCSQGvq.js";import"./jspdf-BsthCvR5.js";import"./@babel/runtime-BanGtE2-.js";import"./fflate-_ayOYiT1.js";import"./vue-router-QlpZ4wdW.js";import"./pinia-B8cvXbiZ.js";import"./axios-C80V62Fs.js";import"./@vueuse/core-1S4fJlii.js";import"./@vueuse/shared-Cl3lVqjz.js";import"./css-color-function-DI01JAaZ.js";import"./balanced-match-BdS7OldZ.js";import"./color-B2zxaWkI.js";import"./clone-DBZ6_OiU.js";import"./color-convert-OrFsTA_V.js";import"./color-name-Dju3oUBS.js";import"./color-string-pUQDDJII.js";import"./ms-CzQ2E3wO.js";import"./vue-clipboard3-DByT_rEQ.js";import"./clipboard-CHgxszqY.js";import"./echarts-CNLwa9wG.js";import"./tslib-BDyQ-Jie.js";import"./zrender-DRNXw7y3.js";import"./highlight.js-Bxt7hFFy.js";import"./@highlightjs/vue-plugin-C4onkBvW.js";export{o as default};
|
||||
+1
@@ -0,0 +1 @@
|
||||
import{d as F,B as U,H as k,G as M,F as D,K as G,S as B,A}from"./element-plus-8nruJdow.js";import{s as P}from"./@vue/runtime-dom-DDAG46FW.js";import{p as q}from"./tcm-BFeJYLDf.js";import{h as f}from"./index-XBs6Ys9P.js";import{f as T,as as H,ak as C,I as K,F as L,aP as z,G as N,aN as t,O as u,a as r,H as b,A as W}from"./@vue/runtime-core-C6bnekPw.js";import{n as g,r as $}from"./@vue/reactivity-DiY1c2vO.js";const h=T({__name:"GancaoSubmissionReconcileButton",props:{order:{}},emits:["resolved"],setup(v,{emit:y}){const d=v,V=y,w=W(()=>{var m,p,a;const i=String(((m=d.order)==null?void 0:m.pharmacy_claim_target)||"").trim().toLowerCase(),e=String(((p=d.order)==null?void 0:p.pharmacy_claim_status)||"").trim().toUpperCase(),n=Number(((a=d.order)==null?void 0:a.pharmacy_claim_lease_expires_at)||0),c=e==="PENDING"&&n>0&&n<=Math.floor(Date.now()/1e3);return i==="gancao"&&(c||["UNKNOWN","PENDING_RECONCILE"].includes(e))}),s=g(!1),_=g(!1),o=$({resolution:"CONFIRM_SUCCESS",remote_order_no:"",note:""});function I(){o.resolution="CONFIRM_SUCCESS",o.remote_order_no="",o.note="",s.value=!0}async function S(){var e;const i=Number((e=d.order)==null?void 0:e.id);if(i){if(o.resolution==="CONFIRM_SUCCESS"&&!o.remote_order_no.trim()){f.msgError("请填写甘草药方单号");return}if(!o.note.trim()){f.msgError("请填写甘草后台核对依据");return}_.value=!0;try{await q({id:i,resolution:o.resolution,remote_order_no:o.resolution==="CONFIRM_SUCCESS"?o.remote_order_no.trim():"",note:o.note.trim()}),f.msgSuccess("甘草提交核对已记录"),s.value=!1,V("resolved")}catch{}finally{_.value=!1}}}return(i,e)=>{const n=F,c=k,m=B,p=G,a=D,E=A,O=M,R=U,x=H("perms");return w.value?(C(),K(L,{key:0},[z((C(),N(n,{type:"danger",size:"small",plain:"",onClick:I},{default:t(()=>[...e[5]||(e[5]=[u("核对甘草提交",-1)])]),_:1})),[[x,["tcm.prescriptionOrder/confirmGancaoSubmission"]]]),r(R,{modelValue:s.value,"onUpdate:modelValue":e[4]||(e[4]=l=>s.value=l),title:"人工核对甘草提交",width:"min(92vw, 520px)","append-to-body":"","destroy-on-close":"","close-on-click-modal":!1},{footer:t(()=>[r(n,{onClick:e[3]||(e[3]=l=>s.value=!1)},{default:t(()=>[...e[8]||(e[8]=[u("取消",-1)])]),_:1}),r(n,{type:"primary",loading:_.value,onClick:S},{default:t(()=>[...e[9]||(e[9]=[u("确认并记录",-1)])]),_:1},8,["loading"])]),default:t(()=>[r(c,{title:"请先在甘草后台核对。本操作会写入不可变更的审计记录。",type:"warning",closable:!1,"show-icon":"",class:"mb-4"}),r(O,{"label-width":"100px",onSubmit:P(S,["prevent"])},{default:t(()=>[r(a,{label:"核对结果",required:""},{default:t(()=>[r(p,{modelValue:o.resolution,"onUpdate:modelValue":e[0]||(e[0]=l=>o.resolution=l)},{default:t(()=>[r(m,{label:"CONFIRM_SUCCESS"},{default:t(()=>[...e[6]||(e[6]=[u("确认已创建",-1)])]),_:1}),r(m,{label:"CONFIRM_NOT_CREATED"},{default:t(()=>[...e[7]||(e[7]=[u("确认未创建",-1)])]),_:1})]),_:1},8,["modelValue"])]),_:1}),o.resolution==="CONFIRM_SUCCESS"?(C(),N(a,{key:0,label:"甘草单号",required:""},{default:t(()=>[r(E,{modelValue:o.remote_order_no,"onUpdate:modelValue":e[1]||(e[1]=l=>o.remote_order_no=l),maxlength:"64",clearable:""},null,8,["modelValue"])]),_:1})):b("",!0),r(a,{label:"核对依据",required:""},{default:t(()=>[r(E,{modelValue:o.note,"onUpdate:modelValue":e[2]||(e[2]=l=>o.note=l),type:"textarea",rows:3,maxlength:"1000","show-word-limit":"",placeholder:"例如:核对时间、甘草后台查询条件及结果"},null,8,["modelValue"])]),_:1})]),_:1})]),_:1},8,["modelValue"])],64)):b("",!0)}}});export{h as _};
|
||||
+1
@@ -0,0 +1 @@
|
||||
import{d as F,B as U,H as k,G as M,F as D,K as G,S as B,A}from"./element-plus-8nruJdow.js";import{s as P}from"./@vue/runtime-dom-DDAG46FW.js";import{p as q}from"./tcm-BCsm1G3I.js";import{h as f}from"./index-CxCSQGvq.js";import{f as T,as as H,ak as C,I as K,F as L,aP as z,G as N,aN as t,O as u,a as r,H as b,A as W}from"./@vue/runtime-core-C6bnekPw.js";import{n as g,r as $}from"./@vue/reactivity-DiY1c2vO.js";const h=T({__name:"GancaoSubmissionReconcileButton",props:{order:{}},emits:["resolved"],setup(v,{emit:y}){const d=v,V=y,w=W(()=>{var m,p,a;const i=String(((m=d.order)==null?void 0:m.pharmacy_claim_target)||"").trim().toLowerCase(),e=String(((p=d.order)==null?void 0:p.pharmacy_claim_status)||"").trim().toUpperCase(),n=Number(((a=d.order)==null?void 0:a.pharmacy_claim_lease_expires_at)||0),c=e==="PENDING"&&n>0&&n<=Math.floor(Date.now()/1e3);return i==="gancao"&&(c||["UNKNOWN","PENDING_RECONCILE"].includes(e))}),s=g(!1),_=g(!1),o=$({resolution:"CONFIRM_SUCCESS",remote_order_no:"",note:""});function I(){o.resolution="CONFIRM_SUCCESS",o.remote_order_no="",o.note="",s.value=!0}async function S(){var e;const i=Number((e=d.order)==null?void 0:e.id);if(i){if(o.resolution==="CONFIRM_SUCCESS"&&!o.remote_order_no.trim()){f.msgError("请填写甘草药方单号");return}if(!o.note.trim()){f.msgError("请填写甘草后台核对依据");return}_.value=!0;try{await q({id:i,resolution:o.resolution,remote_order_no:o.resolution==="CONFIRM_SUCCESS"?o.remote_order_no.trim():"",note:o.note.trim()}),f.msgSuccess("甘草提交核对已记录"),s.value=!1,V("resolved")}catch{}finally{_.value=!1}}}return(i,e)=>{const n=F,c=k,m=B,p=G,a=D,E=A,O=M,R=U,x=H("perms");return w.value?(C(),K(L,{key:0},[z((C(),N(n,{type:"danger",size:"small",plain:"",onClick:I},{default:t(()=>[...e[5]||(e[5]=[u("核对甘草提交",-1)])]),_:1})),[[x,["tcm.prescriptionOrder/confirmGancaoSubmission"]]]),r(R,{modelValue:s.value,"onUpdate:modelValue":e[4]||(e[4]=l=>s.value=l),title:"人工核对甘草提交",width:"min(92vw, 520px)","append-to-body":"","destroy-on-close":"","close-on-click-modal":!1},{footer:t(()=>[r(n,{onClick:e[3]||(e[3]=l=>s.value=!1)},{default:t(()=>[...e[8]||(e[8]=[u("取消",-1)])]),_:1}),r(n,{type:"primary",loading:_.value,onClick:S},{default:t(()=>[...e[9]||(e[9]=[u("确认并记录",-1)])]),_:1},8,["loading"])]),default:t(()=>[r(c,{title:"请先在甘草后台核对。本操作会写入不可变更的审计记录。",type:"warning",closable:!1,"show-icon":"",class:"mb-4"}),r(O,{"label-width":"100px",onSubmit:P(S,["prevent"])},{default:t(()=>[r(a,{label:"核对结果",required:""},{default:t(()=>[r(p,{modelValue:o.resolution,"onUpdate:modelValue":e[0]||(e[0]=l=>o.resolution=l)},{default:t(()=>[r(m,{label:"CONFIRM_SUCCESS"},{default:t(()=>[...e[6]||(e[6]=[u("确认已创建",-1)])]),_:1}),r(m,{label:"CONFIRM_NOT_CREATED"},{default:t(()=>[...e[7]||(e[7]=[u("确认未创建",-1)])]),_:1})]),_:1},8,["modelValue"])]),_:1}),o.resolution==="CONFIRM_SUCCESS"?(C(),N(a,{key:0,label:"甘草单号",required:""},{default:t(()=>[r(E,{modelValue:o.remote_order_no,"onUpdate:modelValue":e[1]||(e[1]=l=>o.remote_order_no=l),maxlength:"64",clearable:""},null,8,["modelValue"])]),_:1})):b("",!0),r(a,{label:"核对依据",required:""},{default:t(()=>[r(E,{modelValue:o.note,"onUpdate:modelValue":e[2]||(e[2]=l=>o.note=l),type:"textarea",rows:3,maxlength:"1000","show-word-limit":"",placeholder:"例如:核对时间、甘草后台查询条件及结果"},null,8,["modelValue"])]),_:1})]),_:1})]),_:1},8,["modelValue"])],64)):b("",!0)}}});export{h as _};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
import{_ as o}from"./MediaSourceSelect.vue_vue_type_script_setup_true_lang-vTXo8BEz.js";import"./element-plus-8nruJdow.js";import"./@vue/runtime-dom-DDAG46FW.js";import"./lodash-D3kF6u-c.js";import"./@vue/runtime-core-C6bnekPw.js";import"./@vue/reactivity-DiY1c2vO.js";import"./@vue/shared-mAAVTE9n.js";import"./@element-plus/icons-vue-CbYn5zW9.js";import"./lodash-es-C2A-Pj28.js";import"./@popperjs/core-C5az9QE8.js";import"./dayjs-DG77mNTn.js";import"./@ctrl/tinycolor-BuyEbX8F.js";import"./async-validator-CFA_igpM.js";import"./normalize-wheel-es-BQoi3Ox2.js";export{o as default};
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
import{N as g,M as V}from"./element-plus-8nruJdow.js";import{f as C,ak as o,G as s,aN as v,I as p,F as h,ap as B,H as k,A as m}from"./@vue/runtime-core-C6bnekPw.js";import{y as c}from"./@vue/reactivity-DiY1c2vO.js";import{p as w,o as S}from"./@vue/shared-mAAVTE9n.js";const F=C({__name:"MediaSourceSelect",props:{modelValue:{default:""},options:{},loading:{type:Boolean,default:!1},placeholder:{default:"请选择自媒体来源"},clearable:{type:Boolean,default:!0},filterable:{type:Boolean,default:!0},allowCreate:{type:Boolean,default:!1},disabled:{type:Boolean,default:!1},selectClass:{},selectStyle:{}},emits:["update:modelValue","change","visible-change"],setup(e,{emit:i}){const u=e,n=i,d=m(()=>(u.options||[]).map(l=>typeof l=="string"?{name:l}:{name:l.name,value:l.value})),f=m(()=>d.value.some(l=>l.name===u.modelValue)),b=l=>{n("visible-change",l)};return(l,t)=>{const r=g,y=V;return o(),s(y,{"model-value":e.modelValue,placeholder:e.placeholder,clearable:e.clearable,filterable:e.filterable,"allow-create":e.allowCreate,"default-first-option":e.allowCreate,disabled:e.disabled,loading:e.loading,class:S(e.selectClass),style:w(e.selectStyle),"onUpdate:modelValue":t[0]||(t[0]=a=>n("update:modelValue",a)),onChange:t[1]||(t[1]=a=>n("change",a)),onVisibleChange:b},{default:v(()=>[(o(!0),p(h,null,B(c(d),a=>(o(),s(r,{key:a.name,label:a.name,value:a.name},null,8,["label","value"]))),128)),e.modelValue&&!c(f)?(o(),s(r,{key:`__legacy_${e.modelValue}`,label:`${e.modelValue}(已停用)`,value:e.modelValue},null,8,["label","value"])):k("",!0)]),_:1},8,["model-value","placeholder","clearable","filterable","allow-create","default-first-option","disabled","loading","class","style"])}}});export{F as _};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user