import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, Form, useActionData, useLoaderData, useNavigation, redirect } from "react-router"; import { Button } from "~/components/ui/button"; import { Card } from "~/components/ui/card"; import { getUser, login, isAuthEnabled } from "~/lib/auth"; export const meta: MetaFunction = () => { return [ { title: "Counterscale: Web Analytics" }, { name: "description", content: "Counterscale: Web Analytics" }, ]; }; export async function loader({ request, context }: LoaderFunctionArgs) { const env = context.cloudflare.env; const user = await getUser(request, env); const authEnabled = isAuthEnabled(env); // Return auth status to conditionally render the login form return { user, authEnabled }; } export async function action({ request, context }: ActionFunctionArgs) { const env = context.cloudflare.env; // If auth is disabled, this action shouldn't be called, but handle it gracefully if (!isAuthEnabled(env)) { return redirect("/dashboard"); } const formData = await request.formData(); const password = formData.get("password"); if (typeof password !== "string" || !password) { return { error: "Password is required" }; } try { return await login(request, password, env); } catch { return { error: "Invalid password" }; } } export default function Index() { const { user, authEnabled } = useLoaderData(); const actionData = useActionData(); const navigation = useNavigation(); const isSubmitting = ["submitting", "loading"].includes(navigation.state); return (
CounterScale Logo

Welcome to Counterscale

{!authEnabled ? "Access your analytics dashboard." : user?.authenticated ? "Continue to access your analytics dashboard." : "Enter your password to access the dashboard" }

{/* When auth is disabled or user is already authenticated, show dashboard button */} {(!authEnabled || user?.authenticated) ? ( ) : ( /* When auth is enabled and user is not authenticated, show login form */
{actionData?.error && (
{actionData.error}
)}
)}
); }