mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-10-08 08:36:37 +08:00
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:
@@ -1,8 +1,8 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import {useEffect, useMemo, useRef, useState} from "react"
|
import {useEffect, useRef, useState} from "react"
|
||||||
import {useMutation, useQuery} from "@tanstack/react-query"
|
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 {EyeIcon, EyeOffIcon} from "lucide-react"
|
||||||
import {toast} from "sonner"
|
import {toast} from "sonner"
|
||||||
import Link from "next/link"
|
import Link from "next/link"
|
||||||
@@ -20,21 +20,6 @@ import services from "@/lib/services"
|
|||||||
import type {LoginRequest} from "@/lib/services/auth/types"
|
import type {LoginRequest} from "@/lib/services/auth/types"
|
||||||
import {safeRedirectTarget} from "@/lib/utils"
|
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>) {
|
function persistRedirectTarget(searchParams: ReturnType<typeof useSearchParams>) {
|
||||||
const callbackUrl = searchParams.get("callbackUrl")
|
const callbackUrl = searchParams.get("callbackUrl")
|
||||||
if (callbackUrl && typeof window !== "undefined") {
|
if (callbackUrl && typeof window !== "undefined") {
|
||||||
@@ -49,7 +34,6 @@ function configBool(value: string | undefined, fallback: boolean) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function LoginForm({ onOTPStateChange }: { onOTPStateChange?: (show: boolean) => void }) {
|
export function LoginForm({ onOTPStateChange }: { onOTPStateChange?: (show: boolean) => void }) {
|
||||||
const router = useRouter()
|
|
||||||
const searchParams = useSearchParams()
|
const searchParams = useSearchParams()
|
||||||
const { setUser } = useAuth()
|
const { setUser } = useAuth()
|
||||||
const [username, setUsername] = useState("")
|
const [username, setUsername] = useState("")
|
||||||
@@ -89,11 +73,6 @@ export function LoginForm({ onOTPStateChange }: { onOTPStateChange?: (show: bool
|
|||||||
enabled: configBool(publicConfigQuery.data?.oidc_login_enabled, true),
|
enabled: configBool(publicConfigQuery.data?.oidc_login_enabled, true),
|
||||||
})
|
})
|
||||||
|
|
||||||
const redirectTarget = useMemo(
|
|
||||||
() => getRedirectTarget(searchParams),
|
|
||||||
[searchParams],
|
|
||||||
)
|
|
||||||
|
|
||||||
const capEnabled = configBool(publicConfigQuery.data?.cap_login_enabled, false)
|
const capEnabled = configBool(publicConfigQuery.data?.cap_login_enabled, false)
|
||||||
const capAutoSolve = configBool(publicConfigQuery.data?.cap_auto_solve, true)
|
const capAutoSolve = configBool(publicConfigQuery.data?.cap_auto_solve, true)
|
||||||
|
|
||||||
@@ -110,7 +89,6 @@ export function LoginForm({ onOTPStateChange }: { onOTPStateChange?: (show: bool
|
|||||||
},
|
},
|
||||||
onSuccess: (user) => {
|
onSuccess: (user) => {
|
||||||
setUser(user)
|
setUser(user)
|
||||||
router.replace(redirectTarget)
|
|
||||||
toast.success("登录成功")
|
toast.success("登录成功")
|
||||||
},
|
},
|
||||||
onError: (error: Error) => {
|
onError: (error: Error) => {
|
||||||
|
|||||||
@@ -27,21 +27,17 @@ import {safeRedirectTarget} from "@/lib/utils"
|
|||||||
export function LoginPage() {
|
export function LoginPage() {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const searchParams = useSearchParams()
|
const searchParams = useSearchParams()
|
||||||
const { user, setUser } = useAuth()
|
const { user, loading, setUser } = useAuth()
|
||||||
const [showOTP, setShowOTP] = useState(false)
|
const [showOTP, setShowOTP] = useState(false)
|
||||||
|
|
||||||
/* 处理OAuth回调 */
|
/* 处理OAuth回调 */
|
||||||
const [isProcessingCallback, setIsProcessingCallback] = useState(() => {
|
const isOAuthCallback = !!(searchParams.get('state') && searchParams.get('code'))
|
||||||
const state = searchParams.get('state')
|
const [isProcessingCallback, setIsProcessingCallback] = useState(isOAuthCallback)
|
||||||
const code = searchParams.get('code')
|
const isCheckingSession = !isOAuthCallback && loading
|
||||||
return !!(state && code)
|
|
||||||
})
|
|
||||||
const [isCheckingSession, setIsCheckingSession] = useState(() => !searchParams.get('state') || !searchParams.get('code'))
|
|
||||||
|
|
||||||
const [loginSuccess, setLoginSuccess] = useState(false)
|
const [loginSuccess, setLoginSuccess] = useState(false)
|
||||||
const redirectedRef = useRef(false)
|
const redirectedRef = useRef(false)
|
||||||
const callbackProcessedRef = useRef(false)
|
const callbackProcessedRef = useRef(false)
|
||||||
const wasUserPresentRef = useRef(!!user)
|
|
||||||
|
|
||||||
const resolveRedirectTarget = useCallback(() => {
|
const resolveRedirectTarget = useCallback(() => {
|
||||||
const callbackUrl = searchParams.get('callbackUrl')
|
const callbackUrl = searchParams.get('callbackUrl')
|
||||||
@@ -66,63 +62,15 @@ export function LoginPage() {
|
|||||||
const state = searchParams.get('state')
|
const state = searchParams.get('state')
|
||||||
const code = searchParams.get('code')
|
const code = searchParams.get('code')
|
||||||
|
|
||||||
if (state && code) {
|
if ((state && code) || loading || !user) {
|
||||||
setIsCheckingSession(false)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (user) {
|
if (!redirectedRef.current) {
|
||||||
if (wasUserPresentRef.current) {
|
redirectedRef.current = true
|
||||||
if (!redirectedRef.current) {
|
router.replace(resolveRedirectTargetRef.current())
|
||||||
redirectedRef.current = true
|
|
||||||
router.replace(resolveRedirectTargetRef.current())
|
|
||||||
setIsCheckingSession(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
}, [loading, router, searchParams, user])
|
||||||
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])
|
|
||||||
|
|
||||||
/* 回调逻辑 */
|
/* 回调逻辑 */
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
NotFoundError,
|
NotFoundError,
|
||||||
ServerError,
|
ServerError,
|
||||||
TimeoutError,
|
TimeoutError,
|
||||||
|
UnauthorizedError,
|
||||||
ValidationError,
|
ValidationError,
|
||||||
} from './errors';
|
} from './errors';
|
||||||
import {ApiError, ApiResponse} from './types';
|
import {ApiError, ApiResponse} from './types';
|
||||||
@@ -80,13 +81,15 @@ apiClient.interceptors.request.use(
|
|||||||
* @param currentPath - 当前路径,用于登录成功后重定向回来
|
* @param currentPath - 当前路径,用于登录成功后重定向回来
|
||||||
*/
|
*/
|
||||||
function initiateLogin(currentPath: string): Promise<never> {
|
function initiateLogin(currentPath: string): Promise<never> {
|
||||||
if (!currentPath.startsWith('/login') && !currentPath.startsWith('/callback')) {
|
if (currentPath.startsWith('/login') || currentPath.startsWith('/callback')) {
|
||||||
if (typeof window !== 'undefined') {
|
return Promise.reject(new UnauthorizedError());
|
||||||
sessionStorage.setItem('redirect_after_login', currentPath);
|
}
|
||||||
const loginUrl = new URL('/login', window.location.origin);
|
|
||||||
loginUrl.searchParams.set('callbackUrl', currentPath);
|
if (typeof window !== 'undefined') {
|
||||||
window.location.href = loginUrl.toString();
|
sessionStorage.setItem('redirect_after_login', currentPath);
|
||||||
}
|
const loginUrl = new URL('/login', window.location.origin);
|
||||||
|
loginUrl.searchParams.set('callbackUrl', currentPath);
|
||||||
|
window.location.href = loginUrl.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
return new Promise<never>(() => { });
|
return new Promise<never>(() => { });
|
||||||
@@ -259,9 +262,10 @@ function createRequestMethod(
|
|||||||
const promise = apiClient[method]<T>(url, data, config);
|
const promise = apiClient[method]<T>(url, data, config);
|
||||||
pendingRequests.set(requestKey, promise as Promise<AxiosResponse<ApiResponse>>);
|
pendingRequests.set(requestKey, promise as Promise<AxiosResponse<ApiResponse>>);
|
||||||
|
|
||||||
promise.finally(() => {
|
promise.then(
|
||||||
pendingRequests.delete(requestKey);
|
() => pendingRequests.delete(requestKey),
|
||||||
});
|
() => pendingRequests.delete(requestKey),
|
||||||
|
);
|
||||||
|
|
||||||
return promise;
|
return promise;
|
||||||
};
|
};
|
||||||
@@ -277,9 +281,10 @@ function createRequestMethod(
|
|||||||
const promise = apiClient[method]<T>(url, config);
|
const promise = apiClient[method]<T>(url, config);
|
||||||
pendingRequests.set(requestKey, promise as Promise<AxiosResponse<ApiResponse>>);
|
pendingRequests.set(requestKey, promise as Promise<AxiosResponse<ApiResponse>>);
|
||||||
|
|
||||||
promise.finally(() => {
|
promise.then(
|
||||||
pendingRequests.delete(requestKey);
|
() => pendingRequests.delete(requestKey),
|
||||||
});
|
() => pendingRequests.delete(requestKey),
|
||||||
|
);
|
||||||
|
|
||||||
return promise;
|
return promise;
|
||||||
};
|
};
|
||||||
|
|||||||
+1
-1
@@ -103,7 +103,7 @@ export function proxy(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* 页面请求:公共路由放行 */
|
/* 页面请求:公共路由放行 */
|
||||||
const publicRoutes = ['/', '/login', '/register', '/callback', '/privacy', '/terms']
|
const publicRoutes = ['/', '/login', '/register', '/callback', '/privacy', '/terms', '/icon']
|
||||||
const publicPrefixes = ['/docs/', '/epay/']
|
const publicPrefixes = ['/docs/', '/epay/']
|
||||||
|
|
||||||
if (publicRoutes.includes(pathname) || publicPrefixes.some(p => pathname.startsWith(p))) {
|
if (publicRoutes.includes(pathname) || publicPrefixes.some(p => pathname.startsWith(p))) {
|
||||||
|
|||||||
Reference in New Issue
Block a user