setting up files

This commit is contained in:
masongga
2026-05-23 15:09:49 -06:00
parent 4a478a653e
commit 2ad9e42f3f
25 changed files with 881 additions and 108 deletions

113
app/(app)/avatar/page.tsx Normal file
View File

@@ -0,0 +1,113 @@
import Link from "next/link";
import { PixelAvatar } from "@/components/avatar/pixel-avatar";
import { AppShell } from "@/components/layout/app-shell";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { routes } from "@/lib/routes";
const placeholderHabits = [
{ id: "water", label: "Drink water", streak: 3 },
{ id: "walk", label: "Take a walk", streak: 5 },
{ id: "sleep", label: "Sleep 7+ hours", streak: 2 },
];
export default function AvatarPage() {
return (
<AppShell
title="Your Habit Pet"
description="Check in daily to keep your pet happy and build streaks."
>
<div className="flex flex-col gap-6">
<Card>
<CardContent className="flex flex-col items-center gap-4 pt-6">
<PixelAvatar mood="happy" />
<p className="text-center text-sm text-muted-foreground">
Your pet reacts to habits, wellness check-ins, and journal entries.
</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-base">Today&apos;s habits</CardTitle>
<CardDescription>
Custom checkmarks and streak tracking live here.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{placeholderHabits.map((habit) => (
<div
key={habit.id}
className="flex items-center justify-between rounded-lg border p-3"
>
<div className="flex items-center gap-3">
<Checkbox id={habit.id} />
<Label htmlFor={habit.id}>{habit.label}</Label>
</div>
<Badge variant="secondary">{habit.streak} day streak</Badge>
</div>
))}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-base">Wellness check-in</CardTitle>
<CardDescription>Rate how you feel today.</CardDescription>
</CardHeader>
<CardContent className="space-y-5">
{[
{ id: "energy", label: "Energy" },
{ id: "mood", label: "Mood" },
{ id: "stress", label: "Stress" },
].map((metric) => (
<div key={metric.id} className="space-y-2">
<div className="flex items-center justify-between text-sm">
<Label htmlFor={metric.id}>{metric.label}</Label>
<span className="text-muted-foreground">5/10</span>
</div>
<input
id={metric.id}
type="range"
min={1}
max={10}
defaultValue={5}
className="w-full accent-primary"
/>
</div>
))}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-base">Daily journal</CardTitle>
<CardDescription>
One entry per day to reflect and help your pet grow.
</CardDescription>
</CardHeader>
<CardContent>
<textarea
className="min-h-28 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
placeholder="How did today go?"
/>
</CardContent>
</Card>
<Button asChild className="w-full">
<Link href={routes.dailyQuiz}>Take today&apos;s quiz</Link>
</Button>
</div>
</AppShell>
);
}

View File

@@ -0,0 +1,56 @@
import { AppShell } from "@/components/layout/app-shell";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
const quizQuestion = {
prompt: "What is one small win you can celebrate today?",
options: [
"I showed up for myself",
"I rested when I needed to",
"I reached out to someone",
"I kept a promise to myself",
],
};
export default function DailyQuizPage() {
return (
<AppShell
title="Daily quiz"
description="One quiz per day. Come back tomorrow for a new prompt."
>
<div className="flex flex-col gap-6">
<div className="flex items-center justify-between">
<Badge>Today&apos;s prompt</Badge>
<Badge variant="outline">Not completed</Badge>
</div>
<Card>
<CardHeader>
<CardTitle className="text-base">{quizQuestion.prompt}</CardTitle>
<CardDescription>
Pick the answer that fits best. You can only submit once per day.
</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
{quizQuestion.options.map((option) => (
<Button
key={option}
variant="outline"
className="h-auto w-full justify-start whitespace-normal px-4 py-3 text-left"
>
{option}
</Button>
))}
</CardContent>
</Card>
</div>
</AppShell>
);
}

15
app/(app)/layout.tsx Normal file
View File

@@ -0,0 +1,15 @@
import { Suspense } from "react";
import { AppAuthGate } from "@/components/layout/app-auth-gate";
export default function AppLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<Suspense fallback={<div className="min-h-svh bg-background pb-24" />}>
<AppAuthGate>{children}</AppAuthGate>
</Suspense>
);
}

View File

@@ -0,0 +1,72 @@
import { Suspense } from "react";
import { AppShell } from "@/components/layout/app-shell";
import { LogoutButton } from "@/components/logout-button";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { getSessionUser } from "@/lib/auth-helpers";
async function ProfileContent() {
const user = await getSessionUser();
return (
<div className="flex flex-col gap-6">
<Card>
<CardHeader>
<CardTitle className="text-base">Account</CardTitle>
<CardDescription>Your sign-in details and session.</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input id="email" value={user?.email ?? ""} readOnly />
</div>
<div className="flex items-center justify-between rounded-lg border px-3 py-2">
<span className="text-sm">Onboarding</span>
<Badge variant="secondary">Complete</Badge>
</div>
<LogoutButton />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-base">Preferences</CardTitle>
<CardDescription>
Notification and reminder settings will live here.
</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
<Button variant="outline" className="w-full justify-start">
Daily reminder time
</Button>
<Button variant="outline" className="w-full justify-start">
Pet appearance
</Button>
</CardContent>
</Card>
</div>
);
}
export default function ProfilePage() {
return (
<AppShell
title="Profile"
description="Manage your account and habit pet preferences."
>
<Suspense fallback={<p className="text-sm text-muted-foreground">Loading profile...</p>}>
<ProfileContent />
</Suspense>
</AppShell>
);
}

66
app/(app)/shop/page.tsx Normal file
View File

@@ -0,0 +1,66 @@
import { AppShell } from "@/components/layout/app-shell";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
const shopItems = [
{
id: "hat",
name: "Pixel cap",
price: 50,
description: "A cozy cap for your habit pet.",
},
{
id: "bed",
name: "Cloud bed",
price: 120,
description: "Boost recovery after tough days.",
},
{
id: "snack",
name: "Berry snack",
price: 25,
description: "A small treat for good streaks.",
},
];
export default function ShopPage() {
return (
<AppShell
title="Shop"
description="Spend points earned from habits and daily check-ins."
>
<div className="mb-4 flex items-center justify-between rounded-lg border bg-muted/40 px-4 py-3">
<span className="text-sm text-muted-foreground">Your balance</span>
<Badge variant="secondary">120 points</Badge>
</div>
<div className="grid gap-4">
{shopItems.map((item) => (
<Card key={item.id}>
<CardHeader>
<div className="flex items-start justify-between gap-3">
<div>
<CardTitle className="text-base">{item.name}</CardTitle>
<CardDescription>{item.description}</CardDescription>
</div>
<Badge>{item.price} pts</Badge>
</div>
</CardHeader>
<CardContent>
<Button className="w-full" variant="outline">
Buy
</Button>
</CardContent>
</Card>
))}
</div>
</AppShell>
);
}

View File

@@ -1,4 +1,5 @@
import { createClient } from "@/lib/supabase/server";
import { routes } from "@/lib/routes";
import { type EmailOtpType } from "@supabase/supabase-js";
import { redirect } from "next/navigation";
import { type NextRequest } from "next/server";
@@ -7,7 +8,7 @@ export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const token_hash = searchParams.get("token_hash");
const type = searchParams.get("type") as EmailOtpType | null;
const next = searchParams.get("next") ?? "/";
const next = searchParams.get("next") ?? routes.onboardingQuiz;
if (token_hash && type) {
const supabase = await createClient();

View File

@@ -10,7 +10,7 @@ const defaultUrl = process.env.VERCEL_URL
export const metadata: Metadata = {
metadataBase: new URL(defaultUrl),
title: "Habit Pet",
description: "Hackathon bootstrap for a Next.js and Supabase habit pet app.",
description: "Build habits, care for your pixel pet, and track wellness every day.",
};
const geistSans = Geist({

15
app/onboarding/layout.tsx Normal file
View File

@@ -0,0 +1,15 @@
import { Suspense } from "react";
import { OnboardingAuthGate } from "@/components/layout/onboarding-auth-gate";
export default function OnboardingLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<Suspense fallback={<div className="min-h-svh bg-background" />}>
<OnboardingAuthGate>{children}</OnboardingAuthGate>
</Suspense>
);
}

View File

@@ -0,0 +1,148 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { PixelAvatar } from "@/components/avatar/pixel-avatar";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { createClient } from "@/lib/supabase/client";
import { routes } from "@/lib/routes";
const questions = [
{
id: "focus",
prompt: "What habit do you most want to build first?",
options: ["Sleep", "Movement", "Hydration", "Mindfulness"],
},
{
id: "pet-name",
prompt: "Pick a starter vibe for your pet.",
options: ["Calm", "Energetic", "Curious", "Cozy"],
},
];
export default function OnboardingQuizPage() {
const router = useRouter();
const [step, setStep] = useState(0);
const [answers, setAnswers] = useState<Record<string, string>>({});
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const currentQuestion = questions[step];
const isLastStep = step === questions.length - 1;
const handleSelect = (value: string) => {
setAnswers((current) => ({
...current,
[currentQuestion.id]: value,
}));
};
const handleContinue = async () => {
if (!answers[currentQuestion.id]) {
return;
}
if (!isLastStep) {
setStep((current) => current + 1);
return;
}
setIsSubmitting(true);
setError(null);
try {
const supabase = createClient();
const { error: updateError } = await supabase.auth.updateUser({
data: {
onboarding_completed: true,
onboarding_answers: answers,
},
});
if (updateError) {
throw updateError;
}
router.push(routes.avatar);
router.refresh();
} catch (submitError) {
setError(
submitError instanceof Error
? submitError.message
: "Could not save onboarding answers.",
);
} finally {
setIsSubmitting(false);
}
};
return (
<div className="min-h-svh bg-background">
<main className="mx-auto flex min-h-svh max-w-lg flex-col justify-center px-5 py-10">
<div className="mb-8 flex flex-col items-center gap-4 text-center">
<PixelAvatar mood="neutral" size="md" />
<div>
<p className="text-sm uppercase tracking-[0.2em] text-muted-foreground">
Step {step + 1} of {questions.length}
</p>
<h1 className="mt-2 text-2xl font-semibold tracking-tight">
Welcome to Habit Pet
</h1>
</div>
</div>
<Card>
<CardHeader>
<CardTitle className="text-base">{currentQuestion.prompt}</CardTitle>
<CardDescription>
This helps personalize your pet and starting habits.
</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
{currentQuestion.options.map((option) => {
const selected = answers[currentQuestion.id] === option;
return (
<button
key={option}
type="button"
onClick={() => handleSelect(option)}
className={`w-full rounded-lg border px-4 py-3 text-left text-sm transition-colors ${
selected
? "border-primary bg-primary/10"
: "hover:bg-muted"
}`}
>
<Label className="cursor-pointer">{option}</Label>
</button>
);
})}
{error ? <p className="text-sm text-red-500">{error}</p> : null}
<Button
className="w-full"
disabled={!answers[currentQuestion.id] || isSubmitting}
onClick={handleContinue}
>
{isSubmitting
? "Saving..."
: isLastStep
? "Meet your pet"
: "Continue"}
</Button>
</CardContent>
</Card>
</main>
</div>
);
}

View File

@@ -1,58 +1,91 @@
import { DeployButton } from "@/components/deploy-button";
import { EnvVarWarning } from "@/components/env-var-warning";
import { AuthButton } from "@/components/auth-button";
import { Hero } from "@/components/hero";
import { ThemeSwitcher } from "@/components/theme-switcher";
import { ConnectSupabaseSteps } from "@/components/tutorial/connect-supabase-steps";
import { SignUpUserSteps } from "@/components/tutorial/sign-up-user-steps";
import { hasEnvVars } from "@/lib/utils";
import Link from "next/link";
import { Suspense } from "react";
import { PixelAvatar } from "@/components/avatar/pixel-avatar";
import { LoggedInRedirect } from "@/components/layout/logged-in-redirect";
import { SiteFooter, SiteHeader } from "@/components/layout/site-header";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { routes } from "@/lib/routes";
export default function Home() {
return (
<main className="min-h-screen flex flex-col items-center">
<div className="flex-1 w-full flex flex-col gap-20 items-center">
<nav className="w-full flex justify-center border-b border-b-foreground/10 h-16">
<div className="w-full max-w-5xl flex justify-between items-center p-3 px-5 text-sm">
<div className="flex gap-5 items-center font-semibold">
<Link href={"/"}>Habit Pet</Link>
<div className="flex items-center gap-2">
<DeployButton />
</div>
</div>
{!hasEnvVars ? (
<EnvVarWarning />
) : (
<Suspense>
<AuthButton />
<main className="min-h-svh flex flex-col">
<Suspense fallback={null}>
<LoggedInRedirect />
</Suspense>
)}
<SiteHeader />
<div className="mx-auto flex w-full max-w-5xl flex-1 flex-col gap-12 px-5 py-12">
<section className="grid gap-10 lg:grid-cols-[1.1fr_0.9fr] lg:items-center">
<div className="space-y-6">
<p className="text-sm uppercase tracking-[0.25em] text-muted-foreground">
Calgary Hackathon MVP
</p>
<h1 className="text-4xl font-semibold tracking-tight sm:text-5xl">
Build habits. Care for your pixel pet.
</h1>
<p className="max-w-xl text-base text-muted-foreground sm:text-lg">
Habit Pet turns daily check-ins, wellness sliders, and journaling
into a simple game. Keep streaks alive, take your once-per-day
quiz, and watch your pet change with you.
</p>
<div className="flex flex-wrap gap-3">
<Button asChild size="lg">
<Link href={routes.signUp}>Get started</Link>
</Button>
<Button asChild size="lg" variant="outline">
<Link href={routes.login}>Sign in</Link>
</Button>
</div>
</nav>
<div className="flex-1 flex flex-col gap-20 max-w-5xl p-5">
<Hero />
<main className="flex-1 flex flex-col gap-6 px-4">
<h2 className="font-medium text-xl mb-4">Next steps</h2>
{hasEnvVars ? <SignUpUserSteps /> : <ConnectSupabaseSteps />}
</main>
</div>
<footer className="w-full flex items-center justify-center border-t mx-auto text-center text-xs gap-8 py-16">
<p>
Powered by{" "}
<a
href="https://supabase.com/?utm_source=create-next-app&utm_medium=template&utm_term=nextjs"
target="_blank"
className="font-bold hover:underline"
rel="noreferrer"
>
Supabase
</a>
<Card className="border-dashed">
<CardContent className="flex flex-col items-center gap-6 pt-8">
<PixelAvatar mood="happy" />
<div className="space-y-2 text-center">
<p className="text-sm font-medium">Your daily loop</p>
<p className="text-sm text-muted-foreground">
Habits, wellness, journal, quiz, shop.
</p>
<ThemeSwitcher />
</footer>
</div>
</CardContent>
</Card>
</section>
<section className="grid gap-4 md:grid-cols-3">
{[
{
title: "Daily habits",
description: "Custom checkmarks and streak tracking.",
},
{
title: "Wellness + journal",
description: "Sliders and a daily reflection box.",
},
{
title: "Pet that responds",
description: "Avatar mood changes from your input.",
},
].map((feature) => (
<Card key={feature.title}>
<CardHeader>
<CardTitle className="text-base">{feature.title}</CardTitle>
<CardDescription>{feature.description}</CardDescription>
</CardHeader>
</Card>
))}
</section>
</div>
<SiteFooter />
</main>
);
}

View File

@@ -1,43 +1,7 @@
import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { InfoIcon } from "lucide-react";
import { FetchDataSteps } from "@/components/tutorial/fetch-data-steps";
import { Suspense } from "react";
async function UserDetails() {
const supabase = await createClient();
const { data, error } = await supabase.auth.getClaims();
if (error || !data?.claims) {
redirect("/auth/login");
}
return JSON.stringify(data.claims, null, 2);
}
import { routes } from "@/lib/routes";
export default function ProtectedPage() {
return (
<div className="flex-1 w-full flex flex-col gap-12">
<div className="w-full">
<div className="bg-accent text-sm p-3 px-5 rounded-md text-foreground flex gap-3 items-center">
<InfoIcon size="16" strokeWidth={2} />
This is a protected page that you can only see as an authenticated
user
</div>
</div>
<div className="flex flex-col gap-2 items-start">
<h2 className="font-bold text-2xl mb-4">Your user details</h2>
<pre className="text-xs font-mono p-3 rounded border max-h-32 overflow-auto">
<Suspense>
<UserDetails />
</Suspense>
</pre>
</div>
<div>
<h2 className="font-bold text-2xl mb-4">Next steps</h2>
<FetchDataSteps />
</div>
</div>
);
redirect(routes.avatar);
}

View File

@@ -1,28 +1,29 @@
import Link from "next/link";
import { Button } from "./ui/button";
import { createClient } from "@/lib/supabase/server";
import { LogoutButton } from "./logout-button";
import { routes } from "@/lib/routes";
export async function AuthButton() {
const supabase = await createClient();
// You can also use getUser() which will be slower.
const { data } = await supabase.auth.getClaims();
const user = data?.claims;
return user ? (
<div className="flex items-center gap-4">
Hey, {user.email}!
<div className="flex items-center gap-3">
<Button asChild size="sm" variant="outline">
<Link href={routes.avatar}>Open app</Link>
</Button>
<LogoutButton />
</div>
) : (
<div className="flex gap-2">
<Button asChild size="sm" variant={"outline"}>
<Link href="/auth/login">Sign in</Link>
<Link href={routes.login}>Sign in</Link>
</Button>
<Button asChild size="sm" variant={"default"}>
<Link href="/auth/sign-up">Sign up</Link>
<Link href={routes.signUp}>Sign up</Link>
</Button>
</div>
);

View File

@@ -0,0 +1,52 @@
import { cn } from "@/lib/utils";
type AvatarMood = "happy" | "neutral" | "tired";
const moodStyles: Record<AvatarMood, string> = {
happy: "bg-emerald-400 shadow-[0_0_0_4px_rgba(16,185,129,0.25)]",
neutral: "bg-amber-300 shadow-[0_0_0_4px_rgba(251,191,36,0.25)]",
tired: "bg-sky-400 shadow-[0_0_0_4px_rgba(56,189,248,0.25)]",
};
type PixelAvatarProps = {
mood?: AvatarMood;
size?: "sm" | "md" | "lg";
className?: string;
};
const sizeStyles = {
sm: "h-16 w-16",
md: "h-24 w-24",
lg: "h-32 w-32",
};
export function PixelAvatar({
mood = "neutral",
size = "lg",
className,
}: PixelAvatarProps) {
return (
<div
className={cn("flex flex-col items-center gap-3", className)}
aria-label={`Pixel pet avatar, mood ${mood}`}
>
<div
className={cn(
"relative rounded-md border-2 border-foreground/80",
sizeStyles[size],
moodStyles[mood],
)}
style={{ imageRendering: "pixelated" }}
>
<div className="absolute left-1/2 top-[28%] flex -translate-x-1/2 gap-2">
<span className="h-2 w-2 rounded-[1px] bg-foreground/90" />
<span className="h-2 w-2 rounded-[1px] bg-foreground/90" />
</div>
<div className="absolute bottom-[24%] left-1/2 h-1 w-4 -translate-x-1/2 rounded-[1px] bg-foreground/80" />
</div>
<p className="text-xs uppercase tracking-[0.2em] text-muted-foreground">
{mood}
</p>
</div>
);
}

View File

@@ -0,0 +1,10 @@
import { requireOnboardingComplete } from "@/lib/auth-helpers";
type AppAuthGateProps = {
children: React.ReactNode;
};
export async function AppAuthGate({ children }: AppAuthGateProps) {
await requireOnboardingComplete();
return children;
}

View File

@@ -0,0 +1,48 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Home, ShoppingBag, Sparkles, UserRound } from "lucide-react";
import { cn } from "@/lib/utils";
import { appNavItems, routes } from "@/lib/routes";
const navIcons = {
[routes.avatar]: Home,
[routes.dailyQuiz]: Sparkles,
[routes.shop]: ShoppingBag,
[routes.profile]: UserRound,
} as const;
export function AppNav() {
const pathname = usePathname();
return (
<nav className="fixed inset-x-0 bottom-0 z-50 border-t bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80">
<div className="mx-auto grid max-w-lg grid-cols-4 gap-1 px-2 pb-[max(0.5rem,env(safe-area-inset-bottom))] pt-2">
{appNavItems.map((item) => {
const Icon = navIcons[item.href];
const isActive =
pathname === item.href ||
(item.href !== routes.avatar && pathname.startsWith(item.href));
return (
<Link
key={item.href}
href={item.href}
className={cn(
"flex flex-col items-center gap-1 rounded-lg px-2 py-2 text-[11px] font-medium transition-colors",
isActive
? "bg-primary text-primary-foreground"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<Icon className="h-4 w-4" />
<span>{item.shortLabel}</span>
</Link>
);
})}
</div>
</nav>
);
}

View File

@@ -0,0 +1,28 @@
import { AppNav } from "@/components/layout/app-nav";
type AppShellProps = {
children: React.ReactNode;
title?: string;
description?: string;
};
export function AppShell({ children, title, description }: AppShellProps) {
return (
<div className="min-h-svh bg-background pb-24">
{(title || description) && (
<header className="border-b border-border/60 bg-card/40">
<div className="mx-auto max-w-lg px-5 py-5">
{title ? (
<h1 className="text-xl font-semibold tracking-tight">{title}</h1>
) : null}
{description ? (
<p className="mt-1 text-sm text-muted-foreground">{description}</p>
) : null}
</div>
</header>
)}
<main className="mx-auto max-w-lg px-5 py-6">{children}</main>
<AppNav />
</div>
);
}

View File

@@ -0,0 +1,19 @@
import { redirect } from "next/navigation";
import {
getSessionUser,
hasCompletedOnboarding,
} from "@/lib/auth-helpers";
import { routes } from "@/lib/routes";
export async function LoggedInRedirect() {
const user = await getSessionUser();
if (user) {
redirect(
hasCompletedOnboarding(user) ? routes.avatar : routes.onboardingQuiz,
);
}
return null;
}

View File

@@ -0,0 +1,21 @@
import { redirect } from "next/navigation";
import {
hasCompletedOnboarding,
requireSessionUser,
} from "@/lib/auth-helpers";
import { routes } from "@/lib/routes";
type OnboardingAuthGateProps = {
children: React.ReactNode;
};
export async function OnboardingAuthGate({ children }: OnboardingAuthGateProps) {
const user = await requireSessionUser();
if (hasCompletedOnboarding(user)) {
redirect(routes.avatar);
}
return children;
}

View File

@@ -0,0 +1,38 @@
import Link from "next/link";
import { Suspense } from "react";
import { AuthButton } from "@/components/auth-button";
import { EnvVarWarning } from "@/components/env-var-warning";
import { ThemeSwitcher } from "@/components/theme-switcher";
import { routes } from "@/lib/routes";
import { hasEnvVars } from "@/lib/utils";
export function SiteHeader() {
return (
<header className="w-full border-b border-b-foreground/10">
<div className="mx-auto flex h-16 w-full max-w-5xl items-center justify-between px-5 text-sm">
<Link href={routes.home} className="font-semibold tracking-tight">
Habit Pet
</Link>
{!hasEnvVars ? (
<EnvVarWarning />
) : (
<Suspense>
<AuthButton />
</Suspense>
)}
</div>
</header>
);
}
export function SiteFooter() {
return (
<footer className="w-full border-t py-8 text-center text-xs text-muted-foreground">
<div className="mx-auto flex max-w-5xl flex-col items-center gap-4 px-5">
<p>Build habits. Care for your pet. Feel better every day.</p>
<ThemeSwitcher />
</div>
</footer>
);
}

View File

@@ -16,6 +16,8 @@ import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { routes } from "@/lib/routes";
export function LoginForm({
className,
...props
@@ -38,8 +40,8 @@ export function LoginForm({
password,
});
if (error) throw error;
// Update this route to redirect to an authenticated route. The user already has an active session.
router.push("/protected");
router.push(routes.avatar);
router.refresh();
} catch (error: unknown) {
setError(error instanceof Error ? error.message : "An error occurred");
} finally {

View File

@@ -16,6 +16,8 @@ import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { routes } from "@/lib/routes";
export function SignUpForm({
className,
...props
@@ -44,7 +46,7 @@ export function SignUpForm({
email,
password,
options: {
emailRedirectTo: `${window.location.origin}/protected`,
emailRedirectTo: `${window.location.origin}${routes.onboardingQuiz}`,
},
});
if (error) throw error;

43
lib/auth-helpers.ts Normal file
View File

@@ -0,0 +1,43 @@
import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { routes } from "@/lib/routes";
import type { User } from "@supabase/supabase-js";
export function hasCompletedOnboarding(user: User) {
return user.user_metadata?.onboarding_completed === true;
}
export async function getSessionUser() {
const supabase = await createClient();
const {
data: { user },
error,
} = await supabase.auth.getUser();
if (error || !user) {
return null;
}
return user;
}
export async function requireSessionUser() {
const user = await getSessionUser();
if (!user) {
redirect(routes.login);
}
return user;
}
export async function requireOnboardingComplete() {
const user = await requireSessionUser();
if (!hasCompletedOnboarding(user)) {
redirect(routes.onboardingQuiz);
}
return user;
}

28
lib/routes.ts Normal file
View File

@@ -0,0 +1,28 @@
export const routes = {
home: "/",
login: "/auth/login",
signUp: "/auth/sign-up",
signUpSuccess: "/auth/sign-up-success",
onboardingQuiz: "/onboarding/quiz",
avatar: "/avatar",
dailyQuiz: "/daily/quiz",
shop: "/shop",
profile: "/profile",
} as const;
export type AppRoute = (typeof routes)[keyof typeof routes];
export const appNavItems = [
{ href: routes.avatar, label: "Pet", shortLabel: "Pet" },
{ href: routes.dailyQuiz, label: "Daily Quiz", shortLabel: "Quiz" },
{ href: routes.shop, label: "Shop", shortLabel: "Shop" },
{ href: routes.profile, label: "Profile", shortLabel: "Profile" },
] as const;
export function isAuthPath(pathname: string) {
return pathname.startsWith("/auth");
}
export function isPublicPath(pathname: string) {
return pathname === routes.home || isAuthPath(pathname);
}

View File

@@ -1,7 +1,8 @@
import { createServerClient } from "@supabase/ssr";
import { NextResponse, type NextRequest } from "next/server";
import { hasEnvVars } from "../utils";
import { isPublicPath, routes } from "@/lib/routes";
import { getSupabaseEnv } from "@/lib/supabase/env";
import { hasEnvVars } from "../utils";
export async function updateSession(request: NextRequest) {
let supabaseResponse = NextResponse.next({
@@ -50,15 +51,11 @@ export async function updateSession(request: NextRequest) {
const { data } = await supabase.auth.getClaims();
const user = data?.claims;
if (
request.nextUrl.pathname !== "/" &&
!user &&
!request.nextUrl.pathname.startsWith("/login") &&
!request.nextUrl.pathname.startsWith("/auth")
) {
// no user, potentially respond by redirecting the user to the login page
const { pathname } = request.nextUrl;
if (!user && !isPublicPath(pathname)) {
const url = request.nextUrl.clone();
url.pathname = "/auth/login";
url.pathname = routes.login;
return NextResponse.redirect(url);
}

3
package-lock.json generated
View File

@@ -1,9 +1,10 @@
{
"name": "bootstrap-stack",
"name": "habit-pet",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "habit-pet",
"dependencies": {
"@radix-ui/react-checkbox": "^1.3.1",
"@radix-ui/react-dropdown-menu": "^2.1.14",