feat: implement authentication layout and pages, including login and registration forms, with validation and API integration

This commit is contained in:
2025-09-06 19:19:20 +02:00
parent e7cf76a0d8
commit c7cb3f537d
11 changed files with 572 additions and 157 deletions

View File

@@ -0,0 +1,12 @@
// app/(auth)/layout.tsx
export default function AuthLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div className="flex items-center justify-center min-h-screen bg-gray-100">
{children}
</div>
);
}

View File

@@ -0,0 +1,112 @@
"use client";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import {
Form,
FormField,
FormItem,
FormLabel,
FormControl,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { LoginSchema, loginUser } from "@/lib/api";
import { useAuth } from "@/hooks/use-auth";
import { useState } from "react";
export default function LoginPage() {
const router = useRouter();
const { setToken } = useAuth();
const [error, setError] = useState<string | null>(null);
const form = useForm<z.infer<typeof LoginSchema>>({
resolver: zodResolver(LoginSchema),
defaultValues: { username: "", password: "" },
});
async function onSubmit(values: z.infer<typeof LoginSchema>) {
try {
setError(null);
const { token } = await loginUser(values);
setToken(token);
router.push("/"); // Redirect to homepage on successful login
} catch (err) {
setError("Invalid username or password.");
}
}
return (
<Card className="w-full max-w-sm">
<CardHeader>
<CardTitle>Login</CardTitle>
<CardDescription>
Enter your credentials to access your account.
</CardDescription>
</CardHeader>
<CardContent>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
{/* ... Form fields for username and password ... */}
<FormField
control={form.control}
name="username"
render={({ field }) => (
<FormItem>
<FormLabel>Username</FormLabel>
<FormControl>
<Input placeholder="frutiger" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input type="password" placeholder="••••••••" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{error && (
<p className="text-sm font-medium text-destructive">{error}</p>
)}
<Button
type="submit"
className="w-full"
disabled={form.formState.isSubmitting}
>
{form.formState.isSubmitting ? "Logging in..." : "Login"}
</Button>
</form>
</Form>
<p className="mt-4 text-center text-sm text-gray-600">
Don&apos;t have an account?{" "}
<Link
href="/register"
className="font-medium text-blue-600 hover:underline"
>
Register
</Link>
</p>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,125 @@
"use client";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import {
Form,
FormField,
FormItem,
FormLabel,
FormControl,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { RegisterSchema, registerUser } from "@/lib/api";
import { useState } from "react";
export default function RegisterPage() {
const router = useRouter();
const [error, setError] = useState<string | null>(null);
const form = useForm<z.infer<typeof RegisterSchema>>({
resolver: zodResolver(RegisterSchema),
defaultValues: { username: "", email: "", password: "" },
});
async function onSubmit(values: z.infer<typeof RegisterSchema>) {
try {
setError(null);
await registerUser(values);
// You can automatically log the user in here or just redirect them
router.push("/login");
} catch (err) {
setError("Username or email may already be taken.");
}
}
return (
<Card className="w-full max-w-sm">
<CardHeader>
<CardTitle>Create an Account</CardTitle>
<CardDescription>Enter your details to register.</CardDescription>
</CardHeader>
<CardContent>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
{/* ... Form fields for username, email, and password ... */}
<FormField
control={form.control}
name="username"
render={({ field }) => (
<FormItem>
<FormLabel>Username</FormLabel>
<FormControl>
<Input placeholder="frutiger" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input
type="email"
placeholder="aero@example.com"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input type="password" placeholder="••••••••" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{error && (
<p className="text-sm font-medium text-destructive">{error}</p>
)}
<Button
type="submit"
className="w-full"
disabled={form.formState.isSubmitting}
>
{form.formState.isSubmitting ? "Creating account..." : "Register"}
</Button>
</form>
</Form>
<p className="mt-4 text-center text-sm text-gray-600">
Already have an account?{" "}
<Link
href="/login"
className="font-medium text-blue-600 hover:underline"
>
Login
</Link>
</p>
</CardContent>
</Card>
);
}

View File

@@ -1,6 +1,8 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { AuthProvider } from "@/hooks/use-auth";
import { Toaster } from "@/components/ui/sonner";
const geistSans = Geist({
variable: "--font-geist-sans",
@@ -27,7 +29,10 @@ export default function RootLayout({
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
<AuthProvider>
{children}
<Toaster />
</AuthProvider>
</body>
</html>
);

View File

@@ -1,155 +1,83 @@
"use client";
import { useState, useEffect, FormEvent } from "react";
// app/page.tsx
import { cookies } from "next/headers";
import { getFeed, getUserProfile } from "@/lib/api";
import { ThoughtCard } from "@/components/thought-card";
import { PostThoughtForm } from "@/components/post-thought-form";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardHeader, CardContent } from "@/components/ui/card";
import { Alert } from "@/components/ui/alert";
import Link from "next/link";
interface Thought {
id: number;
author_id: number;
content: string;
created_at: string;
// This is now an async Server Component
export default async function Home() {
const token = (await cookies()).get("auth_token")?.value ?? null;
if (token) {
return <FeedPage token={token} />;
} else {
return <LandingPage />;
}
}
export default function Home() {
const [thoughts, setThoughts] = useState<Thought[]>([]);
const [newThoughtContent, setNewThoughtContent] = useState("");
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
async function FeedPage({ token }: { token: string }) {
const feedData = await getFeed(token);
const authors = [...new Set(feedData.thoughts.map((t) => t.authorUsername))];
const userProfiles = await Promise.all(
authors.map((username) => getUserProfile(username, token).catch(() => null))
);
const fetchFeed = async () => {
try {
setError(null);
const response = await fetch("http://localhost:8000/feed");
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setThoughts(data.thoughts || []);
} catch (e: unknown) {
console.error("Failed to fetch feed:", e);
setError(
"Could not load the feed. The backend might be busy. Please try refreshing."
);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
fetchFeed();
}, []);
const handleSubmitThought = async (e: FormEvent) => {
e.preventDefault();
if (!newThoughtContent.trim()) return;
try {
const response = await fetch("http://localhost:8000/thoughts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ content: newThoughtContent, author_id: 1 }),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
setNewThoughtContent("");
fetchFeed();
} catch (e: unknown) {
console.error("Failed to post thought:", e);
setError("Failed to post your thought. Please try again.");
}
};
const authorDetails = new Map(
userProfiles
.filter(Boolean)
.map((user) => [user!.username, { avatarUrl: user!.avatarUrl }])
);
return (
<div className="font-sans bg-gradient-to-br from-sky-200 via-teal-100 to-green-200 min-h-screen text-gray-800">
<div className="container mx-auto max-w-2xl p-4 sm:p-6">
{/* Header */}
<header className="text-center my-6">
<h1
className="text-5xl font-bold text-white"
style={{ textShadow: "2px 2px 4px rgba(0,0,0,0.2)" }}
>
Thoughts
</h1>
<p className="text-white/80 mt-2">
Your space on the decentralized web.
<div className="container mx-auto max-w-2xl p-4 sm:p-6">
<header className="my-6">
<h1 className="text-3xl font-bold">Your Feed</h1>
</header>
<main className="space-y-6">
<PostThoughtForm />
{feedData.thoughts.map((thought) => (
<ThoughtCard
key={thought.id}
thought={thought}
author={{
username: thought.authorUsername,
avatarUrl: authorDetails.get(thought.authorUsername)?.avatarUrl,
}}
/>
))}
{feedData.thoughts.length === 0 && (
<p className="text-center text-muted-foreground pt-8">
Your feed is empty. Follow some users to see their thoughts here!
</p>
</header>
)}
</main>
</div>
);
}
{/* New Thought Form */}
<Card className="bg-white/70 backdrop-blur-lg rounded-xl shadow-lg p-5 mb-8">
<form onSubmit={handleSubmitThought}>
<Textarea
value={newThoughtContent}
onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) =>
setNewThoughtContent(e.target.value)
}
className="resize-none"
placeholder="What's on your mind?"
maxLength={128}
/>
<div className="flex justify-between items-center mt-3">
<span className="text-sm text-gray-500">
{128 - newThoughtContent.length} characters remaining
</span>
<Button
type="submit"
variant="default"
disabled={!newThoughtContent.trim()}
>
Post
</Button>
</div>
</form>
</Card>
{/* Feed Section */}
<main>
{isLoading ? (
<p className="text-center text-gray-600">Loading feed...</p>
) : error ? (
<Alert variant="destructive" className="text-center">
{error}
</Alert>
) : thoughts.length === 0 ? (
<p className="text-center text-gray-600">
The feed is empty. Follow some users to see their thoughts!
</p>
) : (
<div className="space-y-4">
{thoughts.map((thought) => (
<Card
key={thought.id}
className="bg-white/80 backdrop-blur-lg rounded-xl shadow-lg p-4 transition-transform hover:scale-[1.02]"
>
<CardHeader className="flex items-center mb-2">
<div className="w-10 h-10 rounded-full bg-gradient-to-br from-green-300 to-sky-400 flex items-center justify-center font-bold text-white mr-3">
{thought.author_id}
</div>
<div>
<p className="font-bold">User {thought.author_id}</p>
<p className="text-xs text-gray-500">
{new Date(thought.created_at).toLocaleString()}
</p>
</div>
</CardHeader>
<CardContent>
<p className="text-gray-800 break-words">
{thought.content}
</p>
</CardContent>
</Card>
))}
</div>
)}
</main>
function LandingPage() {
return (
<div className="font-sans min-h-screen text-gray-800 flex items-center justify-center">
<div className="container mx-auto max-w-2xl p-4 sm:p-6 text-center">
<h1
className="text-5xl font-bold"
style={{ textShadow: "2px 2px 4px rgba(0,0,0,0.1)" }}
>
Welcome to Thoughts
</h1>
<p className="text-muted-foreground mt-2">
Your space on the decentralized web.
</p>
<div className="mt-8 flex justify-center gap-4">
<Button asChild>
<Link href="/login">Login</Link>
</Button>
<Button variant="secondary" asChild>
<Link href="/register">Register</Link>
</Button>
</div>
</div>
</div>
);

View File

@@ -4,6 +4,7 @@ import { ThoughtCard } from "@/components/thought-card";
import { Calendar } from "lucide-react";
import { Card } from "@/components/ui/card";
import { notFound } from "next/navigation";
import { cookies } from "next/headers";
interface ProfilePageProps {
params: { username: string };
@@ -11,12 +12,13 @@ interface ProfilePageProps {
export default async function ProfilePage({ params }: ProfilePageProps) {
const { username } = params;
const token = (await cookies()).get("auth_token")?.value ?? null;
// Fetch data directly on the server.
// The `loading.tsx` file will be shown to the user during this fetch.
const [userResult, thoughtsResult] = await Promise.allSettled([
getUserProfile(username),
getUserThoughts(username),
getUserProfile(username, token),
getUserThoughts(username, token),
]);
// Handle errors from the server-side fetch