Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 25 additions & 4 deletions server/route/v2/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,21 @@ function validateRedirectUrl(redirectUrl: string | null | undefined, defaultUrl:
return redirectUrl;
}

function getLoginRedirectUrl(frontendBaseUrl: string, stateData: any | null): URL {
return new URL(validateRedirectUrl(stateData?.redirectUrl, '/login'), frontendBaseUrl);
}

async function extractOptionalStateData(state: string | undefined): Promise<any | null> {
if (!state) return null;

try {
return await extractStateData(state);
} catch {
// Provider cancel callbacks may omit or expire state; route back to the default login page.
return null;
}
}

// 获取前端基础 URL
async function getFrontendBaseUrl(c: HonoContext): Promise<string> {
const siteConfig = await getConfig<SiteConfig>('site');
Expand Down Expand Up @@ -82,7 +97,7 @@ async function handleOAuthError(
return c.redirect(bindUrl.toString());
} else {
// 登录模式错误,重定向到登录页面
const loginUrl = new URL('/login', frontendBaseUrl);
const loginUrl = getLoginRedirectUrl(frontendBaseUrl, stateData);
loginUrl.searchParams.set('oauth', 'error');
loginUrl.searchParams.set('provider', provider);
loginUrl.searchParams.set('message', userFriendlyMessage);
Expand All @@ -98,10 +113,11 @@ async function handleOAuthError(
async function handleOAuthCancelled(
c: HonoContext,
provider: string,
_errorCode: string
_errorCode: string,
stateData: any | null
): Promise<Response> {
const frontendBaseUrl = await getFrontendBaseUrl(c);
const loginUrl = new URL('/login', frontendBaseUrl);
const loginUrl = getLoginRedirectUrl(frontendBaseUrl, stateData);
loginUrl.searchParams.set('oauth', 'cancelled');
loginUrl.searchParams.set('provider', provider);
return c.redirect(loginUrl.toString());
Expand Down Expand Up @@ -277,7 +293,12 @@ async function handleOAuthCallback(c: HonoContext, providerName: string): Promis
// 处理用户取消授权
const cancelErrors = ['access_denied', 'user_cancelled_authorize'];
if (error && cancelErrors.includes(error)) {
return await handleOAuthCancelled(c, providerName, error);
return await handleOAuthCancelled(
c,
providerName,
error,
await extractOptionalStateData(state)
);
}

if (error) {
Expand Down
19 changes: 11 additions & 8 deletions web/src/pages/login/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import { usePasskey } from '@/hooks/usePasskey';
import { get, getApiUrl, post } from '@/utils/api';
import { authService } from '@/utils/auth';
import { useAPIGet } from '@/utils/fetcher';
import {
getLoginPathWithRedirect,
getSafeLoginRedirect,
isOAuthAuthorizeRedirect,
} from '@/utils/loginRedirect';
import { registerWithPasskey } from '@/utils/passkey';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
Expand Down Expand Up @@ -47,10 +52,8 @@ function Login() {
const [showPasskeyPrompt, setShowPasskeyPrompt] = useState(false);
const isIosLoginFlow = searchParams.get('type') === 'ioslogin';
const redirectTarget = searchParams.get('redirect');
const postLoginRedirect =
redirectTarget && redirectTarget.startsWith('/') && !redirectTarget.startsWith('//')
? redirectTarget
: '/home';
const hasOAuthAuthorizeRedirect = isOAuthAuthorizeRedirect(redirectTarget);
const postLoginRedirect = getSafeLoginRedirect(searchParams);

// 如果注册被禁用,确保 activeTab 是 'login'
useEffect(() => {
Expand Down Expand Up @@ -110,7 +113,7 @@ function Login() {
refreshToken?: string | null;
}) {
if (!isIosLoginFlow) {
navigate(postLoginRedirect);
navigate(postLoginRedirect, { replace: true });
return;
}

Expand Down Expand Up @@ -223,7 +226,7 @@ function Login() {
if (accessToken && refreshToken) {
authService.setTokens(accessToken, refreshToken);

if (isIosLoginFlow) {
if (isIosLoginFlow || hasOAuthAuthorizeRedirect) {
mutateProfile();
completeAuthenticatedFlow({ accessToken, refreshToken });
} else if (passkeyEnabled) {
Expand Down Expand Up @@ -321,7 +324,7 @@ function Login() {
// OAuth 登录失败
toast.error(decodeURIComponent(errorMessage));
// 清除 URL 参数
navigate('/login', { replace: true });
navigate(getLoginPathWithRedirect(postLoginRedirect), { replace: true });
} else if (oauthStatus === 'cancelled') {
// 用户取消授权
const provider = searchParams.get('provider');
Expand All @@ -332,7 +335,7 @@ function Login() {
toast.info(t('messages.oauthCancelled'));
}
// 清除 URL 参数
navigate('/login', { replace: true });
navigate(getLoginPathWithRedirect(postLoginRedirect), { replace: true });
}
}, [searchParams, navigate, mutateProfile, t, isIosLoginFlow, postLoginRedirect]);

Expand Down
11 changes: 3 additions & 8 deletions web/src/pages/oauth/authorize.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import LoadingPlaceholder from '@/components/others/LoadingPlaceholder';
import { Button } from '@/components/ui/button';
import { authService } from '@/utils/auth';
import { getCurrentRedirectPath, getLoginPathWithRedirect } from '@/utils/loginRedirect';
import {
getOAuthAuthorizeSession,
submitOAuthAuthorizeDecision,
Expand All @@ -12,10 +13,6 @@ import { useTranslation } from 'react-i18next';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import { toast } from 'sonner';

function getLoginRedirectPath() {
return `${window.location.pathname}${window.location.search}`;
}

function getScopeLabelKey(scope: string) {
return scope.replaceAll(':', '_');
}
Expand Down Expand Up @@ -103,7 +100,7 @@ export default function OAuthAuthorizePage() {
}

if (!authService.hasValidAccessToken() && !authService.hasValidRefreshToken()) {
navigate(`/login?redirect=${encodeURIComponent(getLoginRedirectPath())}`, { replace: true });
navigate(getLoginPathWithRedirect(getCurrentRedirectPath()), { replace: true });
return;
}

Expand All @@ -115,9 +112,7 @@ export default function OAuthAuthorizePage() {
})
.catch((err: any) => {
if (err?.response?.status === 401) {
navigate(`/login?redirect=${encodeURIComponent(getLoginRedirectPath())}`, {
replace: true,
});
navigate(getLoginPathWithRedirect(getCurrentRedirectPath()), { replace: true });
return;
}
setError(err?.response?.data?.message || err?.message || t('errors.loadFailed'));
Expand Down
8 changes: 1 addition & 7 deletions web/src/route/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import LoadingPlaceholder from '@/components/others/LoadingPlaceholder';
import ScrollPositionManager from '@/components/ScrollPositionManager';
import LayoutDashboard from '@/layout/dashboard';
import { useAuthState } from '@/state/profile';
import { getSafeLoginRedirect } from '@/utils/loginRedirect';
import { createBrowserRouter, Navigate, Outlet, RouterProvider } from 'react-router-dom';
import { ProtectedRoute } from './protectedRoute';

Expand Down Expand Up @@ -40,13 +41,6 @@ function RootLayout() {
);
}

function getSafeLoginRedirect(search: string) {
const redirectTarget = new URLSearchParams(search).get('redirect');
return redirectTarget && redirectTarget.startsWith('/') && !redirectTarget.startsWith('//')
? redirectTarget
: '/home';
}

function LoginRouteEntry() {
const { tokenValid, isAuthPending } = useAuthState();
const isIosLogin = new URLSearchParams(window.location.search).get('type') === 'ioslogin';
Expand Down
10 changes: 8 additions & 2 deletions web/src/route/protectedRoute.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import LoadingPlaceholder from '@/components/others/LoadingPlaceholder';
import { useAuthState } from '@/state/profile';
import { getLoginPathWithRedirect } from '@/utils/loginRedirect';
import MobileDetect from 'mobile-detect';
import { useEffect, useState } from 'react';
import { Navigate } from 'react-router-dom';
import { Navigate, useLocation } from 'react-router-dom';
import { toast } from 'sonner';

export const ProtectedRoute = ({ children }: any) => {
const { tokenValid, isAuthPending } = useAuthState();
const location = useLocation();
const [iosSafariToastDone, setIosSafariToastDone] = useState(
localStorage.getItem('iosSafariToastDone') === 'true'
);
Expand Down Expand Up @@ -44,5 +46,9 @@ export const ProtectedRoute = ({ children }: any) => {
return <LoadingPlaceholder className="h-dvh w-full" size={6} />;
}

return tokenValid ? children : <Navigate to="/login" />;
return tokenValid ? (
children
) : (
<Navigate replace to={getLoginPathWithRedirect(`${location.pathname}${location.search}`)} />
);
};
38 changes: 38 additions & 0 deletions web/src/utils/loginRedirect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const DEFAULT_LOGIN_REDIRECT = '/home';

export function isSafeLoginRedirect(value: string | null | undefined): value is string {
return Boolean(value && value.startsWith('/') && !value.startsWith('//'));
}

export function getSafeLoginRedirect(
search: string | URLSearchParams,
fallback = DEFAULT_LOGIN_REDIRECT
) {
const params = typeof search === 'string' ? new URLSearchParams(search) : search;
const redirectTarget = params.get('redirect');
return isSafeLoginRedirect(redirectTarget) ? redirectTarget : fallback;
}

export function getCurrentRedirectPath() {
return `${window.location.pathname}${window.location.search}${window.location.hash}`;
}

export function isOAuthAuthorizeRedirect(value: string | null | undefined): value is string {
if (!isSafeLoginRedirect(value)) return false;

try {
const redirectUrl = new URL(value, window.location.origin);
return (
redirectUrl.pathname === '/oauth/authorize' &&
Boolean(redirectUrl.searchParams.get('requestId'))
);
} catch {
return false;
}
}

export function getLoginPathWithRedirect(redirectPath: string = getCurrentRedirectPath()) {
return isSafeLoginRedirect(redirectPath)
? `/login?redirect=${encodeURIComponent(redirectPath)}`
: '/login';
}
Loading