All files / src/pages auth.tsx

100% Statements 47/47
94.23% Branches 49/52
100% Functions 7/7
100% Lines 43/43

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280                                                3x     50x 50x 50x 50x   50x 50x 50x         50x                       50x             50x 33x 3x 3x 3x 3x     50x       50x 6x 6x 6x       6x 1x 5x 1x   4x                 50x   50x 8x 8x 8x           3x         50x 1x                                               49x 1x                                               48x 48x 48x 48x   48x                                                                                                                     5x                           3x                                                                                        
import { useState, useEffect } from "react";
import { Link, useNavigate } from "@tanstack/react-router";
import { AuthView } from "@daveyplate/better-auth-ui";
import { TabToggle } from "../components/auth/TabToggle";
import { MagicLinkForm } from "../components/auth/MagicLinkForm";
import { PasswordForm } from "../components/auth/PasswordForm";
import { PhoneOtpForm } from "../components/auth/PhoneOtpForm";
import { ForgotPasswordForm } from "../components/auth/ForgotPasswordForm";
import { queryClient } from "../lib/query-client";
import { useAuth } from "../lib/auth-context";
import { authClient } from "../lib/auth-client";
import {
	Card,
	CardContent,
	CardHeader,
	CardTitle,
} from "../components/ui/card";
import { LogoIcon } from "../components/ui/logo-icon";
 
interface AuthPageProps {
	pathname: string;
	search: Record<string, string | undefined>;
}
 
const isLocalUrl = (url: string) => url.startsWith("/") && !url.startsWith("//");
 
export function AuthPage({ pathname, search }: AuthPageProps) {
	const navigate = useNavigate();
	const { refreshSession } = useAuth();
	const [activeTab, setActiveTab] = useState<"email" | "phone" | "password">("email");
	const [socialError, setSocialError] = useState<string | null>(null);
 
	const invitationToken = search.token;
	const authErrorCode = search.error;
	const isSignUp = pathname === "sign-up";
 
	// Better Auth surfaces failure codes via `?error=` on the redirect target.
	// Raw codes ("state_mismatch") are not user-readable; map the known ones
	// to a useful sentence and fall back to a generic prompt for the rest.
	const AUTH_ERROR_MESSAGES: Record<string, string> = {
		state_mismatch: "Your sign-in attempt expired before you finished. Please try again.",
		please_restart_the_process: "Your sign-in attempt expired. Please try again.",
		account_not_linked:
			"An account with this email already exists. Sign in with your password instead, then link Google from settings.",
		oauth_failure: "Google didn't complete the sign-in. Please try again.",
		invalid_code: "We couldn't verify the sign-in response. Please try again.",
		// Issue #581: shown when the user's pro access was revoked while they
		// were signed in; the auth-context force-signs them out and lands here.
		access_revoked:
			"Your access to this organization has been revoked. Please contact your team owner if you think this is a mistake.",
	};
	const authError = authErrorCode
		? AUTH_ERROR_MESSAGES[authErrorCode] ||
			"We couldn't complete your sign-in. Please try again."
		: undefined;
 
	// Clear the error param from the URL after capturing it so it doesn't
	// persist across tab switches or navigations (Issue #229)
	useEffect(() => {
		if (authErrorCode) {
			const url = new URL(window.location.href);
			url.searchParams.delete("error");
			url.searchParams.delete("code");
			window.history.replaceState({}, "", url.toString());
		}
	}, [authErrorCode]);
	const socialCallbackURL = invitationToken
		? `${window.location.origin}/accept-invitation?token=${invitationToken}`
		: `${window.location.origin}/`;
 
	const handlePhoneSuccess = async () => {
		queryClient.clear();
		try {
			await refreshSession();
		} catch {
			// Session exists server-side — navigate anyway
		}
		if (invitationToken) {
			navigate({ to: "/accept-invitation", search: { token: invitationToken } });
		} else if (search.redirect && isLocalUrl(search.redirect)) {
			navigate({ to: search.redirect as string });
		} else {
			navigate({ to: "/" });
		}
	};
 
	// Better Auth appends `?error=<code>` to errorCallbackURL on OAuth failure.
	// Without an explicit value, failures land on `${BETTER_AUTH_URL}/error?...`
	// (e.g. api-dev.decorrocket.com), exposing the API origin to users. Sending
	// them back to the portal `/auth` page lets the existing `authError` capture
	// (line 34) surface a readable message instead.
	const socialErrorCallbackURL = `${window.location.origin}/auth/sign-in`;
 
	const handleSocialSignIn = async (provider: "google" | "facebook") => {
		setSocialError(null);
		try {
			await authClient.signIn.social({
				provider,
				callbackURL: socialCallbackURL,
				errorCallbackURL: socialErrorCallbackURL,
			});
		} catch (err) {
			setSocialError(err instanceof Error ? err.message : "Social sign-in failed. Please try again.");
		}
	};
 
	// Forgot password: custom form with success state
	if (pathname === "forgot-password") {
		return (
			<div className="min-h-screen flex items-center justify-center bg-background p-4">
				<div className="w-full max-w-md">
					<div className="text-center mb-6">
						<div className="flex items-center justify-center gap-2 mb-1">
							<LogoIcon size={36} className="text-foreground-default" />
							<h1 className="text-2xl font-bold">Interioring</h1>
						</div>
					</div>
					<Card>
						<CardHeader className="pb-2">
							<CardTitle className="text-xl">Forgot Password</CardTitle>
							<p className="text-sm text-muted-foreground">Enter your email to reset your password</p>
						</CardHeader>
						<CardContent className="pt-2">
							<ForgotPasswordForm />
						</CardContent>
					</Card>
				</div>
			</div>
		);
	}
 
	// Reset password: keep using AuthView (needs token handling from URL)
	if (pathname === "reset-password") {
		return (
			<div className="min-h-screen flex items-center justify-center bg-background p-4">
				<div className="w-full max-w-md">
					<div className="text-center mb-6">
						<div className="flex items-center justify-center gap-2 mb-1">
							<LogoIcon size={36} className="text-foreground-default" />
							<h1 className="text-2xl font-bold">Interioring</h1>
						</div>
					</div>
					<AuthView pathname={pathname} />
					<div className="text-center mt-4">
						<p className="text-sm text-foreground-muted">
							Link expired?{" "}
							<a href="/auth/forgot-password" className="text-primary-600 hover:underline">
								Request a new one
							</a>
						</p>
					</div>
				</div>
			</div>
		);
	}
 
	// Build search params for toggle links (preserve token, redirect, email)
	const toggleSearch: Record<string, string> = {};
	if (search.token) toggleSearch.token = search.token;
	if (search.redirect) toggleSearch.redirect = search.redirect;
	if (search.email) toggleSearch.email = search.email;
 
	return (
		<div className="min-h-screen flex items-center justify-center bg-background p-4">
			<div className="w-full max-w-md">
				<div className="text-center mb-6">
					<div className="flex items-center justify-center gap-2 mb-1">
							<LogoIcon size={36} className="text-foreground-default" />
							<h1 className="text-2xl font-bold">Interioring</h1>
						</div>
					<p className="text-sm text-muted-foreground mt-1">
						{isSignUp ? "Create your account" : "Welcome back"}
					</p>
				</div>
 
				<Card>
					<CardHeader className="pb-2">
						<CardTitle className="text-xl">
							{isSignUp ? "Sign Up" : "Sign In"}
						</CardTitle>
					</CardHeader>
					<CardContent className="pt-2">
						{authError && (
							<div role="alert" className="mb-4 p-3 rounded-md bg-destructive/10 border border-destructive/20 text-sm text-destructive">
								{authError}
							</div>
						)}
						<TabToggle activeTab={activeTab} onChange={setActiveTab} />
 
						{activeTab === "email" && (
							<MagicLinkForm key={isSignUp ? "signup" : "signin"} isSignUp={isSignUp} invitationToken={invitationToken} />
						)}
						{activeTab === "phone" && (
							<PhoneOtpForm
								key={isSignUp ? "signup" : "signin"}
								onSuccess={handlePhoneSuccess}
								mode={isSignUp ? "sign-up" : "sign-in"}
							/>
						)}
						{activeTab === "password" && (
							<PasswordForm
								key={isSignUp ? "signup" : "signin"}
								isSignUp={isSignUp}
								invitationToken={invitationToken}
								redirect={search.redirect}
							/>
						)}
 
						{/* Social login — always visible regardless of active tab */}
						<div className="relative my-4">
							<div className="absolute inset-0 flex items-center">
								<div className="w-full border-t border-border" />
							</div>
							<div className="relative flex justify-center text-xs uppercase">
								<span className="bg-card px-2 text-muted-foreground">Or continue with</span>
							</div>
						</div>
 
						<div className="flex gap-3">
							<button
								type="button"
								onClick={() => handleSocialSignIn("google")}
								className="flex-1 h-10 px-4 border border-input rounded-md bg-background text-foreground text-sm font-medium hover:bg-muted transition-colors flex items-center justify-center gap-2"
							>
								<svg className="size-4" viewBox="0 0 24 24" aria-hidden="true">
									<path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4" />
									<path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853" />
									<path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05" />
									<path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335" />
								</svg>
								Google
							</button>
 
							<button
								type="button"
								onClick={() => handleSocialSignIn("facebook")}
								className="flex-1 h-10 px-4 border border-input rounded-md bg-background text-foreground text-sm font-medium hover:bg-muted transition-colors flex items-center justify-center gap-2"
							>
								<svg className="size-4" viewBox="0 0 24 24" aria-hidden="true">
									<path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z" fill="#1877F2" />
								</svg>
								Facebook
							</button>
						</div>
						{socialError && (
							<p role="alert" className="mt-2 text-sm text-destructive">{socialError}</p>
						)}
 
						<div className="mt-4 text-center text-sm text-muted-foreground">
							{isSignUp ? (
								<>
									Already have an account?{" "}
									<Link
										to="/auth/sign-in"
										search={toggleSearch}
										className="text-primary font-medium hover:underline"
									>
										Sign In
									</Link>
								</>
							) : (
								<>
									Don&apos;t have an account?{" "}
									<Link
										to="/auth/sign-up"
										search={toggleSearch}
										className="text-primary font-medium hover:underline"
									>
										Sign Up
									</Link>
								</>
							)}
						</div>
					</CardContent>
				</Card>
			</div>
		</div>
	);
}