oa-login-password-recovery-ux 改进登录找回密码体验

这个提交包含在:
2026-05-26 20:03:47 +08:00
父节点 311c732679
当前提交 cea5fb03c1
共修改 18 个文件,包含 753 行新增和 17 行删除
+18
查看文件
@@ -17,6 +17,24 @@ export async function changePassword(payload: { oldPassword: string; newPassword
});
}
export async function forgotPassword(payload: { email: string }) {
return apiRequestData<Record<string, never>>("/api/auth/forgot-password", {
method: "POST",
auth: false,
headers: JSON_HEADERS,
body: JSON.stringify(payload),
});
}
export async function resetPassword(payload: { email: string; code: string; newPassword: string }) {
return apiRequestData<Record<string, never>>("/api/auth/reset-password", {
method: "POST",
auth: false,
headers: JSON_HEADERS,
body: JSON.stringify(payload),
});
}
export type SsoProviderInfo = { id: "oidc"; label: string; enabled: boolean; loginUrl: string };
export type WecomEntryConfig = {
@@ -0,0 +1,41 @@
import { Eye, EyeOff } from "lucide-react";
import * as React from "react";
import { cn } from "../../lib/utils";
import { Button } from "./button";
import { Input, type InputProps } from "./input";
export type PasswordInputProps = Omit<InputProps, "type"> & {
revealLabel?: string;
hideLabel?: string;
};
export const PasswordInput = React.forwardRef<HTMLInputElement, PasswordInputProps>(
({ className, revealLabel = "显示密码", hideLabel = "隐藏密码", ...props }, ref) => {
const [visible, setVisible] = React.useState(false);
const Icon = visible ? EyeOff : Eye;
const label = visible ? hideLabel : revealLabel;
return (
<div className="relative">
<Input
{...props}
ref={ref}
type={visible ? "text" : "password"}
className={cn("pr-11", className)}
/>
<Button
type="button"
variant="ghost"
size="icon"
aria-label={label}
className="absolute right-1 top-1/2 h-8 w-8 -translate-y-1/2 text-slate-500 hover:text-primary"
onClick={() => setVisible((current) => !current)}
>
<Icon aria-hidden="true" className="h-4 w-4" />
</Button>
</div>
);
},
);
PasswordInput.displayName = "PasswordInput";
+47
查看文件
@@ -0,0 +1,47 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { PWA_UPDATE_READY_EVENT } from "../lib/pwaUpdateEvents";
type PwaUpdateReadyDetail = {
applyUpdate?: () => void | Promise<void>;
};
function resolveApplyUpdate(event: Event) {
const detail = (event as CustomEvent<PwaUpdateReadyDetail>).detail;
return typeof detail?.applyUpdate === "function" ? detail.applyUpdate : null;
}
export function usePwaUpdatePrompt() {
const applyUpdateRef = useRef<(() => void | Promise<void>) | null>(null);
const [updateReady, setUpdateReady] = useState(false);
useEffect(() => {
const handleUpdateReady = (event: Event) => {
applyUpdateRef.current = resolveApplyUpdate(event);
setUpdateReady(true);
};
window.addEventListener(PWA_UPDATE_READY_EVENT, handleUpdateReady);
return () => {
window.removeEventListener(PWA_UPDATE_READY_EVENT, handleUpdateReady);
};
}, []);
const applyUpdate = useCallback(() => {
const handler = applyUpdateRef.current;
if (handler) {
void handler();
return;
}
window.location.reload();
}, []);
const dismissUpdate = useCallback(() => {
setUpdateReady(false);
}, []);
return {
updateReady,
applyUpdate,
dismissUpdate,
};
}
+18
查看文件
@@ -1,13 +1,31 @@
import { Outlet } from "react-router-dom";
import { AppBrand } from "../components/shell/AppBrand";
import { Button } from "../components/ui/button";
import { usePwaUpdatePrompt } from "../hooks/usePwaUpdatePrompt";
export function AuthLayout() {
const { updateReady, applyUpdate, dismissUpdate } = usePwaUpdatePrompt();
return (
<div className="min-h-screen bg-slate-50 px-4 py-8 sm:px-6 lg:px-10">
<div className="mx-auto flex min-h-[calc(100vh-4rem)] max-w-md flex-col justify-center">
<div className="mb-5">
<AppBrand />
</div>
{updateReady ? (
<div className="mb-4 rounded-xl border border-primary/20 bg-primary/5 px-4 py-3 text-sm text-slate-700" data-testid="auth-pwa-update-notice">
<div className="font-medium text-slate-900">系统有新版本</div>
<div className="mt-1 leading-6">完成当前输入后刷新页面即可更新,当前表单不会被自动打断。</div>
<div className="mt-3 flex gap-2">
<Button size="sm" type="button" onClick={applyUpdate}>
现在刷新
</Button>
<Button size="sm" type="button" variant="secondary" onClick={dismissUpdate}>
稍后
</Button>
</div>
</div>
) : null}
<section className="w-full">
<Outlet />
</section>
+1
查看文件
@@ -0,0 +1 @@
export const PWA_UPDATE_READY_EVENT = "hyb-oa:pwa-update-ready";
+4 -7
查看文件
@@ -4,8 +4,8 @@ import { isApiError } from "../api/types";
import { mapApiErrorMessage } from "../api/errorMessages";
import { useAuth } from "../auth/AuthContext";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Label } from "../components/ui/label";
import { PasswordInput } from "../components/ui/password-input";
import { markOnboardingEntryReady } from "../lib/onboardingGuide";
const PASSWORD_REQUIREMENTS = [
@@ -62,26 +62,24 @@ export function ChangePasswordPage() {
<form className="space-y-4" onSubmit={handleSubmit}>
<div className="space-y-1">
<Label htmlFor="oldPassword">旧密码</Label>
<Input
<PasswordInput
autoComplete="current-password"
data-testid="change-password-old"
id="oldPassword"
onChange={(event) => setOldPassword(event.target.value)}
placeholder="请输入旧密码"
type="password"
value={oldPassword}
/>
</div>
<div className="space-y-1">
<Label htmlFor="newPassword">新密码</Label>
<Input
<PasswordInput
autoComplete="new-password"
data-testid="change-password-new"
id="newPassword"
onChange={(event) => setNewPassword(event.target.value)}
placeholder="至少 12 位,建议包含大小写/数字"
type="password"
value={newPassword}
/>
<p className="text-xs text-zinc-500">密码要求:{PASSWORD_REQUIREMENTS.join(";")}。</p>
@@ -98,12 +96,11 @@ export function ChangePasswordPage() {
<div className="space-y-1">
<Label htmlFor="confirmPassword">确认新密码</Label>
<Input
<PasswordInput
autoComplete="new-password"
id="confirmPassword"
onChange={(event) => setConfirmPassword(event.target.value)}
placeholder="再次输入新密码"
type="password"
value={confirmPassword}
/>
</div>
+192
查看文件
@@ -0,0 +1,192 @@
import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { forgotPassword, resetPassword } from "../api/auth";
import { mapApiErrorMessage } from "../api/errorMessages";
import { isApiError } from "../api/types";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Label } from "../components/ui/label";
import { PasswordInput } from "../components/ui/password-input";
const PASSWORD_REQUIREMENTS = [
"至少 12 位",
"包含大写字母、小写字母和数字",
"不要使用公司名、常见顺序或过于简单的组合",
];
export function ForgotPasswordPage() {
const navigate = useNavigate();
const [email, setEmail] = useState("");
const [code, setCode] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [codeRequested, setCodeRequested] = useState(false);
const [submittingCode, setSubmittingCode] = useState(false);
const [submittingReset, setSubmittingReset] = useState(false);
const [message, setMessage] = useState("");
const [error, setError] = useState("");
async function handleRequestCode(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
setError("");
setMessage("");
const normalizedEmail = email.trim();
if (!normalizedEmail) {
setError("请输入邮箱。");
return;
}
setSubmittingCode(true);
try {
await forgotPassword({ email: normalizedEmail });
setCodeRequested(true);
setMessage("如账号可用,验证码将发送到该邮箱。请在有效期内完成重置。");
} catch (err) {
if (isApiError(err)) {
setError(mapApiErrorMessage(err.code, err.details, err.message));
} else {
setError("请求验证码失败,请稍后重试或联系管理员。");
}
} finally {
setSubmittingCode(false);
}
}
async function handleResetPassword(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
setError("");
const normalizedEmail = email.trim();
const normalizedCode = code.trim();
if (!normalizedEmail) {
setError("请输入邮箱。");
return;
}
if (normalizedCode.length !== 6) {
setError("请输入 6 位验证码。");
return;
}
if (newPassword !== confirmPassword) {
setError("两次输入的新密码不一致,请确认后再提交。");
return;
}
setSubmittingReset(true);
try {
await resetPassword({
email: normalizedEmail,
code: normalizedCode,
newPassword,
});
setMessage("密码已重置,请使用新密码登录。");
navigate("/login", { replace: true });
} catch (err) {
if (isApiError(err)) {
setError(mapApiErrorMessage(err.code, err.details, err.message));
} else {
setError("重置密码失败,请稍后重试或联系管理员。");
}
} finally {
setSubmittingReset(false);
}
}
return (
<div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm sm:p-6" data-testid="forgot-password-page">
<div>
<h1 className="text-xl font-semibold text-slate-900">找回密码</h1>
<p className="mt-1 text-sm leading-6 text-slate-500">使用账号邮箱接收验证码,设置新密码后重新登录。</p>
</div>
<form className="mt-6 space-y-4" onSubmit={handleRequestCode}>
<div className="space-y-2">
<Label htmlFor="forgot-password-email">邮箱</Label>
<Input
autoComplete="email"
data-testid="forgot-password-email"
id="forgot-password-email"
onChange={(event) => setEmail(event.target.value)}
placeholder="请输入账号邮箱"
type="email"
value={email}
/>
</div>
<Button className="w-full" data-testid="forgot-password-request-code" disabled={submittingCode || !email.trim()} type="submit">
{submittingCode ? "发送中..." : codeRequested ? "重新发送验证码" : "发送验证码"}
</Button>
</form>
{codeRequested ? (
<form className="mt-5 space-y-4 border-t border-slate-100 pt-5" onSubmit={handleResetPassword}>
<div className="space-y-2">
<Label htmlFor="forgot-password-code">验证码</Label>
<Input
autoComplete="one-time-code"
data-testid="forgot-password-code"
id="forgot-password-code"
inputMode="numeric"
maxLength={6}
onChange={(event) => setCode(event.target.value.replace(/\D/g, "").slice(0, 6))}
placeholder="6 位验证码"
value={code}
/>
</div>
<div className="space-y-2">
<Label htmlFor="forgot-password-new">新密码</Label>
<PasswordInput
autoComplete="new-password"
data-testid="forgot-password-new"
id="forgot-password-new"
onChange={(event) => setNewPassword(event.target.value)}
placeholder="至少 12 位,建议包含大小写/数字"
value={newPassword}
/>
<p className="text-xs text-slate-500">密码要求:{PASSWORD_REQUIREMENTS.join(";")}。</p>
</div>
<div className="space-y-2">
<Label htmlFor="forgot-password-confirm">确认新密码</Label>
<PasswordInput
autoComplete="new-password"
data-testid="forgot-password-confirm"
id="forgot-password-confirm"
onChange={(event) => setConfirmPassword(event.target.value)}
placeholder="再次输入新密码"
value={confirmPassword}
/>
</div>
<Button
className="w-full"
data-testid="forgot-password-submit"
disabled={submittingReset || !email.trim() || code.length !== 6 || !newPassword.trim() || !confirmPassword.trim()}
type="submit"
>
{submittingReset ? "提交中..." : "重置密码"}
</Button>
</form>
) : null}
{message ? (
<div className="mt-4 rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700" data-testid="forgot-password-message">
{message}
</div>
) : null}
{error ? (
<div className="mt-4 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-600" data-testid="forgot-password-error">
{error}
</div>
) : null}
<div className="mt-5 text-center text-sm">
<Link className="font-medium text-primary hover:underline" to="/login">
返回登录
</Link>
</div>
</div>
);
}
+9 -4
查看文件
@@ -1,6 +1,6 @@
import { useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useNavigate, useSearchParams } from "react-router-dom";
import { Link, useNavigate, useSearchParams } from "react-router-dom";
import { fetchSsoProviders, fetchWecomConfig } from "../api/auth";
import { mapApiErrorMessage } from "../api/errorMessages";
import { isApiError } from "../api/types";
@@ -9,6 +9,7 @@ import { getDeviceFingerprint } from "../auth/deviceFingerprint";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Label } from "../components/ui/label";
import { PasswordInput } from "../components/ui/password-input";
import { isWecomWebView, resolveDefaultWorkspacePath } from "../lib/runtimeContext";
import {
buildWecomLoginUrl,
@@ -122,14 +123,18 @@ export function LoginPage() {
</div>
<div className="space-y-2">
<Label htmlFor="login-password">密码</Label>
<Input
<div className="flex items-center justify-between gap-3">
<Label htmlFor="login-password">密码</Label>
<Link className="text-sm font-medium text-primary hover:underline" to="/forgot-password">
忘记密码?
</Link>
</div>
<PasswordInput
autoComplete="current-password"
data-testid="login-password"
id="login-password"
onChange={(event) => setPassword(event.target.value)}
placeholder="请输入密码"
type="password"
value={password}
/>
</div>
+20 -5
查看文件
@@ -1,9 +1,15 @@
import { registerSW } from "virtual:pwa-register";
import { canUseWindow, isEnterpriseMessengerContainer, matchesMedia } from "./lib/runtimeContext";
import { PWA_UPDATE_READY_EVENT } from "./lib/pwaUpdateEvents";
const MOBILE_APPROVAL_TASK_PATH = /^\/workflow\/tasks\/([^/]+)$/i;
const OFFLINE_ALLOWED_PATHS = ["/mobile/approvals"];
const CLEARABLE_CACHE_PREFIXES = ["app-api-runtime", "app-static-runtime", "workbox-precache"];
const AUTH_INPUT_PATHS = ["/login", "/change-password", "/forgot-password", "/reset-password"];
function isAuthInputPath(pathname: string) {
return AUTH_INPUT_PATHS.some((path) => pathname === path || pathname.startsWith(`${path}/`));
}
function bindServiceWorkerUpdateCleanup(registration: ServiceWorkerRegistration | undefined) {
if (!canUseWindow() || !registration) {
@@ -42,11 +48,20 @@ export function registerPwaIfEnabled() {
updateServiceWorker = registerSW({
immediate: true,
onNeedRefresh() {
void clearPwaRuntimeCaches()
.catch(() => undefined)
.finally(() => {
void updateServiceWorker?.(true);
});
const applyUpdate = () => {
void clearPwaRuntimeCaches()
.catch(() => undefined)
.finally(() => {
void updateServiceWorker?.(true);
});
};
if (canUseWindow() && isAuthInputPath(window.location.pathname)) {
window.dispatchEvent(new CustomEvent(PWA_UPDATE_READY_EVENT, { detail: { applyUpdate } }));
return;
}
applyUpdate();
},
onOfflineReady() {
if (canUseWindow()) {
+12
查看文件
@@ -7,6 +7,7 @@ import { BudgetsPage } from "../pages/BudgetsPage";
import { ChangePasswordPage } from "../pages/ChangePasswordPage";
import { DashboardPage } from "../pages/DashboardPage";
import { ForbiddenPage } from "../pages/ForbiddenPage";
import { ForgotPasswordPage } from "../pages/ForgotPasswordPage";
import { LoginPage } from "../pages/LoginPage";
import { NotFoundPage } from "../pages/NotFoundPage";
import { ProfilePage } from "../pages/ProfilePage";
@@ -91,6 +92,17 @@ export function AppRouter() {
<Route index element={<LoginPage />} />
</Route>
<Route
path="/forgot-password"
element={
<GuestOnly>
<AuthLayout />
</GuestOnly>
}
>
<Route index element={<ForgotPasswordPage />} />
</Route>
<Route
path="/change-password"
element={