修复认证验证码投递与登录入口体验 05-27-oa-auth-delivery-wecom-entry-fix

这个提交包含在:
2026-05-27 10:14:49 +08:00
父节点 347d337c0c
当前提交 511efa0b2d
共修改 17 个文件,包含 746 行新增和 63 行删除
+17
查看文件
@@ -57,6 +57,19 @@ export async function verifyEmailLoginCode(payload: { email: string; code: strin
});
}
export type AuthCapabilities = {
emailDelivery: {
ready: boolean;
statusReasons: string[];
};
emailLoginCode: {
enabled: boolean;
};
passwordReset: {
enabled: boolean;
};
};
export type SsoProviderInfo = { id: "oidc"; label: string; enabled: boolean; loginUrl: string };
export type WecomEntryConfig = {
@@ -76,6 +89,10 @@ export async function fetchSsoProviders() {
return apiRequestData<SsoProviderInfo[]>("/api/auth/sso/providers", { auth: false });
}
export async function fetchAuthCapabilities() {
return apiRequestData<AuthCapabilities>("/api/auth/capabilities", { auth: false });
}
export async function fetchWecomConfig() {
return apiRequestData<WecomEntryConfig>("/api/auth/wecom/config", { auth: false });
}
+4
查看文件
@@ -82,6 +82,10 @@ export function mapApiErrorMessage(
return "目标数据不存在或已被删除。";
}
if (code === "SYS_001" && details?.email === "delivery_not_configured") {
return "邮件验证码暂不可用,请使用密码登录或联系管理员。";
}
if (code === "SYS_001") {
return "服务暂不可用,请稍后重试或联系管理员。";
}
+42 -4
查看文件
@@ -1,6 +1,8 @@
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { MailCheck } from "lucide-react";
import { Link, useNavigate } from "react-router-dom";
import { forgotPassword, resetPassword } from "../api/auth";
import { fetchAuthCapabilities, forgotPassword, resetPassword } from "../api/auth";
import { mapApiErrorMessage } from "../api/errorMessages";
import { isApiError } from "../api/types";
import { AuthPanel } from "../components/auth/AuthPanel";
@@ -26,6 +28,15 @@ export function ForgotPasswordPage() {
const [submittingReset, setSubmittingReset] = useState(false);
const [message, setMessage] = useState("");
const [error, setError] = useState("");
const authCapabilitiesQuery = useQuery({
queryKey: ["auth", "capabilities"],
queryFn: () => fetchAuthCapabilities(),
staleTime: 60_000,
});
const emailDeliveryReady = authCapabilitiesQuery.data?.emailDelivery.ready === true;
const emailDeliveryChecking = authCapabilitiesQuery.isLoading;
const emailDeliveryUnavailable = authCapabilitiesQuery.isSuccess && !emailDeliveryReady;
const emailDeliveryUnknown = authCapabilitiesQuery.isError;
async function handleRequestCode(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
@@ -37,12 +48,20 @@ export function ForgotPasswordPage() {
setError("请输入邮箱。");
return;
}
if (!emailDeliveryReady) {
setError(
emailDeliveryChecking
? "正在检查邮件服务,请稍后再试。"
: "邮件验证码暂不可用,请联系管理员处理。",
);
return;
}
setSubmittingCode(true);
try {
await forgotPassword({ email: normalizedEmail });
setCodeRequested(true);
setMessage("如账号可用,验证码将发送到该邮箱。请在有效期内完成重置。");
setMessage("如账号可用,验证码将发送到企业邮箱;请在有效期内完成重置,并查看免提醒邮件。");
} catch (err) {
if (isApiError(err)) {
setError(mapApiErrorMessage(err.code, err.details, err.message));
@@ -118,8 +137,27 @@ export function ForgotPasswordPage() {
/>
</div>
<Button className="w-full" data-testid="forgot-password-request-code" disabled={submittingCode || !email.trim()} type="submit">
{submittingCode ? "发送中..." : codeRequested ? "重新发送验证码" : "发送验证码"}
{!emailDeliveryReady ? (
<div
aria-live="polite"
className="flex gap-3 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm leading-6 text-amber-800"
data-testid="forgot-password-email-delivery-status"
>
<MailCheck aria-hidden="true" className="mt-0.5 h-4 w-4 flex-none" />
<span>
{emailDeliveryChecking
? "正在检查企业邮箱验证码服务。"
: emailDeliveryUnknown
? "暂时无法确认邮件服务,请稍后刷新或联系管理员。"
: emailDeliveryUnavailable
? "邮件验证码暂不可用,请联系管理员处理。"
: "邮件验证码暂不可用。"}
</span>
</div>
) : null}
<Button className="w-full" data-testid="forgot-password-request-code" disabled={submittingCode || !email.trim() || !emailDeliveryReady} type="submit">
{emailDeliveryChecking ? "检查邮件服务..." : submittingCode ? "发送中..." : codeRequested ? "重新发送验证码" : "发送验证码"}
</Button>
</form>
+63 -9
查看文件
@@ -1,7 +1,8 @@
import { useEffect, useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Building2, MailCheck } from "lucide-react";
import { Link, useNavigate, useSearchParams } from "react-router-dom";
import { fetchSsoProviders, fetchWecomConfig, requestEmailLoginCode } from "../api/auth";
import { fetchAuthCapabilities, fetchSsoProviders, fetchWecomConfig, requestEmailLoginCode } from "../api/auth";
import { mapApiErrorMessage } from "../api/errorMessages";
import { isApiError } from "../api/types";
import { useAuth } from "../auth/AuthContext";
@@ -70,6 +71,16 @@ export function LoginPage() {
});
const oidcProvider = (ssoProvidersQuery.data ?? []).find((item) => item.id === "oidc" && item.enabled);
const authCapabilitiesQuery = useQuery({
queryKey: ["auth", "capabilities"],
queryFn: () => fetchAuthCapabilities(),
staleTime: 60_000,
});
const emailDeliveryReady = authCapabilitiesQuery.data?.emailDelivery.ready === true;
const emailDeliveryChecking = authCapabilitiesQuery.isLoading;
const emailDeliveryUnavailable = authCapabilitiesQuery.isSuccess && !emailDeliveryReady;
const emailDeliveryUnknown = authCapabilitiesQuery.isError;
const wecomConfigQuery = useQuery({
queryKey: ["auth", "wecom-config"],
queryFn: () => fetchWecomConfig(),
@@ -85,6 +96,7 @@ export function LoginPage() {
const showWecomPrimary = isWecomContext;
const showPasswordPanel = !showWecomPrimary || Boolean(wecomNotice) || passwordFallbackOpen || (showWecomPrimary && wecomConfig && !wecomEntry);
const showBrowserWecomNotice = !showWecomPrimary && Boolean(wecomEntry);
useEffect(() => {
if (emailCodeCooldown <= 0) {
@@ -140,13 +152,21 @@ export function LoginPage() {
setEmailCodeError("请输入企业邮箱。");
return;
}
if (!emailDeliveryReady) {
setEmailCodeError(
emailDeliveryChecking
? "正在检查邮件服务,请稍后再试。"
: "邮件验证码暂不可用,请使用密码登录或联系管理员。",
);
return;
}
setEmailCodeSending(true);
try {
await requestEmailLoginCode({ email });
setEmailCodeRequested(true);
setEmailCodeCooldown(60);
setEmailCodeMessage("如账号可用,验证码将发送到该邮箱。");
setEmailCodeMessage("如账号可用,验证码将发送到企业邮箱;请同时查看免提醒邮件。");
} catch (err) {
if (isApiError(err)) {
setEmailCodeError(mapApiErrorMessage(err.code, err.details, err.message));
@@ -266,14 +286,41 @@ export function LoginPage() {
<Button
className="w-full"
data-testid="login-email-code-request"
disabled={emailCodeSending || emailCodeCooldown > 0 || !emailLoginEmail.trim()}
disabled={emailCodeSending || emailCodeCooldown > 0 || !emailLoginEmail.trim() || !emailDeliveryReady}
type="submit"
variant="secondary"
>
{emailCodeSending ? "发送中..." : emailCodeCooldown > 0 ? `${emailCodeCooldown} 秒后重发` : emailCodeRequested ? "重新发送验证码" : "发送验证码"}
{emailDeliveryChecking
? "检查邮件服务..."
: emailCodeSending
? "发送中..."
: emailCodeCooldown > 0
? `${emailCodeCooldown} 秒后重发`
: emailCodeRequested
? "重新发送验证码"
: "发送验证码"}
</Button>
</form>
{!emailDeliveryReady ? (
<div
aria-live="polite"
className="flex gap-3 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm leading-6 text-amber-800"
data-testid="login-email-delivery-status"
>
<MailCheck aria-hidden="true" className="mt-0.5 h-4 w-4 flex-none" />
<span>
{emailDeliveryChecking
? "正在检查企业邮箱验证码服务。"
: emailDeliveryUnknown
? "暂时无法确认邮件服务,请使用密码登录或稍后刷新。"
: emailDeliveryUnavailable
? "邮件验证码暂不可用,请使用密码登录或联系管理员。"
: "邮件验证码暂不可用。"}
</span>
</div>
) : null}
<form className="space-y-4" onSubmit={handleEmailCodeLogin}>
<div className="space-y-2">
<Label htmlFor="login-email-code">验证码</Label>
@@ -375,7 +422,7 @@ export function LoginPage() {
: renderPasswordPanel(showWecomPrimary ? "login-password-secondary-panel" : "login-password-primary-panel")
: null}
{!showWecomPrimary && (wecomEntry || oidcProvider) ? (
{!showWecomPrimary && (showBrowserWecomNotice || oidcProvider) ? (
<div className="space-y-3">
<div className="flex items-center gap-3 text-xs text-slate-400">
<span className="h-px flex-1 bg-slate-100" />
@@ -383,10 +430,17 @@ export function LoginPage() {
<span className="h-px flex-1 bg-slate-100" />
</div>
{wecomEntry ? (
<Button className="w-full" data-testid="wecom-entry-secondary" type="button" variant="secondary" onClick={handleWecomLogin}>
企业微信登录
</Button>
{showBrowserWecomNotice ? (
<div
className="flex gap-3 rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm leading-6 text-slate-600"
data-testid="wecom-entry-browser-notice"
>
<Building2 aria-hidden="true" className="mt-0.5 h-4 w-4 flex-none text-primary" />
<div>
<div className="font-medium text-slate-900">企业微信一键进入</div>
<div>请从企业微信工作台打开 OA;普通浏览器使用密码或邮箱验证码。</div>
</div>
</div>
) : null}
{oidcProvider ? (
+60 -8
查看文件
@@ -15,8 +15,30 @@ function envelope(data: unknown) {
};
}
function mockPasswordLogin(page: import("@playwright/test").Page) {
function authCapabilitiesPayload(emailReady = true) {
return {
emailDelivery: {
ready: emailReady,
statusReasons: emailReady ? [] : ["email_disabled"],
},
emailLoginCode: {
enabled: emailReady,
},
passwordReset: {
enabled: emailReady,
},
};
}
function mockPasswordLogin(page: import("@playwright/test").Page, emailReady = true) {
return Promise.all([
page.route("**/api/auth/capabilities", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(envelope(authCapabilitiesPayload(emailReady))),
});
}),
page.route("**/api/auth/sso/providers", async (route) => {
await route.fulfill({
status: 200,
@@ -66,8 +88,15 @@ function mockPasswordLogin(page: import("@playwright/test").Page) {
]);
}
async function mockGuestAuthChrome(page: import("@playwright/test").Page) {
async function mockGuestAuthChrome(page: import("@playwright/test").Page, emailReady = true) {
await Promise.all([
page.route("**/api/auth/capabilities", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(envelope(authCapabilitiesPayload(emailReady))),
});
}),
page.route("**/api/auth/sso/providers", async (route) => {
await route.fulfill({
status: 200,
@@ -397,10 +426,33 @@ test("邮箱验证码登录可发送验证码并进入工作台", async ({ page
expect(verifyPayloads).toEqual([{ email: "[email protected]", code: "654321" }]);
});
test("邮件服务不可用时登录和找回密码禁用验证码发送", async ({ page }) => {
await mockGuestAuthChrome(page, false);
await page.goto("/login");
await page.getByTestId("login-mode-email-code").click();
await expect(page.getByTestId("login-email-delivery-status")).toContainText("邮件验证码暂不可用");
await page.getByTestId("login-email-code-email").fill("[email protected]");
await expect(page.getByTestId("login-email-code-request")).toBeDisabled();
await page.goto("/forgot-password");
await expect(page.getByTestId("forgot-password-email-delivery-status")).toContainText("邮件验证码暂不可用");
await page.getByTestId("forgot-password-email").fill("[email protected]");
await expect(page.getByTestId("forgot-password-request-code")).toBeDisabled();
});
test("找回密码流程使用邮箱验证码重置新密码", async ({ page }) => {
const requestedEmails: string[] = [];
const resetPayloads: unknown[] = [];
await page.route("**/api/auth/capabilities", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(envelope(authCapabilitiesPayload())),
});
});
await page.route("**/api/auth/forgot-password", async (route) => {
const payload = route.request().postDataJSON() as { email?: string };
requestedEmails.push(String(payload.email ?? ""));
@@ -473,10 +525,10 @@ test("Portal 员工视角优先显示今日动作顺序", async ({ page }) => {
await expect(page.locator("summary").filter({ hasText: "我的申请与资产 / 继续工作" })).toBeVisible();
await expect(page.getByRole("tab", { name: "公告" })).toBeVisible();
await expect(page.getByRole("heading", { name: "快捷操作栏" })).toBeVisible();
await expect(page.getByRole("heading", { name: "团队全员状态" })).toBeVisible();
await expect(page.getByRole("heading", { name: "今日待办聚合" })).toBeVisible();
await expect(page.getByRole("heading", { name: "近期动态流" })).toBeVisible();
await expect(page.getByRole("heading", { name: "常用" })).toBeVisible();
await expect(page.getByRole("heading", { name: "团队状态" })).toBeVisible();
await expect(page.getByRole("heading", { name: "待处理" })).toBeVisible();
await expect(page.getByRole("heading", { name: "通知" })).toBeVisible();
});
test("Portal 管理视角重排正确,备用模块默认折叠", async ({ page }) => {
@@ -501,7 +553,7 @@ test("Portal 管理视角重排正确,备用模块默认折叠", async ({ page
"portal-card-weekly_help",
]);
await expect(page.locator("summary").filter({ hasText: "角色重点 / 常用入口" })).toBeVisible();
await expect(page.locator("summary").filter({ hasText: "角色重点" })).toBeVisible();
await expect(page.getByText("试点观测摘要")).toBeVisible();
await expect(page.getByRole("link", { name: "采购申请" })).not.toBeVisible();
await page.locator("summary").filter({ hasText: "备用模块" }).click();
@@ -594,7 +646,7 @@ test("Portal 域管理角色也进入经理视图", async ({ page }) => {
await login(page, EMPLOYEE);
await expect(page.locator("summary").filter({ hasText: "角色重点 / 常用入口" })).toBeVisible();
await expect(page.locator("summary").filter({ hasText: "角色重点" })).toBeVisible();
await expect(page.locator('[aria-label="portal-card-pending_approvals"]')).toBeVisible();
await expect(page.locator('[aria-label="portal-card-team_presence"]')).toBeVisible();
});
+39 -26
查看文件
@@ -15,31 +15,52 @@ function mockWecomConfigPayload() {
};
}
test("E2E 企微入口:普通浏览器下企微按钮为次级入口", async ({ page }) => {
function envelope(data: unknown) {
return {
requestId: "mock-request",
data,
};
}
async function mockAuthBase(page: import("@playwright/test").Page) {
await page.route("**/api/auth/capabilities", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(envelope({
emailDelivery: { ready: true, statusReasons: [] },
emailLoginCode: { enabled: true },
passwordReset: { enabled: true },
})),
});
});
await page.route("**/api/auth/sso/providers", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(envelope([])),
});
});
}
async function mockWecomConfig(page: import("@playwright/test").Page) {
await page.route("**/api/auth/wecom/config", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
requestId: "mock-wecom-config",
data: mockWecomConfigPayload(),
}),
});
});
await page.route("**/api/auth/wecom/login?**", async (route) => {
await route.fulfill({
status: 200,
contentType: "text/plain",
body: "mock wecom login entry",
body: JSON.stringify(envelope(mockWecomConfigPayload())),
});
});
}
test("E2E 企微入口:普通浏览器下只提示企业微信工作台打开", async ({ page }) => {
await mockAuthBase(page);
await mockWecomConfig(page);
await page.goto("/login");
await expect(page.getByTestId("login-password-primary-panel")).toBeVisible();
await expect(page.getByTestId("wecom-entry-secondary")).toBeVisible();
await page.getByTestId("wecom-entry-secondary").click();
await expect(page).toHaveURL(/\/api\/auth\/wecom\/login\?returnTo=/);
await expect(page.getByTestId("wecom-entry-browser-notice")).toContainText("请从企业微信工作台打开 OA");
await expect(page.getByTestId("wecom-entry-secondary")).toHaveCount(0);
});
test("E2E 企微入口:企业微信场景优先显示企微 CTA,并展示未绑定提示", async ({ page }) => {
@@ -49,16 +70,8 @@ test("E2E 企微入口:企业微信场景优先显示企微 CTA,并展示未
value: "Mozilla/5.0 wxwork/4.1.20 MicroMessenger/7.0.1",
});
});
await page.route("**/api/auth/wecom/config", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
requestId: "mock-wecom-config",
data: mockWecomConfigPayload(),
}),
});
});
await mockAuthBase(page);
await mockWecomConfig(page);
await page.route("**/api/auth/wecom/login?**", async (route) => {
await route.fulfill({
status: 200,