fix: restore original URL after OAuth login redirect

Save the intended destination to sessionStorage before navigating to
the OAuth provider, and read it back in AuthCallback after login.
Also handles 401-triggered redirects so session-expired users are
returned to the page they were on.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
M1ngdaXie
2026-03-09 04:42:19 +00:00
parent 731bd67334
commit 763575f284
3 changed files with 21 additions and 4 deletions

View File

@@ -11,7 +11,11 @@ function AuthCallback() {
useEffect(() => {
const handleCallback = async () => {
const token = searchParams.get('token');
const redirect = searchParams.get('redirect') || '/';
const redirect =
searchParams.get('redirect') ||
sessionStorage.getItem('oauth_redirect') ||
'/';
sessionStorage.removeItem('oauth_redirect');
if (!token) {
setError('No authentication token received');

View File

@@ -1,5 +1,5 @@
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { API_BASE_URL } from '../config';
import DocNestLogo from '../assets/docnest/docnest-icon-128.png';
@@ -9,6 +9,7 @@ import './LoginPage.css';
function LoginPage() {
const { user, loading } = useAuth();
const navigate = useNavigate();
const [searchParams] = useSearchParams();
useEffect(() => {
if (!loading && user) {
@@ -16,12 +17,20 @@ function LoginPage() {
}
}, [user, loading, navigate]);
const saveRedirectAndGo = (oauthUrl: string) => {
const redirect = searchParams.get('redirect');
if (redirect) {
sessionStorage.setItem('oauth_redirect', redirect);
}
window.location.href = oauthUrl;
};
const handleGoogleLogin = () => {
window.location.href = `${API_BASE_URL}/auth/google`;
saveRedirectAndGo(`${API_BASE_URL}/auth/google`);
};
const handleGitHubLogin = () => {
window.location.href = `${API_BASE_URL}/auth/github`;
saveRedirectAndGo(`${API_BASE_URL}/auth/github`);
};
if (loading) {