Fix post-login redirect when the session cookie is off-origin
Signing in showed the "Welcome back!" toast but never left /login. The session cookie was host-only on the API subdomain, so the Next middleware guard on the site origin saw no cookie and bounced /dashboard straight back to /login?redirect=/dashboard. - Add AUTH_COOKIE_DOMAIN, wiring Better Auth's crossSubDomainCookies so the cookie also reaches the site origin. Unset in dev, where localhost is single-host and must stay host-only. - Navigate after authentication with a full page load, via a shared authRedirect helper: only a top-level request carries the httpOnly cookie. Used by the login, register, magic-link and Google flows. - Show "Redirecting..." on the login and register pages and keep the submit button disabled until the browser replaces the page, instead of re-enabling it mid-navigation. - Guard against a redirect loop with a sessionStorage marker. A React ref cannot do this: the full page load resets component state. If the destination bounces back, explain it rather than navigating again. - Middleware: accept any *.session_token cookie so a cookiePrefix change cannot lock everyone out, and preserve the destination's query string. - Trust any loopback port in dev, so reaching the dev server through a forwarded port does not fail Better Auth's CSRF origin check. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
733d2459df
commit
dafa3711f8
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState, Suspense } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useState, useEffect, Suspense } from 'react';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { useLanguage } from '@/context/LanguageContext';
|
||||
import { useAuth } from '@/context/AuthContext';
|
||||
@@ -11,14 +11,20 @@ import Input from '@/components/ui/Input';
|
||||
import GoogleSignInButton from '@/components/GoogleSignInButton';
|
||||
import { authApi } from '@/lib/api';
|
||||
import { safeInternalPath } from '@/lib/safeRedirect';
|
||||
import {
|
||||
clearRedirectAttempt,
|
||||
didRedirectBounce,
|
||||
redirectAfterAuth,
|
||||
} from '@/lib/authRedirect';
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
function LoginContent() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { t, locale: language } = useLanguage();
|
||||
const { login } = useAuth();
|
||||
const { login, user, isLoading: authLoading } = useAuth();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [redirecting, setRedirecting] = useState(false);
|
||||
const [bounced, setBounced] = useState(false);
|
||||
const [loginMode, setLoginMode] = useState<'password' | 'magic-link'>('password');
|
||||
const [magicLinkSent, setMagicLinkSent] = useState(false);
|
||||
const [formData, setFormData] = useState({
|
||||
@@ -29,6 +35,27 @@ function LoginContent() {
|
||||
// Check for redirect after login (only same-origin relative paths are honoured)
|
||||
const redirectTo = safeInternalPath(searchParams.get('redirect'), '/dashboard');
|
||||
|
||||
// Send an already-signed-in visitor on to their destination — and detect the case
|
||||
// where that destination bounced them back here, which otherwise looks like the
|
||||
// login page silently ignoring a successful sign-in.
|
||||
useEffect(() => {
|
||||
if (authLoading || redirecting) return;
|
||||
|
||||
if (!user) {
|
||||
// Signed out on the login page is a clean slate.
|
||||
clearRedirectAttempt();
|
||||
return;
|
||||
}
|
||||
|
||||
if (didRedirectBounce(redirectTo)) {
|
||||
setBounced(true);
|
||||
return;
|
||||
}
|
||||
|
||||
setRedirecting(true);
|
||||
redirectAfterAuth(redirectTo);
|
||||
}, [authLoading, redirecting, user, redirectTo]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
@@ -36,10 +63,12 @@ function LoginContent() {
|
||||
try {
|
||||
await login(formData.email, formData.password);
|
||||
toast.success(language === 'es' ? '¡Bienvenido!' : 'Welcome back!');
|
||||
router.push(redirectTo);
|
||||
// Deliberately leaves `loading` set: the button must stay disabled until the
|
||||
// browser replaces this page.
|
||||
setRedirecting(true);
|
||||
redirectAfterAuth(redirectTo);
|
||||
} catch (error: any) {
|
||||
toast.error(error.message || t('auth.errors.invalidCredentials'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
@@ -67,6 +96,38 @@ function LoginContent() {
|
||||
}
|
||||
};
|
||||
|
||||
// The destination sent us back here even though the session is valid. Say so, rather
|
||||
// than re-showing a form that appears to do nothing. The retry link is a plain <a> so
|
||||
// it is a full page load, like every other navigation out of this page.
|
||||
if (bounced) {
|
||||
return (
|
||||
<div className="section-padding min-h-[70vh] flex items-center">
|
||||
<div className="container-page">
|
||||
<div className="max-w-md mx-auto">
|
||||
<Card className="p-8 text-center">
|
||||
<h1 className="text-2xl font-bold">{t('auth.login.redirectBlocked')}</h1>
|
||||
{user && <p className="mt-2 text-sm text-gray-600">{user.email}</p>}
|
||||
<p className="mt-4 text-sm text-gray-600">
|
||||
<code className="px-1.5 py-0.5 bg-gray-100 rounded">{redirectTo}</code>
|
||||
</p>
|
||||
<a href={redirectTo} className="mt-6 block">
|
||||
<Button className="w-full" size="lg">
|
||||
{t('auth.login.redirectRetry')}
|
||||
</Button>
|
||||
</a>
|
||||
<Link
|
||||
href="/"
|
||||
className="mt-3 inline-block text-sm text-secondary-blue hover:underline"
|
||||
>
|
||||
{t('nav.home')}
|
||||
</Link>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="section-padding min-h-[70vh] flex items-center">
|
||||
<div className="container-page">
|
||||
@@ -151,9 +212,25 @@ function LoginContent() {
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full" size="lg" isLoading={loading}>
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
size="lg"
|
||||
isLoading={loading || redirecting}
|
||||
loadingText={redirecting ? t('auth.login.redirecting') : t('common.loading')}
|
||||
>
|
||||
{t('auth.login.submit')}
|
||||
</Button>
|
||||
|
||||
{redirecting && (
|
||||
<p
|
||||
className="text-center text-sm text-gray-600"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
>
|
||||
{t('auth.login.redirecting')}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
) : magicLinkSent ? (
|
||||
<div className="text-center py-8">
|
||||
|
||||
Reference in New Issue
Block a user