cb9d836227
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
535 lines
18 KiB
React
535 lines
18 KiB
React
// WeyAi 客户端授权页 /client/authorize(方案 4.4)。
|
||
// - 自带登录判断,不套 PrivateRoute(PrivateRoute 总是去企业登录页)。
|
||
// - client_id / redirect_uri 不合法时只报错、不做任何跳转。
|
||
// - 所有跳转地址都用服务端返回的 redirect,页面绝不自己拼 redirect_uri。
|
||
// - 页面禁止被嵌入:服务端应下发 X-Frame-Options / frame-ancestors,这里再做前端兜底。
|
||
|
||
import React, {
|
||
useCallback,
|
||
useContext,
|
||
useEffect,
|
||
useMemo,
|
||
useRef,
|
||
useState,
|
||
} from 'react';
|
||
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
|
||
import { useTranslation } from 'react-i18next';
|
||
import { Banner, Button, Typography } from '@/components/ui';
|
||
import { Monitor } from 'lucide-react';
|
||
import { API } from '../../helpers/api';
|
||
import { clearUserData, getLogo } from '../../helpers';
|
||
import { UserContext } from '../../context/User';
|
||
import GlassCard from '../../components/auth/GlassCard';
|
||
import AuthCardHeader from '../../components/auth/AuthCardHeader';
|
||
import AuthBackground from '../../components/common/AuthBackground';
|
||
import ScopeOptionList from './ScopeOptionList';
|
||
import WeyAiHandoff, {
|
||
HANDOFF_STAGE_ISSUING,
|
||
HANDOFF_STAGE_LOADING,
|
||
HANDOFF_STAGE_REDIRECT,
|
||
} from './WeyAiHandoff';
|
||
import { fetchOAuthContext, submitAuthorize } from './clientAuthorizeApi';
|
||
import {
|
||
DESKTOP_CLIENT_ID,
|
||
buildLoginTarget,
|
||
isAllowedRedirect,
|
||
optionKey,
|
||
parseClientApiError,
|
||
readAuthorizeParams,
|
||
} from './authorizeParams';
|
||
|
||
const { Text } = Typography;
|
||
|
||
// 被 iframe 嵌入时(点击劫持)不渲染任何可操作内容,并尝试跳出框架。
|
||
function detectFramed() {
|
||
try {
|
||
return window.self !== window.top;
|
||
} catch (_e) {
|
||
return true;
|
||
}
|
||
}
|
||
|
||
const ClientAuthorize = () => {
|
||
const { t } = useTranslation();
|
||
const navigate = useNavigate();
|
||
const location = useLocation();
|
||
const [searchParams] = useSearchParams();
|
||
const [, userDispatch] = useContext(UserContext);
|
||
const logo = getLogo();
|
||
|
||
const params = useMemo(
|
||
() => readAuthorizeParams(searchParams),
|
||
[searchParams],
|
||
);
|
||
const isDesktop = params.client_id === DESKTOP_CLIENT_ID;
|
||
const currentPath = `${location.pathname}${location.search}`;
|
||
|
||
const [framed] = useState(detectFramed);
|
||
// phase: loading | fatal | ready | submitting | done
|
||
const [phase, setPhase] = useState('loading');
|
||
const [fatalMessage, setFatalMessage] = useState('');
|
||
const [context, setContext] = useState(null);
|
||
const [selected, setSelected] = useState('');
|
||
const [inlineError, setInlineError] = useState('');
|
||
const [doneInfo, setDoneInfo] = useState(null);
|
||
const autoSubmittedRef = useRef(false);
|
||
|
||
const reasonText = useCallback(
|
||
(reason) => {
|
||
switch (reason) {
|
||
case 'org_only_no_org':
|
||
case 'org_only':
|
||
return t('当前账号仅能使用企业资源,但没有可用的企业');
|
||
case 'web_access_denied':
|
||
return t('你的账号暂未开通 WeyAi 网页端,请联系管理员');
|
||
case 'super_admin':
|
||
return t('超级管理员只能使用个人范围');
|
||
case 'not_member':
|
||
return t('你已不是该企业的成员');
|
||
case 'org_unusable':
|
||
return t('该企业当前不可用(已冻结、欠费或待审核)');
|
||
default:
|
||
return t('当前账号没有可用的使用范围');
|
||
}
|
||
},
|
||
[t],
|
||
);
|
||
|
||
const goLogin = useCallback(() => {
|
||
// 服务端判定未登录时,本地缓存的登录态已失效:清掉,否则 /login 的
|
||
// AuthRedirect 会把「看起来已登录」的用户弹到体验中心,回不到授权页。
|
||
clearUserData();
|
||
userDispatch({ type: 'logout' });
|
||
navigate(buildLoginTarget(params.scope_hint, currentPath), {
|
||
replace: true,
|
||
});
|
||
}, [currentPath, navigate, params.scope_hint, userDispatch]);
|
||
|
||
const loadContext = useCallback(async () => {
|
||
setPhase('loading');
|
||
setInlineError('');
|
||
if (!params.client_id || !params.redirect_uri) {
|
||
setFatalMessage(t('授权请求无效:缺少客户端或回调地址'));
|
||
setPhase('fatal');
|
||
return;
|
||
}
|
||
// 与后端 Authorize 的必填项对齐。缺这几个参数时后端一定拒绝,不先拦住
|
||
// 就会让用户选完范围、点了"允许"才看到报错,而且无从补救
|
||
if (
|
||
!params.state ||
|
||
!params.code_challenge ||
|
||
params.code_challenge_method !== 'S256'
|
||
) {
|
||
setFatalMessage(t('授权请求无效:缺少必要的安全参数'));
|
||
setPhase('fatal');
|
||
return;
|
||
}
|
||
try {
|
||
const data = await fetchOAuthContext(params);
|
||
const options = Array.isArray(data?.options) ? data.options : [];
|
||
setContext({ ...data, options });
|
||
const preferred = data?.default_option
|
||
? optionKey(data.default_option)
|
||
: '';
|
||
const hasPreferred = options.some(
|
||
(option) => optionKey(option) === preferred,
|
||
);
|
||
setSelected(
|
||
hasPreferred ? preferred : options[0] ? optionKey(options[0]) : '',
|
||
);
|
||
setPhase('ready');
|
||
} catch (error) {
|
||
const err = parseClientApiError(error);
|
||
if (err.code === 'INVALID_CLIENT') {
|
||
setFatalMessage(t('授权请求无效:客户端或回调地址不合法'));
|
||
setPhase('fatal');
|
||
return;
|
||
}
|
||
// weyai-remote(公网访问):后台总开关关闭
|
||
if (err.code === 'REMOTE_DISABLED') {
|
||
setFatalMessage(t('WeyAi 公网访问暂未开放,请联系管理员'));
|
||
setPhase('fatal');
|
||
return;
|
||
}
|
||
if (err.code === 'UNAUTHENTICATED' || err.status === 401) {
|
||
goLogin();
|
||
return;
|
||
}
|
||
if (err.code === 'INVALID_REQUEST') {
|
||
setFatalMessage(t('授权请求参数有误'));
|
||
} else if (err.code === 'RATE_LIMITED') {
|
||
setFatalMessage(t('请求过于频繁,请稍后再试'));
|
||
} else {
|
||
setFatalMessage(err.message || t('加载授权信息失败,请稍后重试'));
|
||
}
|
||
setPhase('fatal');
|
||
}
|
||
}, [goLogin, params, t]);
|
||
|
||
// 只在进入页面(或地址参数变化)时加载一次;切换语言等导致的回调重建不重复拉取
|
||
const loadedForRef = useRef('');
|
||
useEffect(() => {
|
||
if (framed) {
|
||
try {
|
||
window.top.location.replace(window.location.href);
|
||
} catch (_e) {
|
||
// 跨域父页面不允许改写 location,保持不渲染操作按钮即可
|
||
}
|
||
return;
|
||
}
|
||
if (loadedForRef.current === location.search) return;
|
||
loadedForRef.current = location.search;
|
||
loadContext();
|
||
}, [framed, loadContext, location.search]);
|
||
|
||
const followRedirect = useCallback(
|
||
(redirect, denied) => {
|
||
if (!isAllowedRedirect(redirect)) {
|
||
setFatalMessage(t('服务端返回的跳转地址无效'));
|
||
setPhase('fatal');
|
||
return;
|
||
}
|
||
// 拒绝授权与"没有网页端权限"都是 200 + redirect,只有回跳地址里的
|
||
// error= 能区分。不看它就会在被拒时显示"授权完成,正在跳转"
|
||
let refused = denied;
|
||
if (!refused) {
|
||
try {
|
||
refused = !!new URL(
|
||
redirect,
|
||
window.location.origin,
|
||
).searchParams.get('error');
|
||
} catch {
|
||
refused = false;
|
||
}
|
||
}
|
||
setDoneInfo({ redirect, denied: refused });
|
||
setPhase('done');
|
||
window.location.replace(redirect);
|
||
},
|
||
[t],
|
||
);
|
||
|
||
const submit = useCallback(
|
||
async ({ deny = false, optionKeyValue } = {}) => {
|
||
const option = context?.options?.find(
|
||
(item) => optionKey(item) === (optionKeyValue || selected),
|
||
);
|
||
if (!deny && !option) {
|
||
setInlineError(t('请选择使用范围'));
|
||
return;
|
||
}
|
||
setPhase('submitting');
|
||
setInlineError('');
|
||
const payload = {
|
||
client_id: params.client_id,
|
||
redirect_uri: params.redirect_uri,
|
||
state: params.state,
|
||
code_challenge: params.code_challenge,
|
||
code_challenge_method: params.code_challenge_method,
|
||
scope: option ? option.scope : 'personal',
|
||
org_id: option ? Number(option.org_id) || 0 : 0,
|
||
};
|
||
if (params.device_name) payload.device_name = params.device_name;
|
||
if (deny) payload.deny = true;
|
||
try {
|
||
const data = await submitAuthorize(payload);
|
||
followRedirect(data?.redirect, deny);
|
||
} catch (error) {
|
||
const err = parseClientApiError(error);
|
||
if (err.code === 'UNAUTHENTICATED') {
|
||
goLogin();
|
||
return;
|
||
}
|
||
if (err.code === 'INVALID_CLIENT') {
|
||
setFatalMessage(t('授权请求无效:客户端或回调地址不合法'));
|
||
setPhase('fatal');
|
||
return;
|
||
}
|
||
if (err.code === 'REMOTE_DISABLED') {
|
||
setFatalMessage(t('WeyAi 公网访问暂未开放,请联系管理员'));
|
||
setPhase('fatal');
|
||
return;
|
||
}
|
||
if (err.code === 'SCOPE_NOT_ALLOWED') {
|
||
// 可选范围可能已变化(例如刚被移出企业),重新拉取后再让用户选
|
||
await loadContext();
|
||
setInlineError(reasonText(err.data?.reason));
|
||
return;
|
||
}
|
||
if (err.code === 'WEB_ACCESS_DENIED') {
|
||
setInlineError(reasonText('web_access_denied'));
|
||
} else if (err.code === 'RATE_LIMITED') {
|
||
setInlineError(t('请求过于频繁,请稍后再试'));
|
||
} else if (err.code === 'INVALID_REQUEST') {
|
||
setInlineError(t('授权请求参数有误'));
|
||
} else {
|
||
setInlineError(err.message || t('授权失败,请稍后重试'));
|
||
}
|
||
setPhase('ready');
|
||
}
|
||
},
|
||
[
|
||
context,
|
||
followRedirect,
|
||
goLogin,
|
||
loadContext,
|
||
params,
|
||
reasonText,
|
||
selected,
|
||
t,
|
||
],
|
||
);
|
||
|
||
// 网页端可以静默签发的条件:服务端要求静默、有默认范围、且默认范围确实在
|
||
// 可选范围里。最后一条与自动提交 effect 共用:只在 effect 里判会让"默认项
|
||
// 不在可选范围"时自动提交被跳过、而过渡画面仍以为在签发,页面永久停在
|
||
// "正在进入"且没有任何可操作项。不满足就回卡片让用户手选。
|
||
const silentKey =
|
||
!isDesktop && context?.silent && context?.default_option
|
||
? optionKey(context.default_option)
|
||
: '';
|
||
const canAutoSubmit =
|
||
!!silentKey &&
|
||
(context?.options || []).some((option) => optionKey(option) === silentKey);
|
||
|
||
// 网页端:默认范围可用且未要求强制选择时直接签发,不显示页面
|
||
useEffect(() => {
|
||
if (phase !== 'ready' || !canAutoSubmit || autoSubmittedRef.current) {
|
||
return;
|
||
}
|
||
autoSubmittedRef.current = true;
|
||
submit({ optionKeyValue: silentKey });
|
||
}, [canAutoSubmit, phase, silentKey, submit]);
|
||
|
||
const switchAccount = useCallback(async () => {
|
||
setPhase('submitting');
|
||
try {
|
||
await API.get('/api/user/logout', { skipErrorHandler: true });
|
||
} catch (_e) {
|
||
// 退出失败也回登录页,由登录页重新建立会话
|
||
}
|
||
goLogin();
|
||
}, [goLogin]);
|
||
|
||
const clientName =
|
||
context?.client_name || (isDesktop ? t('WeyAi 桌面端') : 'WeyAi');
|
||
const busy = phase === 'submitting';
|
||
const silentPending =
|
||
canAutoSubmit &&
|
||
(phase === 'ready' || phase === 'submitting') &&
|
||
!inlineError;
|
||
|
||
// 三个没有任何可操作内容的瞬态走整页过渡画面(WeyAiHandoff),不再套登录
|
||
// 卡片:拉授权信息 → 静默签发 → 授权完成等浏览器跳走。桌面端授权完成后
|
||
// 要停在页面上给"没有自动打开"的按钮,被拒也要停下来告知,都不算瞬态。
|
||
let handoffStage = null;
|
||
if (!framed) {
|
||
if (phase === 'loading') handoffStage = HANDOFF_STAGE_LOADING;
|
||
else if (silentPending) handoffStage = HANDOFF_STAGE_ISSUING;
|
||
else if (phase === 'done' && !isDesktop && !doneInfo?.denied) {
|
||
handoffStage = HANDOFF_STAGE_REDIRECT;
|
||
}
|
||
}
|
||
|
||
const renderBody = () => {
|
||
if (framed) {
|
||
return (
|
||
<Banner
|
||
type='danger'
|
||
closeIcon={null}
|
||
description={t('出于安全原因,授权页不能在其他页面中打开')}
|
||
/>
|
||
);
|
||
}
|
||
|
||
if (phase === 'fatal') {
|
||
return (
|
||
<div className='flex flex-col gap-4'>
|
||
<Banner type='danger' closeIcon={null} description={fatalMessage} />
|
||
<Button block onClick={() => navigate('/', { replace: true })}>
|
||
{t('返回首页')}
|
||
</Button>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
if (phase === 'done') {
|
||
return (
|
||
<div className='flex flex-col gap-4 items-center text-center'>
|
||
<Text>
|
||
{doneInfo?.denied
|
||
? t('已拒绝授权,可以关闭此页面')
|
||
: isDesktop
|
||
? t('授权完成,请回到 WeyAi 桌面端继续')
|
||
: t('授权完成,正在跳转…')}
|
||
</Text>
|
||
{isDesktop && !doneInfo?.denied && (
|
||
<Button
|
||
theme='light'
|
||
block
|
||
onClick={() => window.location.replace(doneInfo.redirect)}
|
||
>
|
||
{t('没有自动打开?点此打开 WeyAi')}
|
||
</Button>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
const options = context?.options || [];
|
||
const displayName = context?.user?.display_name || '';
|
||
|
||
return (
|
||
<div className='flex flex-col gap-4'>
|
||
{displayName && (
|
||
<div className='flex items-center justify-between gap-2 text-sm'>
|
||
<Text type='tertiary'>{t('当前账号')}</Text>
|
||
<Text strong ellipsis={{ showTooltip: true }}>
|
||
{displayName}
|
||
</Text>
|
||
</div>
|
||
)}
|
||
|
||
{options.length === 0 ? (
|
||
<Banner
|
||
type='warning'
|
||
closeIcon={null}
|
||
description={reasonText(context?.no_option_reason)}
|
||
/>
|
||
) : (
|
||
<div className='flex flex-col gap-2'>
|
||
<Text type='tertiary' size='small'>
|
||
{t('选择使用范围')}
|
||
</Text>
|
||
<ScopeOptionList
|
||
options={options}
|
||
value={selected}
|
||
onChange={setSelected}
|
||
disabled={busy}
|
||
/>
|
||
</div>
|
||
)}
|
||
|
||
{isDesktop && params.device_name && (
|
||
<div className='flex items-center justify-between gap-2 text-sm'>
|
||
<span className='flex items-center gap-1.5'>
|
||
<Monitor size={14} className='text-gray-400' />
|
||
<Text type='tertiary'>{t('设备')}</Text>
|
||
</span>
|
||
<Text ellipsis={{ showTooltip: true }}>{params.device_name}</Text>
|
||
</div>
|
||
)}
|
||
|
||
{inlineError && (
|
||
<Banner type='danger' closeIcon={null} description={inlineError} />
|
||
)}
|
||
|
||
{isDesktop ? (
|
||
<div className='flex flex-col gap-2'>
|
||
<div className='flex gap-2'>
|
||
<Button
|
||
block
|
||
disabled={busy}
|
||
onClick={() => submit({ deny: true })}
|
||
>
|
||
{t('拒绝')}
|
||
</Button>
|
||
<Button
|
||
block
|
||
theme='solid'
|
||
type='primary'
|
||
loading={busy}
|
||
disabled={options.length === 0}
|
||
onClick={() => submit()}
|
||
>
|
||
{t('允许')}
|
||
</Button>
|
||
</div>
|
||
<Button
|
||
block
|
||
theme='borderless'
|
||
disabled={busy}
|
||
onClick={switchAccount}
|
||
>
|
||
{t('切换账号')}
|
||
</Button>
|
||
<Text type='tertiary' size='small' className='text-center'>
|
||
{t('切换账号会退出当前登录,并将同时退出 WeyAi 网页端')}
|
||
</Text>
|
||
</div>
|
||
) : (
|
||
<div className='flex gap-2'>
|
||
<Button
|
||
block
|
||
disabled={busy}
|
||
onClick={() => submit({ deny: true })}
|
||
>
|
||
{t('取消')}
|
||
</Button>
|
||
<Button
|
||
block
|
||
theme='solid'
|
||
type='primary'
|
||
loading={busy}
|
||
disabled={options.length === 0}
|
||
onClick={() => submit()}
|
||
>
|
||
{t('继续')}
|
||
</Button>
|
||
</div>
|
||
)}
|
||
</div>
|
||
);
|
||
};
|
||
|
||
if (handoffStage !== null) {
|
||
const handoffTitle =
|
||
handoffStage === HANDOFF_STAGE_LOADING
|
||
? t('正在加载授权信息')
|
||
: t('正在进入 {{name}}', { name: clientName });
|
||
return (
|
||
<WeyAiHandoff
|
||
logo={logo}
|
||
stage={handoffStage}
|
||
title={handoffTitle}
|
||
// 加载阶段还不知道是静默进入还是要选范围,副标题只说"在确认";
|
||
// 进入签发/跳转阶段才承诺"正在打开工作台"
|
||
subtitle={
|
||
handoffStage === HANDOFF_STAGE_LOADING
|
||
? t('正在确认授权信息,通常只需几秒')
|
||
: t('正在为你打开 {{name}} 工作台,通常只需几秒', {
|
||
name: clientName,
|
||
})
|
||
}
|
||
clientName={clientName}
|
||
/>
|
||
);
|
||
}
|
||
|
||
return (
|
||
<div
|
||
className='relative overflow-hidden flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8'
|
||
style={{ minHeight: 'calc(100vh - var(--content-top-offset, 0px))' }}
|
||
>
|
||
<AuthBackground />
|
||
<div className='w-full max-w-md z-10 flex flex-col items-center'>
|
||
<GlassCard>
|
||
<AuthCardHeader
|
||
wrapperClassName='mb-6'
|
||
logo={logo}
|
||
title={t('登录 {{name}}', { name: clientName })}
|
||
subtitle={
|
||
isDesktop
|
||
? t('确认后将使用此账号登录 WeyAi 桌面端')
|
||
: t('选择进入 WeyAi 时使用的范围')
|
||
}
|
||
/>
|
||
{renderBody()}
|
||
</GlassCard>
|
||
</div>
|
||
</div>
|
||
);
|
||
};
|
||
|
||
export default ClientAuthorize;
|