fix(frontend): repair login session flow

Resolve login-page 401 hangs and redirect races by relying on the shared user state. Keep protected-route redirects intact, clean pending requests without unhandled rejections, and allow the dynamic icon route through the page proxy.
This commit is contained in:
ryan
2026-06-13 11:27:30 +08:00
parent 9a6bb04bf5
commit 49bd850c8b
4 changed files with 30 additions and 99 deletions
+2 -24
View File
@@ -1,8 +1,8 @@
"use client"
import {useEffect, useMemo, useRef, useState} from "react"
import {useEffect, useRef, useState} from "react"
import {useMutation, useQuery} from "@tanstack/react-query"
import {useRouter, useSearchParams} from "next/navigation"
import {useSearchParams} from "next/navigation"
import {EyeIcon, EyeOffIcon} from "lucide-react"
import {toast} from "sonner"
import Link from "next/link"
@@ -20,21 +20,6 @@ import services from "@/lib/services"
import type {LoginRequest} from "@/lib/services/auth/types"
import {safeRedirectTarget} from "@/lib/utils"
function getRedirectTarget(searchParams: ReturnType<typeof useSearchParams>) {
const callbackUrl = searchParams.get("callbackUrl")
const storedRedirect =
typeof window === "undefined"
? null
: sessionStorage.getItem("redirect_after_login")
const target = callbackUrl || storedRedirect || "/home"
if (storedRedirect && typeof window !== "undefined") {
sessionStorage.removeItem("redirect_after_login")
}
return safeRedirectTarget(target)
}
function persistRedirectTarget(searchParams: ReturnType<typeof useSearchParams>) {
const callbackUrl = searchParams.get("callbackUrl")
if (callbackUrl && typeof window !== "undefined") {
@@ -49,7 +34,6 @@ function configBool(value: string | undefined, fallback: boolean) {
}
export function LoginForm({ onOTPStateChange }: { onOTPStateChange?: (show: boolean) => void }) {
const router = useRouter()
const searchParams = useSearchParams()
const { setUser } = useAuth()
const [username, setUsername] = useState("")
@@ -89,11 +73,6 @@ export function LoginForm({ onOTPStateChange }: { onOTPStateChange?: (show: bool
enabled: configBool(publicConfigQuery.data?.oidc_login_enabled, true),
})
const redirectTarget = useMemo(
() => getRedirectTarget(searchParams),
[searchParams],
)
const capEnabled = configBool(publicConfigQuery.data?.cap_login_enabled, false)
const capAutoSolve = configBool(publicConfigQuery.data?.cap_auto_solve, true)
@@ -110,7 +89,6 @@ export function LoginForm({ onOTPStateChange }: { onOTPStateChange?: (show: bool
},
onSuccess: (user) => {
setUser(user)
router.replace(redirectTarget)
toast.success("登录成功")
},
onError: (error: Error) => {
+9 -61
View File
@@ -27,21 +27,17 @@ import {safeRedirectTarget} from "@/lib/utils"
export function LoginPage() {
const router = useRouter()
const searchParams = useSearchParams()
const { user, setUser } = useAuth()
const { user, loading, setUser } = useAuth()
const [showOTP, setShowOTP] = useState(false)
/* 处理OAuth回调 */
const [isProcessingCallback, setIsProcessingCallback] = useState(() => {
const state = searchParams.get('state')
const code = searchParams.get('code')
return !!(state && code)
})
const [isCheckingSession, setIsCheckingSession] = useState(() => !searchParams.get('state') || !searchParams.get('code'))
const isOAuthCallback = !!(searchParams.get('state') && searchParams.get('code'))
const [isProcessingCallback, setIsProcessingCallback] = useState(isOAuthCallback)
const isCheckingSession = !isOAuthCallback && loading
const [loginSuccess, setLoginSuccess] = useState(false)
const redirectedRef = useRef(false)
const callbackProcessedRef = useRef(false)
const wasUserPresentRef = useRef(!!user)
const resolveRedirectTarget = useCallback(() => {
const callbackUrl = searchParams.get('callbackUrl')
@@ -66,63 +62,15 @@ export function LoginPage() {
const state = searchParams.get('state')
const code = searchParams.get('code')
if (state && code) {
setIsCheckingSession(false)
if ((state && code) || loading || !user) {
return
}
if (user) {
if (wasUserPresentRef.current) {
if (!redirectedRef.current) {
redirectedRef.current = true
router.replace(resolveRedirectTargetRef.current())
setIsCheckingSession(false)
}
}
return
if (!redirectedRef.current) {
redirectedRef.current = true
router.replace(resolveRedirectTargetRef.current())
}
let cancelled = false
const checkExistingSession = async () => {
setIsCheckingSession(true)
try {
const response = await fetch('/api/v1/oauth/user-info', {
credentials: 'include',
cache: 'no-store',
})
if (cancelled) return
if (response.ok) {
const payload = await response.json()
if (payload?.data) {
setUser(payload.data)
}
if (!redirectedRef.current) {
redirectedRef.current = true
router.replace(resolveRedirectTargetRef.current())
}
return
}
} catch (error) {
if (!cancelled) {
console.error('Session probe error:', error)
}
} finally {
if (!cancelled) {
setIsCheckingSession(false)
}
}
}
checkExistingSession()
return () => {
cancelled = true
}
}, [router, searchParams, setUser, user])
}, [loading, router, searchParams, user])
/* 回调逻辑 */
useEffect(() => {