seem good

This commit is contained in:
2026-02-18 22:27:05 +09:00
parent 826ce4ba96
commit 3bdb2e9f5b
22 changed files with 2925 additions and 14 deletions

439
frontend/app/auth/page.tsx Normal file
View File

@@ -0,0 +1,439 @@
"use client";
import { useState, useEffect, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useAuth } from "@/lib/auth";
import { clientFetch } from "@/lib/api";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { Eye, EyeOff, Loader2, LogIn, UserPlus, KeyRound, Mail } from "lucide-react";
import { API_URL } from "@/lib/api";
import { UserRole } from "@/lib/types";
// Default export wraps the inner component in Suspense (required by Next.js
// when useSearchParams() is used inside a "use client" page).
export default function AuthPage() {
return (
<Suspense>
<AuthPageInner />
</Suspense>
);
}
function AuthPageInner() {
const { currentUser, login, register, refresh } = useAuth();
const router = useRouter();
const searchParams = useSearchParams();
const resetToken = searchParams.get("token") || "";
const initialTab = resetToken ? "reset" : "signin";
const [loading, setLoading] = useState(false);
const [showPwd, setShowPwd] = useState(false);
// Redirect if already logged in
useEffect(() => {
if (currentUser) router.replace("/dashboard");
}, [currentUser, router]);
// ── Sign In ───────────────────────────────────────────────────────────────
const handleSignIn = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const fd = new FormData(e.currentTarget);
const email = fd.get("email") as string;
const password = fd.get("password") as string;
setLoading(true);
try {
await login(email, password);
toast.success("Welcome back!");
router.push("/dashboard");
router.refresh();
} catch (err: unknown) {
toast.error(err instanceof Error ? err.message : "Login failed");
} finally {
setLoading(false);
}
};
// ── Sign Up ───────────────────────────────────────────────────────────────
const handleSignUp = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const fd = new FormData(e.currentTarget);
const name = fd.get("name") as string;
const email = fd.get("email") as string;
const password = fd.get("password") as string;
setLoading(true);
try {
await register(name, email, password);
toast.success("Account created! Welcome!");
router.push("/dashboard");
router.refresh();
} catch (err: unknown) {
toast.error(err instanceof Error ? err.message : "Registration failed");
} finally {
setLoading(false);
}
};
// ── Magic Link ────────────────────────────────────────────────────────────
const handleMagicLink = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const fd = new FormData(e.currentTarget);
const email = fd.get("email") as string;
setLoading(true);
try {
await clientFetch("/auth/magic-link", {
method: "POST",
body: JSON.stringify({ email }),
});
toast.success("Magic link sent! Check your email.");
} catch (err: unknown) {
toast.error(err instanceof Error ? err.message : "Failed to send magic link");
} finally {
setLoading(false);
}
};
// ── Password Reset Request ────────────────────────────────────────────────
const handleResetRequest = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const fd = new FormData(e.currentTarget);
const email = fd.get("email") as string;
setLoading(true);
try {
await clientFetch("/auth/password-reset/request", {
method: "POST",
body: JSON.stringify({ email }),
});
toast.success("Reset link sent! Check your email.");
} catch (err: unknown) {
toast.error(err instanceof Error ? err.message : "Failed");
} finally {
setLoading(false);
}
};
// ── Password Reset Confirm ────────────────────────────────────────────────
const handleResetConfirm = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const fd = new FormData(e.currentTarget);
const token = fd.get("token") as string;
const password = fd.get("password") as string;
setLoading(true);
try {
await clientFetch("/auth/password-reset/confirm", {
method: "POST",
body: JSON.stringify({ token, password }),
});
toast.success("Password updated! You can now sign in.");
} catch (err: unknown) {
toast.error(err instanceof Error ? err.message : "Failed to reset password");
} finally {
setLoading(false);
}
};
return (
<div className="mx-auto max-w-lg space-y-5">
<Tabs defaultValue={initialTab}>
<TabsList className="grid w-full grid-cols-3">
<TabsTrigger value="signin">Sign In</TabsTrigger>
<TabsTrigger value="signup">Sign Up</TabsTrigger>
<TabsTrigger value="reset">Reset</TabsTrigger>
</TabsList>
{/* ── Sign In Tab ─────────────────────────────────────────────────── */}
<TabsContent value="signin">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<LogIn className="h-5 w-5" /> Sign In
</CardTitle>
<CardDescription>
Sign in to your account to access the dashboard.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<form onSubmit={handleSignIn} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="signin-email">Email</Label>
<Input
id="signin-email"
name="email"
type="email"
placeholder="you@example.com"
required
autoComplete="email"
/>
</div>
<div className="space-y-2">
<Label htmlFor="signin-password">Password</Label>
<div className="flex gap-2">
<Input
id="signin-password"
name="password"
type={showPwd ? "text" : "password"}
placeholder="Enter your password"
required
autoComplete="current-password"
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={() => setShowPwd((v) => !v)}
>
{showPwd ? (
<EyeOff className="h-4 w-4" />
) : (
<Eye className="h-4 w-4" />
)}
</Button>
</div>
</div>
<Button type="submit" className="w-full" disabled={loading}>
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Sign In
</Button>
</form>
<Separator />
<form onSubmit={handleMagicLink} className="space-y-2">
<Input
id="magic-email"
name="email"
type="email"
placeholder="Magic link: enter your email"
/>
<Button
type="submit"
variant="outline"
className="w-full"
disabled={loading}
>
<Mail className="mr-2 h-4 w-4" />
Send magic link
</Button>
</form>
<Button
variant="outline"
className="w-full"
onClick={() =>
(window.location.href = `${API_URL}/auth/google`)
}
>
<svg className="mr-2 h-4 w-4" viewBox="0 0 24 24">
<path
fill="currentColor"
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"
/>
<path
fill="currentColor"
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"
/>
<path
fill="currentColor"
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"
/>
<path
fill="currentColor"
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"
/>
</svg>
Continue with Google
</Button>
</CardContent>
</Card>
</TabsContent>
{/* ── Sign Up Tab ─────────────────────────────────────────────────── */}
<TabsContent value="signup">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<UserPlus className="h-5 w-5" /> Create Account
</CardTitle>
<CardDescription>
New sign-ups are assigned the default MEMBER role.
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSignUp} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="signup-name">Full Name</Label>
<Input
id="signup-name"
name="name"
placeholder="Your full name"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="signup-email">Email</Label>
<Input
id="signup-email"
name="email"
type="email"
placeholder="you@example.com"
required
autoComplete="email"
/>
</div>
<div className="space-y-2">
<Label htmlFor="signup-password">Password</Label>
<div className="flex gap-2">
<Input
id="signup-password"
name="password"
type={showPwd ? "text" : "password"}
placeholder="Create a password"
required
autoComplete="new-password"
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={() => setShowPwd((v) => !v)}
>
{showPwd ? (
<EyeOff className="h-4 w-4" />
) : (
<Eye className="h-4 w-4" />
)}
</Button>
</div>
</div>
<Button type="submit" className="w-full" disabled={loading}>
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Create Account
</Button>
</form>
</CardContent>
</Card>
</TabsContent>
{/* ── Reset Password Tab ──────────────────────────────────────────── */}
<TabsContent value="reset">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<KeyRound className="h-5 w-5" /> Reset Password
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{/* Step 1: Request */}
<form onSubmit={handleResetRequest} className="space-y-3">
<Label>Request reset link</Label>
<div className="flex gap-2">
<Input name="email" type="email" placeholder="your@email.com" />
<Button type="submit" variant="outline" disabled={loading}>
{loading && (
<Loader2 className="mr-1 h-4 w-4 animate-spin" />
)}
Send
</Button>
</div>
</form>
<Separator />
{/* Step 2: Confirm */}
<form onSubmit={handleResetConfirm} className="space-y-3">
<Label>Confirm new password</Label>
<Input
name="token"
placeholder="Reset token from email"
defaultValue={resetToken}
required
/>
<div className="flex gap-2">
<Input
name="password"
type={showPwd ? "text" : "password"}
placeholder="New password"
required
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={() => setShowPwd((v) => !v)}
>
{showPwd ? (
<EyeOff className="h-4 w-4" />
) : (
<Eye className="h-4 w-4" />
)}
</Button>
</div>
<Button type="submit" className="w-full" disabled={loading}>
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Update Password
</Button>
</form>
</CardContent>
</Card>
</TabsContent>
</Tabs>
{/* ── Demo credentials card ─────────────────────────────────────────── */}
<Card className="border-dashed">
<CardContent className="pt-5 space-y-3">
<div className="rounded-lg bg-muted p-4 space-y-1">
<p className="font-semibold">Demo Admin Account</p>
<p className="text-sm text-muted-foreground">
Email: <strong>admin@gmail.com</strong>
</p>
<p className="text-sm text-muted-foreground">
Password: <strong>Whatever123$</strong>
</p>
<Button
size="sm"
variant="secondary"
className="mt-2"
onClick={() => {
const emailInput = document.getElementById(
"signin-email"
) as HTMLInputElement | null;
const pwdInput = document.getElementById(
"signin-password"
) as HTMLInputElement | null;
if (emailInput) emailInput.value = "admin@gmail.com";
if (pwdInput) pwdInput.value = "Whatever123$";
document.querySelector<HTMLButtonElement>('[value="signin"]')?.click();
}}
>
Use these credentials
</Button>
</div>
<div className="space-y-2 text-sm">
<p className="font-semibold">Role Permissions</p>
<div className="space-y-1 text-muted-foreground">
<p>
<span className="font-medium text-blue-600">MEMBER</span> View
blog posts only
</p>
<p>
<span className="font-medium text-amber-600">MANAGER</span>
View all + create (draft only)
</p>
<p>
<span className="font-medium text-red-600">ADMIN</span> Full
CRUD access + user management
</p>
</div>
</div>
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,308 @@
import { notFound } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import { marked } from "marked";
import { apiFetch } from "@/lib/api";
import { BlogPost, PaginatedResult, TagCloudItem } from "@/lib/types";
import { ViewTracker } from "./view-tracker";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { Eye, TrendingUp, ArrowLeft, Calendar } from "lucide-react";
import { Button } from "@/components/ui/button";
interface Props {
params: Promise<{ slug: string }>;
}
export async function generateMetadata({ params }: Props) {
const { slug } = await params;
try {
const { post } = await apiFetch<{ post: BlogPost }>(
`/blog-posts/public/${slug}`
);
return {
title: post.title,
description: post.excerpt,
openGraph: {
title: post.title,
description: post.excerpt,
images: post.featuredImageUrl ? [post.featuredImageUrl] : [],
},
};
} catch {
return { title: "Post not found" };
}
}
async function getPost(slug: string): Promise<BlogPost | null> {
try {
const data = await apiFetch<{ success: boolean; post: BlogPost }>(
`/blog-posts/public/${slug}`
);
return data.post;
} catch {
return null;
}
}
async function getRelatedPosts(post: BlogPost): Promise<BlogPost[]> {
try {
// Get posts with shared category
const cat = post.categories[0];
if (cat) {
const result = await apiFetch<PaginatedResult<BlogPost>>(
`/blog-posts/public?category=${encodeURIComponent(cat)}&pageSize=4`
);
const filtered = result.items.filter((p) => p.id !== post.id);
if (filtered.length > 0) return filtered.slice(0, 4);
}
// Fallback: latest
const result = await apiFetch<PaginatedResult<BlogPost>>(
"/blog-posts/public?pageSize=4"
);
return result.items.filter((p) => p.id !== post.id).slice(0, 4);
} catch {
return [];
}
}
async function getPopularPosts(excludeId: string): Promise<BlogPost[]> {
try {
const result = await apiFetch<PaginatedResult<BlogPost>>(
"/blog-posts/public?sort=most_viewed&pageSize=6"
);
return result.items.filter((p) => p.id !== excludeId).slice(0, 5);
} catch {
return [];
}
}
async function getTopTags(): Promise<TagCloudItem[]> {
try {
const result = await apiFetch<PaginatedResult<BlogPost>>(
"/blog-posts/public?pageSize=100"
);
const counts: Record<string, number> = {};
for (const post of result.items) {
for (const tag of post.tags || []) {
const t = tag.trim();
if (t) counts[t] = (counts[t] || 0) + 1;
}
}
return Object.entries(counts)
.map(([name, count]) => ({ name, count }))
.sort((a, b) => b.count - a.count)
.slice(0, 20);
} catch {
return [];
}
}
export default async function BlogDetailPage({ params }: Props) {
const { slug } = await params;
const post = await getPost(slug);
if (!post) return notFound();
const [relatedPosts, popularPosts, topTags] = await Promise.all([
getRelatedPosts(post),
getPopularPosts(post.id),
getTopTags(),
]);
const contentHtml =
post.contentFormat === "markdown"
? await marked(post.content)
: post.content;
const publishedDate = new Date(post.createdAt).toLocaleDateString("en-US", {
year: "numeric",
month: "long",
day: "numeric",
});
return (
<div className="space-y-6">
<ViewTracker slug={slug} />
{/* ── Back button ────────────────────────────────────────────────────── */}
<Button asChild variant="ghost" size="sm" className="-ml-2">
<Link href="/">
<ArrowLeft className="h-4 w-4 mr-1" /> Back to Blog
</Link>
</Button>
{/* ── Article ────────────────────────────────────────────────────────── */}
<article className="rounded-2xl border bg-card p-5 shadow-sm">
{/* Categories */}
{post.categories.length > 0 && (
<div className="mb-3 flex flex-wrap gap-2">
{post.categories.map((cat) => (
<Badge key={cat} variant="secondary" className="uppercase tracking-wide text-xs">
{cat}
</Badge>
))}
</div>
)}
<h1 className="text-3xl font-bold leading-tight">{post.title}</h1>
{post.excerpt && (
<p className="mt-3 text-lg text-muted-foreground">{post.excerpt}</p>
)}
{/* Meta */}
<div className="mt-3 flex flex-wrap gap-3 text-sm text-muted-foreground">
<span className="flex items-center gap-1">
<Calendar className="h-3 w-3" /> {publishedDate}
</span>
<span className="flex items-center gap-1">
<Eye className="h-3 w-3" /> {post.views.toLocaleString()} views
</span>
{post.author && (
<span>by {post.author.name || post.author.email}</span>
)}
</div>
{/* Featured image */}
{post.featuredImageUrl && (
<div className="mt-5 relative h-64 md:h-96 w-full overflow-hidden rounded-xl">
<Image
src={post.featuredImageUrl}
alt={post.featuredImageAlt || post.title}
fill
className="object-cover"
sizes="(max-width: 768px) 100vw, 800px"
priority
/>
</div>
)}
{/* Tags */}
{post.tags.length > 0 && (
<div className="mt-4 flex flex-wrap gap-2">
{post.tags.map((tag) => (
<Link key={tag} href={`/?tags=${encodeURIComponent(tag)}`}>
<Badge variant="outline" className="cursor-pointer hover:bg-muted">
#{tag}
</Badge>
</Link>
))}
</div>
)}
<Separator className="my-6" />
{/* Content */}
<div
className="prose prose-zinc dark:prose-invert max-w-none
prose-headings:font-bold prose-headings:tracking-tight
prose-h1:text-3xl prose-h2:text-2xl prose-h3:text-xl
prose-a:text-primary prose-a:no-underline hover:prose-a:underline
prose-code:bg-muted prose-code:px-1 prose-code:py-0.5 prose-code:rounded
prose-pre:bg-muted prose-pre:border prose-pre:rounded-lg
prose-blockquote:border-l-4 prose-blockquote:border-muted-foreground/30
prose-img:rounded-xl prose-img:border"
dangerouslySetInnerHTML={{ __html: contentHtml }}
/>
</article>
{/* ── Related + Sidebar ──────────────────────────────────────────────── */}
<div className="grid gap-6 lg:grid-cols-[1fr_20rem]">
{/* Related posts */}
<section className="rounded-2xl border bg-card p-5">
<h2 className="mb-4 text-xl font-bold">More from the blog</h2>
{relatedPosts.length > 0 ? (
<div className="grid gap-3 sm:grid-cols-2">
{relatedPosts.map((related) => (
<article
key={related.id}
className="rounded-xl border bg-muted/30 p-4"
>
{related.categories.length > 0 && (
<div className="mb-2 flex flex-wrap gap-1">
{related.categories.slice(0, 2).map((cat) => (
<Badge
key={cat}
variant="secondary"
className="text-xs uppercase"
>
{cat}
</Badge>
))}
</div>
)}
<Link href={`/blog/${related.slug}`} className="group">
<h3 className="font-semibold leading-tight group-hover:text-primary transition-colors line-clamp-2">
{related.title}
</h3>
</Link>
<p className="mt-1 text-sm text-muted-foreground line-clamp-2">
{related.excerpt}
</p>
<p className="mt-1 text-xs text-muted-foreground flex items-center gap-1">
<Eye className="h-3 w-3" /> {related.views.toLocaleString()}
</p>
</article>
))}
</div>
) : (
<p className="text-sm text-muted-foreground">
No related posts yet.
</p>
)}
</section>
{/* Sidebar */}
<aside className="space-y-4">
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base flex items-center gap-2">
<TrendingUp className="h-4 w-4" /> Popular Posts
</CardTitle>
</CardHeader>
<CardContent className="space-y-2">
{popularPosts.map((p) => (
<Link
key={p.slug}
href={`/blog/${p.slug}`}
className="flex items-center justify-between rounded-lg border px-3 py-2 text-sm font-medium hover:bg-muted transition-colors"
>
<span className="line-clamp-1 mr-2">{p.title}</span>
<span className="text-muted-foreground shrink-0 flex items-center gap-1">
<Eye className="h-3 w-3" />
{p.views.toLocaleString()}
</span>
</Link>
))}
</CardContent>
</Card>
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base">Tags</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-wrap gap-2">
{topTags.map((tag) => (
<Link
key={tag.name}
href={`/?tags=${encodeURIComponent(tag.name)}`}
>
<Badge
variant="outline"
className="cursor-pointer hover:bg-muted transition-colors"
>
#{tag.name}
</Badge>
</Link>
))}
</div>
</CardContent>
</Card>
</aside>
</div>
</div>
);
}

View File

@@ -0,0 +1,13 @@
"use client";
import { useEffect } from "react";
import { clientFetch } from "@/lib/api";
export function ViewTracker({ slug }: { slug: string }) {
useEffect(() => {
clientFetch(`/blog-posts/public/${slug}/view`, { method: "POST" }).catch(
() => {}
);
}, [slug]);
return null;
}

View File

@@ -0,0 +1,200 @@
"use client";
import { useState } from "react";
import { clientFetch } from "@/lib/api";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Loader2, PlusCircle } from "lucide-react";
import { PostStatus, ContentFormat, UserRole } from "@/lib/types";
interface Props {
userRole: UserRole;
onCreated: () => void;
}
export function CreatePostForm({ userRole, onCreated }: Props) {
const [loading, setLoading] = useState(false);
const [status, setStatus] = useState<PostStatus>(PostStatus.DRAFT);
const [contentFormat, setContentFormat] = useState<ContentFormat>(
ContentFormat.MARKDOWN
);
const [isFeatured, setIsFeatured] = useState("false");
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const fd = new FormData(e.currentTarget);
const body = {
title: fd.get("title"),
slug: fd.get("slug") || undefined,
excerpt: fd.get("excerpt") || undefined,
content: fd.get("content"),
contentFormat,
status: userRole === UserRole.ADMIN ? status : PostStatus.DRAFT,
isFeatured: isFeatured === "true",
categories: fd.get("categories") || undefined,
tags: fd.get("tags") || undefined,
featuredImageUrl: fd.get("featuredImageUrl") || undefined,
featuredImageAlt: fd.get("featuredImageAlt") || undefined,
};
setLoading(true);
try {
await clientFetch("/blog-posts", {
method: "POST",
body: JSON.stringify(body),
});
toast.success("Post created!");
(e.target as HTMLFormElement).reset();
onCreated();
} catch (err: unknown) {
toast.error(err instanceof Error ? err.message : "Failed to create post");
} finally {
setLoading(false);
}
};
return (
<form onSubmit={handleSubmit} className="space-y-4 rounded-xl border bg-muted/30 p-4">
<div className="flex items-center justify-between">
<h3 className="font-semibold flex items-center gap-2">
<PlusCircle className="h-4 w-4" /> Create New Post
</h3>
{userRole !== UserRole.ADMIN && (
<span className="text-xs text-muted-foreground border rounded-full px-2 py-0.5">
Status forced to Draft (Manager)
</span>
)}
</div>
<div className="grid gap-3 sm:grid-cols-2">
<div className="space-y-1">
<Label htmlFor="cp-title">Title *</Label>
<Input id="cp-title" name="title" placeholder="Post title" required />
</div>
<div className="space-y-1">
<Label htmlFor="cp-slug">Slug (optional)</Label>
<Input id="cp-slug" name="slug" placeholder="custom-slug" />
</div>
</div>
<div className="space-y-1">
<Label htmlFor="cp-excerpt">Excerpt</Label>
<Textarea
id="cp-excerpt"
name="excerpt"
placeholder="Short description…"
rows={2}
/>
</div>
<div className="space-y-1">
<Label htmlFor="cp-content">Content *</Label>
<Textarea
id="cp-content"
name="content"
placeholder="Write your post content…"
rows={8}
required
/>
</div>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
<div className="space-y-1">
<Label>Format</Label>
<Select
value={contentFormat}
onValueChange={(v) => setContentFormat(v as ContentFormat)}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={ContentFormat.MARKDOWN}>Markdown</SelectItem>
<SelectItem value={ContentFormat.HTML}>HTML</SelectItem>
</SelectContent>
</Select>
</div>
{userRole === UserRole.ADMIN && (
<>
<div className="space-y-1">
<Label>Status</Label>
<Select
value={status}
onValueChange={(v) => setStatus(v as PostStatus)}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={PostStatus.DRAFT}>Draft</SelectItem>
<SelectItem value={PostStatus.PUBLISHED}>Published</SelectItem>
<SelectItem value={PostStatus.ARCHIVED}>Archived</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label>Featured</Label>
<Select value={isFeatured} onValueChange={setIsFeatured}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="false">Not featured</SelectItem>
<SelectItem value="true">Featured</SelectItem>
</SelectContent>
</Select>
</div>
</>
)}
</div>
<div className="grid gap-3 sm:grid-cols-2">
<div className="space-y-1">
<Label htmlFor="cp-categories">Categories (comma separated)</Label>
<Input
id="cp-categories"
name="categories"
placeholder="backend,api"
/>
</div>
<div className="space-y-1">
<Label htmlFor="cp-tags">Tags (comma separated)</Label>
<Input id="cp-tags" name="tags" placeholder="rest,pagination" />
</div>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<div className="space-y-1">
<Label htmlFor="cp-imgurl">Featured Image URL</Label>
<Input
id="cp-imgurl"
name="featuredImageUrl"
placeholder="https://…"
/>
</div>
<div className="space-y-1">
<Label htmlFor="cp-imgalt">Image Alt Text</Label>
<Input id="cp-imgalt" name="featuredImageAlt" placeholder="Alt text" />
</div>
</div>
<div className="flex justify-end">
<Button type="submit" disabled={loading}>
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Create Post
</Button>
</div>
</form>
);
}

View File

@@ -0,0 +1,293 @@
"use client";
import { useState, useCallback } from "react";
import { clientFetch } from "@/lib/api";
import { toast } from "sonner";
import { BlogPost, PostStatus, ContentFormat, UserRole } from "@/lib/types";
import { CreatePostForm } from "./create-post-form";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Eye, Loader2, Pencil, Trash2, X, Check, ExternalLink } from "lucide-react";
import Link from "next/link";
interface Props {
initialPosts: BlogPost[];
userRole: UserRole;
}
export function PostsTable({ initialPosts, userRole }: Props) {
const [posts, setPosts] = useState<BlogPost[]>(initialPosts);
const [editingId, setEditingId] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const refreshPosts = useCallback(async () => {
try {
const data = await clientFetch<{ posts: BlogPost[]; total: number }>(
"/blog-posts?pageSize=50"
);
setPosts(data.posts);
} catch {
/* ignore */
}
}, []);
const handleDelete = async (id: string) => {
setLoading(true);
try {
await clientFetch(`/blog-posts/${id}`, { method: "DELETE" });
toast.success("Post deleted.");
setPosts((prev) => prev.filter((p) => p.id !== id));
} catch (err: unknown) {
toast.error(err instanceof Error ? err.message : "Delete failed");
} finally {
setLoading(false);
}
};
const handleUpdate = async (
e: React.FormEvent<HTMLFormElement>,
id: string
) => {
e.preventDefault();
const fd = new FormData(e.currentTarget);
const body: Record<string, unknown> = {
title: fd.get("title"),
slug: fd.get("slug") || undefined,
excerpt: fd.get("excerpt") || undefined,
content: fd.get("content"),
contentFormat: fd.get("contentFormat"),
status: fd.get("status"),
isFeatured: fd.get("isFeatured") === "true",
categories: fd.get("categories") || undefined,
tags: fd.get("tags") || undefined,
featuredImageUrl: fd.get("featuredImageUrl") || undefined,
featuredImageAlt: fd.get("featuredImageAlt") || undefined,
};
setLoading(true);
try {
await clientFetch(`/blog-posts/${id}`, {
method: "PATCH",
body: JSON.stringify(body),
});
toast.success("Post updated!");
setEditingId(null);
await refreshPosts();
} catch (err: unknown) {
toast.error(err instanceof Error ? err.message : "Update failed");
} finally {
setLoading(false);
}
};
const statusColor: Record<PostStatus, string> = {
[PostStatus.PUBLISHED]: "bg-emerald-100 text-emerald-800 border-emerald-200",
[PostStatus.DRAFT]: "bg-zinc-100 text-zinc-700 border-zinc-200",
[PostStatus.ARCHIVED]: "bg-amber-100 text-amber-800 border-amber-200",
};
return (
<div className="space-y-4">
{/* Create form for ADMIN/MANAGER */}
{(userRole === UserRole.ADMIN || userRole === UserRole.MANAGER) && (
<CreatePostForm userRole={userRole} onCreated={refreshPosts} />
)}
{/* Posts list */}
{posts.length === 0 ? (
<div className="rounded-xl border border-dashed p-8 text-center text-sm text-muted-foreground">
No posts yet.
</div>
) : (
<div className="space-y-3">
{posts.map((post) => (
<article
key={post.id}
className="rounded-xl border bg-card p-4 shadow-sm"
>
{editingId === post.id && userRole === UserRole.ADMIN ? (
/* ── Edit form ─────────────────────────────────────────── */
<form
onSubmit={(e) => handleUpdate(e, post.id)}
className="space-y-3"
>
<div className="flex justify-between items-center">
<span className="font-semibold text-sm">Editing post</span>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => setEditingId(null)}
>
<X className="h-4 w-4" />
</Button>
</div>
<div className="grid gap-2 sm:grid-cols-2">
<Input name="title" defaultValue={post.title} required placeholder="Title" />
<Input name="slug" defaultValue={post.slug} placeholder="Slug" />
</div>
<Textarea name="excerpt" defaultValue={post.excerpt} placeholder="Excerpt" rows={2} />
<Textarea name="content" defaultValue={post.content} placeholder="Content" rows={6} required />
<div className="grid gap-2 sm:grid-cols-3">
<Select name="contentFormat" defaultValue={post.contentFormat}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value={ContentFormat.MARKDOWN}>Markdown</SelectItem>
<SelectItem value={ContentFormat.HTML}>HTML</SelectItem>
</SelectContent>
</Select>
<Select name="status" defaultValue={post.status}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value={PostStatus.DRAFT}>Draft</SelectItem>
<SelectItem value={PostStatus.PUBLISHED}>Published</SelectItem>
<SelectItem value={PostStatus.ARCHIVED}>Archived</SelectItem>
</SelectContent>
</Select>
<Select name="isFeatured" defaultValue={String(post.isFeatured)}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="false">Not featured</SelectItem>
<SelectItem value="true">Featured</SelectItem>
</SelectContent>
</Select>
</div>
<div className="grid gap-2 sm:grid-cols-2">
<Input name="categories" defaultValue={post.categories.join(",")} placeholder="Categories" />
<Input name="tags" defaultValue={post.tags.join(",")} placeholder="Tags" />
</div>
<div className="grid gap-2 sm:grid-cols-2">
<Input name="featuredImageUrl" defaultValue={post.featuredImageUrl || ""} placeholder="Image URL" />
<Input name="featuredImageAlt" defaultValue={post.featuredImageAlt || ""} placeholder="Image Alt" />
</div>
<div className="flex gap-2 justify-end">
<Button type="button" variant="ghost" onClick={() => setEditingId(null)}>
Cancel
</Button>
<Button type="submit" disabled={loading}>
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
<Check className="mr-1 h-4 w-4" /> Save
</Button>
</div>
</form>
) : (
/* ── Post card view ─────────────────────────────────────── */
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="space-y-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<Link
href={`/blog/${post.slug}`}
className="font-semibold hover:text-primary transition-colors"
target="_blank"
>
{post.title}
<ExternalLink className="inline-block ml-1 h-3 w-3" />
</Link>
</div>
<p className="text-xs text-muted-foreground">
/{post.slug}
</p>
<div className="flex flex-wrap gap-1.5 pt-1">
<span className={`inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium ${statusColor[post.status]}`}>
{post.status}
</span>
<span className="inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs text-muted-foreground">
<Eye className="h-3 w-3" /> {post.views.toLocaleString()}
</span>
{post.isFeatured && (
<Badge variant="secondary" className="text-xs"> featured</Badge>
)}
{post.author && (
<span className="text-xs text-muted-foreground">
by {post.author.name || post.author.email}
</span>
)}
</div>
{post.excerpt && (
<p className="mt-1 text-sm text-muted-foreground line-clamp-2">
{post.excerpt}
</p>
)}
<div className="flex flex-wrap gap-1 mt-1">
{post.categories.map((c) => (
<Badge key={c} variant="secondary" className="text-xs">{c}</Badge>
))}
{post.tags.map((t) => (
<Badge key={t} variant="outline" className="text-xs">#{t}</Badge>
))}
</div>
</div>
{/* Actions */}
<div className="flex gap-2 shrink-0">
{userRole === UserRole.ADMIN && (
<>
<Button
variant="outline"
size="sm"
onClick={() => setEditingId(post.id)}
>
<Pencil className="h-4 w-4" />
</Button>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="outline" size="sm" className="text-destructive border-destructive/30 hover:bg-destructive/5">
<Trash2 className="h-4 w-4" />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete post?</AlertDialogTitle>
<AlertDialogDescription>
&quot;{post.title}&quot; will be permanently deleted.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={() => handleDelete(post.id)}
disabled={loading}
>
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
)}
</div>
</div>
)}
</article>
))}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,191 @@
"use client";
import { useState } from "react";
import { clientFetch } from "@/lib/api";
import { toast } from "sonner";
import { User, UserRole } from "@/lib/types";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Loader2, Pencil, X, Check } from "lucide-react";
interface Props {
initialUsers: User[];
}
const roleColor: Record<UserRole, string> = {
[UserRole.ADMIN]: "bg-red-100 text-red-800 border-red-200",
[UserRole.MANAGER]: "bg-amber-100 text-amber-800 border-amber-200",
[UserRole.MEMBER]: "bg-blue-100 text-blue-700 border-blue-200",
};
export function UsersTable({ initialUsers }: Props) {
const [users, setUsers] = useState<User[]>(initialUsers);
const [editingId, setEditingId] = useState<string | null>(null);
const [editName, setEditName] = useState("");
const [editRole, setEditRole] = useState<UserRole>(UserRole.MEMBER);
const [loading, setLoading] = useState(false);
const startEdit = (user: User) => {
setEditingId(user.id);
setEditName(user.name || "");
setEditRole(user.role);
};
const cancelEdit = () => {
setEditingId(null);
};
const handleUpdate = async (user: User) => {
setLoading(true);
try {
// Update name if changed
let updated = user;
if (editName !== (user.name || "")) {
const res = await clientFetch<{ success: boolean; user: User }>(
`/users/${user.id}`,
{
method: "PATCH",
body: JSON.stringify({ name: editName || undefined }),
}
);
updated = res.user;
}
// Update role if changed
if (editRole !== user.role) {
const res = await clientFetch<{ success: boolean; user: User }>(
`/users/${user.id}/role`,
{
method: "PATCH",
body: JSON.stringify({ role: editRole }),
}
);
updated = res.user;
}
toast.success("User updated.");
setUsers((prev) => prev.map((u) => (u.id === user.id ? updated : u)));
setEditingId(null);
} catch (err: unknown) {
toast.error(err instanceof Error ? err.message : "Update failed");
} finally {
setLoading(false);
}
};
return (
<div className="space-y-2">
{users.length === 0 ? (
<div className="rounded-xl border border-dashed p-8 text-center text-sm text-muted-foreground">
No users found.
</div>
) : (
users.map((user) => (
<div
key={user.id}
className="rounded-xl border bg-card p-4 shadow-sm flex flex-wrap items-center gap-3"
>
{editingId === user.id ? (
/* ── Edit row ─────────────────────────────────────────────── */
<div className="flex flex-1 flex-wrap items-center gap-2">
<Input
className="h-8 w-40"
placeholder="Name"
value={editName}
onChange={(e) => setEditName(e.target.value)}
/>
<Select
value={editRole}
onValueChange={(v) => setEditRole(v as UserRole)}
>
<SelectTrigger className="h-8 w-32">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={UserRole.MEMBER}>MEMBER</SelectItem>
<SelectItem value={UserRole.MANAGER}>MANAGER</SelectItem>
<SelectItem value={UserRole.ADMIN}>ADMIN</SelectItem>
</SelectContent>
</Select>
<div className="flex gap-1">
<Button
size="sm"
onClick={() => handleUpdate(user)}
disabled={loading}
>
{loading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Check className="h-4 w-4" />
)}
</Button>
<Button size="sm" variant="ghost" onClick={cancelEdit}>
<X className="h-4 w-4" />
</Button>
</div>
</div>
) : (
/* ── View row ─────────────────────────────────────────────── */
<>
<div className="flex flex-1 flex-wrap items-center gap-3 min-w-0">
{/* Avatar placeholder */}
<div className="h-8 w-8 shrink-0 rounded-full bg-muted flex items-center justify-center text-xs font-semibold uppercase">
{(user.name || user.email).charAt(0)}
</div>
<div className="min-w-0 flex-1">
<p className="text-sm font-medium truncate">
{user.name ?? (
<span className="italic text-muted-foreground">
No name
</span>
)}
</p>
<p className="text-xs text-muted-foreground truncate">
{user.email}
</p>
</div>
<span
className={`inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium ${roleColor[user.role]}`}
>
{user.role}
</span>
{!user.isActive && (
<Badge
variant="outline"
className="text-xs text-muted-foreground"
>
Inactive
</Badge>
)}
<p className="text-xs text-muted-foreground shrink-0">
Joined {new Date(user.createdAt).toLocaleDateString()}
</p>
</div>
{/* Actions */}
<Button
variant="outline"
size="sm"
onClick={() => startEdit(user)}
>
<Pencil className="h-4 w-4" />
</Button>
</>
)}
</div>
))
)}
</div>
);
}

View File

@@ -0,0 +1,204 @@
import { redirect } from "next/navigation";
import { cookies } from "next/headers";
import { apiFetch, ApiError } from "@/lib/api";
import { BlogPost, User, UserRole, CurrentUser } from "@/lib/types";
import { PostsTable } from "./components/posts-table";
import { UsersTable } from "./components/users-table";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { LayoutDashboard, Users, FileText, ShieldAlert } from "lucide-react";
// ── Decode JWT payload without verification (public payload info only) ─────────
function decodeJwtPayload(token: string): CurrentUser | null {
try {
const base64Payload = token.split(".")[1];
const decoded = Buffer.from(base64Payload, "base64url").toString("utf-8");
return JSON.parse(decoded) as CurrentUser;
} catch {
return null;
}
}
const roleColor: Record<UserRole, string> = {
[UserRole.ADMIN]: "bg-red-100 text-red-800 border-red-200",
[UserRole.MANAGER]: "bg-amber-100 text-amber-800 border-amber-200",
[UserRole.MEMBER]: "bg-blue-100 text-blue-700 border-blue-200",
};
export default async function DashboardPage() {
// ── Auth check ─────────────────────────────────────────────────────────────
const cookieStore = await cookies();
const accessToken = cookieStore.get("accessToken")?.value;
if (!accessToken) {
redirect("/auth");
}
const currentUser = decodeJwtPayload(accessToken);
if (!currentUser) {
redirect("/auth");
}
// ── Fetch posts ────────────────────────────────────────────────────────────
let posts: BlogPost[] = [];
try {
const data = await apiFetch<{ posts: BlogPost[]; total: number }>(
"/blog-posts?pageSize=50"
);
posts = data.posts;
} catch (err) {
if (err instanceof ApiError && err.status === 401) {
redirect("/auth");
}
// Non-fatal — show empty list
}
// ── Fetch users (ADMIN only) ───────────────────────────────────────────────
let users: User[] = [];
if (currentUser.role === UserRole.ADMIN) {
try {
const data = await apiFetch<{ users: User[]; total: number }>(
"/users?pageSize=50"
);
users = data.users;
} catch {
// Non-fatal — show empty list
}
}
const displayName = currentUser.name || currentUser.email;
return (
<div className="space-y-6">
{/* ── Header ──────────────────────────────────────────────────────────── */}
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-3">
<LayoutDashboard className="h-6 w-6 text-muted-foreground" />
<div>
<h1 className="text-2xl font-bold">Dashboard</h1>
<p className="text-sm text-muted-foreground">
Manage your blog content and users
</p>
</div>
</div>
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">{displayName}</span>
<span
className={`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium ${roleColor[currentUser.role as UserRole]}`}
>
{currentUser.role}
</span>
</div>
</div>
{/* ── Stats strip ─────────────────────────────────────────────────────── */}
<div className="grid gap-4 sm:grid-cols-3">
<Card>
<CardContent className="pt-5">
<div className="flex items-center gap-3">
<FileText className="h-8 w-8 text-muted-foreground/60" />
<div>
<p className="text-2xl font-bold">{posts.length}</p>
<p className="text-xs text-muted-foreground">Total posts</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-5">
<div className="flex items-center gap-3">
<FileText className="h-8 w-8 text-emerald-500/60" />
<div>
<p className="text-2xl font-bold">
{posts.filter((p) => p.status === "published").length}
</p>
<p className="text-xs text-muted-foreground">Published</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-5">
<div className="flex items-center gap-3">
<FileText className="h-8 w-8 text-zinc-400/60" />
<div>
<p className="text-2xl font-bold">
{posts.filter((p) => p.status === "draft").length}
</p>
<p className="text-xs text-muted-foreground">Drafts</p>
</div>
</div>
</CardContent>
</Card>
</div>
<Separator />
{/* ── Posts section ───────────────────────────────────────────────────── */}
<section className="space-y-4">
<div className="flex items-center gap-2">
<FileText className="h-5 w-5 text-muted-foreground" />
<h2 className="text-xl font-semibold">Posts</h2>
<Badge variant="secondary" className="text-xs">
{posts.length}
</Badge>
</div>
<PostsTable initialPosts={posts} userRole={currentUser.role as UserRole} />
</section>
{/* ── Users section (ADMIN only) ───────────────────────────────────────── */}
{currentUser.role === UserRole.ADMIN && (
<>
<Separator />
<section className="space-y-4">
<div className="flex items-center gap-2">
<Users className="h-5 w-5 text-muted-foreground" />
<h2 className="text-xl font-semibold">Users</h2>
<Badge variant="secondary" className="text-xs">
{users.length}
</Badge>
</div>
{users.length === 0 ? (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<ShieldAlert className="h-4 w-4" /> No users loaded
</CardTitle>
<CardDescription>
Unable to fetch user list. Check your backend connection.
</CardDescription>
</CardHeader>
</Card>
) : (
<UsersTable initialUsers={users} />
)}
</section>
</>
)}
{/* ── Member notice ───────────────────────────────────────────────────── */}
{currentUser.role === UserRole.MEMBER && (
<Card className="border-dashed">
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<ShieldAlert className="h-4 w-4 text-muted-foreground" />
Read-only access
</CardTitle>
<CardDescription>
You have the <strong>MEMBER</strong> role. You can view posts but
cannot create, edit, or delete them. Contact an admin to upgrade
your role.
</CardDescription>
</CardHeader>
</Card>
)}
</div>
);
}

View File

@@ -1,6 +1,7 @@
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@plugin "@tailwindcss/typography";
@custom-variant dark (&:is(.dark *));

View File

@@ -1,6 +1,9 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { AuthProvider } from "@/lib/auth";
import { Navbar } from "@/components/navbar";
import { Toaster } from "@/components/ui/sonner";
const geistSans = Geist({
variable: "--font-geist-sans",
@@ -13,8 +16,12 @@ const geistMono = Geist_Mono({
});
export const metadata: Metadata = {
title: "Duc Binh's Blog",
description: "Fastify + Nextjs + Postgres",
title: {
default: "Duc Binh Blog",
template: "%s | Duc Binh Blog",
},
description:
"Practical engineering stories — fast backend patterns, frontend craft, and product lessons.",
};
export default function RootLayout({
@@ -25,9 +32,15 @@ export default function RootLayout({
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
className={`${geistSans.variable} ${geistMono.variable} antialiased min-h-screen bg-background`}
>
{children}
<AuthProvider>
<Navbar />
<main className="mx-auto max-w-7xl px-4 py-6 sm:px-6 lg:px-8">
{children}
</main>
<Toaster position="top-right" richColors />
</AuthProvider>
</body>
</html>
);

View File

@@ -1,12 +1,332 @@
import { Suspense } from "react";
import Link from "next/link";
import Image from "next/image";
import { apiFetch } from "@/lib/api";
import { BlogPost, PaginatedResult, TagCloudItem } from "@/lib/types";
import { PostCard } from "@/components/post-card";
import { Pagination } from "@/components/pagination";
import { PostFilterForm } from "@/components/post-filter-form";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Eye, Star, TrendingUp } from "lucide-react";
interface HomeSearchParams {
q?: string;
tags?: string;
category?: string;
sort?: string;
page?: string;
pageSize?: string;
}
async function getFeatured(): Promise<BlogPost[]> {
try {
return await apiFetch<BlogPost[]>("/blog-posts/public/featured");
} catch {
return [];
}
}
async function getPosts(
params: HomeSearchParams
): Promise<PaginatedResult<BlogPost>> {
const qs = new URLSearchParams();
if (params.q) qs.set("q", params.q);
if (params.tags) qs.set("tags", params.tags);
if (params.category) qs.set("category", params.category);
if (params.sort) qs.set("sort", params.sort);
qs.set("page", params.page || "1");
qs.set("pageSize", params.pageSize || "9");
try {
return await apiFetch<PaginatedResult<BlogPost>>(
`/blog-posts/public?${qs.toString()}`
);
} catch {
return { items: [], total: 0, page: 1, pageSize: 9, totalPages: 0 };
}
}
async function getAllPostsForCloud(): Promise<BlogPost[]> {
try {
const result = await apiFetch<PaginatedResult<BlogPost>>(
"/blog-posts/public?pageSize=100"
);
return result.items;
} catch {
return [];
}
}
function buildTagCloud(posts: BlogPost[]): TagCloudItem[] {
const counts: Record<string, number> = {};
for (const post of posts) {
for (const tag of post.tags || []) {
const t = tag.trim();
if (t) counts[t] = (counts[t] || 0) + 1;
}
}
return Object.entries(counts)
.map(([name, count]) => ({ name, count }))
.sort((a, b) => b.count - a.count)
.slice(0, 20);
}
function buildCategoryCloud(posts: BlogPost[]): TagCloudItem[] {
const counts: Record<string, number> = {};
for (const post of posts) {
for (const cat of post.categories || []) {
const c = cat.trim();
if (c) counts[c] = (counts[c] || 0) + 1;
}
}
return Object.entries(counts)
.map(([name, count]) => ({ name, count }))
.sort((a, b) => b.count - a.count)
.slice(0, 10);
}
export default async function HomePage({
searchParams,
}: {
searchParams: Promise<HomeSearchParams>;
}) {
const params = await searchParams;
const [featured, postsResult, allPosts, popularResult] = await Promise.all([
getFeatured(),
getPosts(params),
getAllPostsForCloud(),
apiFetch<PaginatedResult<BlogPost>>(
"/blog-posts/public?sort=most_viewed&pageSize=5"
).catch(() => ({ items: [] as BlogPost[] })),
]);
const topTags = buildTagCloud(allPosts);
const topCategories = buildCategoryCloud(allPosts);
const popularPosts = (popularResult as PaginatedResult<BlogPost>).items || [];
const { items: posts, page, totalPages, total } = postsResult;
export default function Home() {
return (
<>
<div>
<Button>Blank page with nextjs + Shadcn ui</Button>
<div className="space-y-6">
{/* ── Hero ──────────────────────────────────────────────────────────── */}
<section className="rounded-2xl border bg-gradient-to-r from-background via-muted/30 to-background p-5">
<div className="flex flex-wrap items-start justify-between gap-4">
<div className="max-w-2xl">
<h1 className="text-3xl font-bold tracking-tight">
Practical Engineering Stories
</h1>
<p className="mt-2 text-muted-foreground">
Fast backend patterns, frontend craft, and product lessons from
shipping real systems.
</p>
</div>
<div className="flex flex-wrap gap-2">
{topCategories.slice(0, 6).map((c) => (
<Link
key={c.name}
href={`/?category=${encodeURIComponent(c.name)}`}
>
<Badge
variant="secondary"
className="cursor-pointer hover:bg-secondary/80"
>
{c.name} ({c.count})
</Badge>
</Link>
))}
</div>
</div>
</section>
{/* ── Featured posts ─────────────────────────────────────────────────── */}
{featured.length > 0 && (
<section className="rounded-2xl border bg-gradient-to-r from-background via-sky-50 to-emerald-50 dark:via-sky-950/20 dark:to-emerald-950/20 p-5">
<div className="flex items-center gap-2 mb-4">
<Star className="h-4 w-4 text-amber-500 fill-amber-500" />
<h2 className="font-semibold text-lg">Featured</h2>
</div>
<div className="grid gap-4 lg:grid-cols-[1.5fr_1fr]">
{/* Primary featured */}
<article className="rounded-xl border bg-background/80 p-5">
<Badge className="mb-3 bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200 border-amber-200">
Featured pick
</Badge>
{featured[0].featuredImageUrl && (
<Link href={`/blog/${featured[0].slug}`} className="block mb-4">
<div className="relative h-52 w-full overflow-hidden rounded-lg">
<Image
src={featured[0].featuredImageUrl}
alt={featured[0].featuredImageAlt || featured[0].title}
fill
className="object-cover"
sizes="(max-width: 1024px) 100vw, 60vw"
priority
/>
</div>
</Link>
)}
<Link href={`/blog/${featured[0].slug}`} className="group">
<h2 className="text-2xl font-bold leading-tight group-hover:text-primary transition-colors">
{featured[0].title}
</h2>
</Link>
<p className="mt-2 text-muted-foreground">
{featured[0].excerpt}
</p>
<p className="mt-2 text-sm text-muted-foreground flex items-center gap-1">
<Eye className="h-3 w-3" />
{featured[0].views.toLocaleString()} views
</p>
</article>
{/* Secondary featured */}
<div className="grid gap-3">
{featured.slice(1).map((post) => (
<article
key={post.id}
className="rounded-xl border bg-background/80 p-4 flex gap-3"
>
{post.featuredImageUrl && (
<div className="relative h-16 w-16 shrink-0 overflow-hidden rounded-lg">
<Image
src={post.featuredImageUrl}
alt={post.featuredImageAlt || post.title}
fill
className="object-cover"
sizes="64px"
/>
</div>
)}
<div className="min-w-0">
<Link href={`/blog/${post.slug}`} className="group">
<h3 className="font-semibold leading-tight group-hover:text-primary transition-colors line-clamp-2">
{post.title}
</h3>
</Link>
<p className="mt-1 text-sm text-muted-foreground line-clamp-2">
{post.excerpt}
</p>
</div>
</article>
))}
</div>
</div>
</section>
)}
{/* ── Main content + sidebar ─────────────────────────────────────────── */}
<div className="grid gap-6 lg:grid-cols-[1fr_20rem]">
<div className="space-y-4">
{/* Filter form */}
<Suspense fallback={null}>
<PostFilterForm
topCategories={topCategories}
currentQ={params.q || ""}
currentCategory={params.category || ""}
currentSort={params.sort || "newest"}
currentTags={params.tags || ""}
/>
</Suspense>
{/* Post grid */}
{posts.length === 0 ? (
<div className="rounded-xl border bg-muted/30 p-8 text-center">
<p className="text-muted-foreground">
No posts found for this filter.
</p>
<Button asChild variant="link" className="mt-2">
<Link href="/">Clear filters</Link>
</Button>
</div>
) : (
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
{posts.map((post) => (
<PostCard key={post.id} post={post} />
))}
</div>
)}
{/* Pagination */}
<Suspense fallback={null}>
<Pagination page={page} totalPages={totalPages} total={total} />
</Suspense>
</div>
{/* Sidebar */}
<aside className="space-y-4">
{/* Popular Posts */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base flex items-center gap-2">
<TrendingUp className="h-4 w-4" /> Popular Posts
</CardTitle>
</CardHeader>
<CardContent className="space-y-2">
{popularPosts.map((post) => (
<Link
key={post.slug}
href={`/blog/${post.slug}`}
className="flex items-center justify-between rounded-lg border px-3 py-2 text-sm font-medium hover:bg-muted transition-colors"
>
<span className="line-clamp-1 mr-2">{post.title}</span>
<span className="text-muted-foreground shrink-0 flex items-center gap-1">
<Eye className="h-3 w-3" />
{post.views.toLocaleString()}
</span>
</Link>
))}
</CardContent>
</Card>
{/* Newsletter */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base">Newsletter</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground mb-3">
One practical note every Friday.
</p>
<div className="flex flex-col gap-2">
<Input type="email" placeholder="you@example.com" />
<Button className="w-full">Join</Button>
</div>
</CardContent>
</Card>
{/* Tag Cloud */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base">Tag Cloud</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-wrap gap-2">
{topTags.map((tag) => (
<Link
key={tag.name}
href={`/?tags=${encodeURIComponent(tag.name)}`}
>
<Badge
variant="outline"
className="cursor-pointer hover:bg-muted transition-colors"
>
#{tag.name} ({tag.count})
</Badge>
</Link>
))}
</div>
</CardContent>
</Card>
<Separator />
<p className="text-xs text-center text-muted-foreground">
Built with NestJS + Next.js 16 + shadcn/ui
</p>
</aside>
</div>
</div>
</>
);
}

View File

@@ -0,0 +1,74 @@
"use client";
import Link from "next/link";
import { useAuth } from "@/lib/auth";
import { Button } from "@/components/ui/button";
import { BookOpen, LayoutDashboard, LogOut, LogIn } from "lucide-react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
export function Navbar() {
const { currentUser, logout } = useAuth();
const router = useRouter();
const handleLogout = async () => {
await logout();
toast.success("Logged out successfully");
router.push("/");
router.refresh();
};
return (
<header className="sticky top-0 z-50 border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<div className="mx-auto flex h-14 max-w-7xl items-center justify-between px-4 sm:px-6 lg:px-8">
{/* Logo */}
<Link
href="/"
className="flex items-center gap-2 font-semibold text-foreground hover:text-primary transition-colors"
>
<span className="flex h-8 w-8 items-center justify-center rounded-full bg-primary text-xs font-bold text-primary-foreground">
DB
</span>
<span className="hidden sm:inline">Duc Binh Blog</span>
</Link>
{/* Nav */}
<nav className="flex items-center gap-2">
<Button variant="ghost" size="sm" asChild>
<Link href="/">
<BookOpen className="h-4 w-4 mr-1" />
<span className="hidden sm:inline">Home</span>
</Link>
</Button>
{currentUser ? (
<>
<Button variant="ghost" size="sm" asChild>
<Link href="/dashboard">
<LayoutDashboard className="h-4 w-4 mr-1" />
<span className="hidden sm:inline">Dashboard</span>
</Link>
</Button>
<Button
variant="ghost"
size="sm"
onClick={handleLogout}
className="text-destructive hover:text-destructive"
>
<LogOut className="h-4 w-4 mr-1" />
<span className="hidden sm:inline">Logout</span>
</Button>
</>
) : (
<Button variant="ghost" size="sm" asChild>
<Link href="/auth">
<LogIn className="h-4 w-4 mr-1" />
<span className="hidden sm:inline">Sign In</span>
</Link>
</Button>
)}
</nav>
</div>
</header>
);
}

View File

@@ -0,0 +1,72 @@
"use client";
import { useRouter, useSearchParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { ChevronLeft, ChevronRight } from "lucide-react";
interface PaginationProps {
page: number;
totalPages: number;
total: number;
}
export function Pagination({ page, totalPages, total }: PaginationProps) {
const router = useRouter();
const searchParams = useSearchParams();
if (totalPages <= 1) return null;
const goToPage = (p: number) => {
const params = new URLSearchParams(searchParams.toString());
params.set("page", String(p));
router.push(`?${params.toString()}`);
};
// Show at most 5 page numbers
const getPageNumbers = () => {
const pages: number[] = [];
const start = Math.max(1, page - 2);
const end = Math.min(totalPages, start + 4);
for (let i = start; i <= end; i++) pages.push(i);
return pages;
};
return (
<div className="flex items-center justify-between gap-2 pt-4 border-t">
<p className="text-sm text-muted-foreground">
Page {page} of {totalPages} ({total} posts)
</p>
<div className="flex items-center gap-1">
<Button
variant="outline"
size="sm"
disabled={page <= 1}
onClick={() => goToPage(page - 1)}
>
<ChevronLeft className="h-4 w-4" />
</Button>
{getPageNumbers().map((p) => (
<Button
key={p}
variant={p === page ? "default" : "outline"}
size="sm"
onClick={() => goToPage(p)}
className="w-9"
>
{p}
</Button>
))}
<Button
variant="outline"
size="sm"
disabled={page >= totalPages}
onClick={() => goToPage(page + 1)}
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
);
}

View File

@@ -0,0 +1,72 @@
import Link from "next/link";
import Image from "next/image";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardFooter } from "@/components/ui/card";
import { Eye } from "lucide-react";
import { BlogPost } from "@/lib/types";
interface PostCardProps {
post: BlogPost;
}
export function PostCard({ post }: PostCardProps) {
return (
<Card className="flex flex-col overflow-hidden hover:shadow-md transition-shadow h-full">
{post.featuredImageUrl && (
<Link href={`/blog/${post.slug}`} className="block overflow-hidden">
<div className="relative h-48 w-full">
<Image
src={post.featuredImageUrl}
alt={post.featuredImageAlt || post.title}
fill
className="object-cover transition-transform duration-300 hover:scale-[1.02]"
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
/>
</div>
</Link>
)}
<CardContent className="flex-1 pt-4 pb-2">
{post.categories.length > 0 && (
<div className="mb-2 flex flex-wrap gap-1">
{post.categories.slice(0, 3).map((cat) => (
<Badge
key={cat}
variant="secondary"
className="text-xs uppercase tracking-wide"
>
{cat}
</Badge>
))}
</div>
)}
<Link href={`/blog/${post.slug}`} className="group">
<h3 className="font-semibold leading-tight text-foreground group-hover:text-primary transition-colors line-clamp-2">
{post.title}
</h3>
</Link>
{post.excerpt && (
<p className="mt-2 text-sm text-muted-foreground line-clamp-3">
{post.excerpt}
</p>
)}
</CardContent>
<CardFooter className="pt-0 pb-4 px-6 flex flex-wrap gap-1.5 items-center justify-between">
<div className="flex flex-wrap gap-1">
{post.tags.slice(0, 3).map((tag) => (
<Badge key={tag} variant="outline" className="text-xs">
#{tag}
</Badge>
))}
</div>
<span className="flex items-center gap-1 text-xs text-muted-foreground ml-auto">
<Eye className="h-3 w-3" />
{post.views.toLocaleString()}
</span>
</CardFooter>
</Card>
);
}

View File

@@ -0,0 +1,137 @@
"use client";
import { useRouter, useSearchParams } from "next/navigation";
import { useCallback } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Search, X } from "lucide-react";
import { TagCloudItem } from "@/lib/types";
interface PostFilterFormProps {
topCategories: TagCloudItem[];
currentQ: string;
currentCategory: string;
currentSort: string;
currentTags: string;
}
export function PostFilterForm({
topCategories,
currentQ,
currentCategory,
currentSort,
currentTags,
}: PostFilterFormProps) {
const router = useRouter();
const searchParams = useSearchParams();
const updateParam = useCallback(
(updates: Record<string, string>) => {
const params = new URLSearchParams(searchParams.toString());
for (const [key, val] of Object.entries(updates)) {
if (val) {
params.set(key, val);
} else {
params.delete(key);
}
}
params.set("page", "1");
router.push(`?${params.toString()}`);
},
[router, searchParams]
);
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const fd = new FormData(e.currentTarget);
updateParam({
q: fd.get("q") as string,
tags: fd.get("tags") as string,
});
};
const clearFilters = () => {
router.push("/");
};
const hasFilters = currentQ || currentCategory || currentTags || (currentSort && currentSort !== "newest");
return (
<form
onSubmit={handleSubmit}
className="rounded-xl border bg-card p-4 shadow-sm space-y-3"
>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
{/* Search */}
<div className="sm:col-span-2 relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
name="q"
defaultValue={currentQ}
placeholder="Search posts…"
className="pl-9"
/>
</div>
{/* Category */}
<Select
defaultValue={currentCategory || "all"}
onValueChange={(val) =>
updateParam({ category: val === "all" ? "" : val })
}
>
<SelectTrigger>
<SelectValue placeholder="Category" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All categories</SelectItem>
{topCategories.map((c) => (
<SelectItem key={c.name} value={c.name}>
{c.name} ({c.count})
</SelectItem>
))}
</SelectContent>
</Select>
{/* Sort */}
<Select
defaultValue={currentSort || "newest"}
onValueChange={(val) => updateParam({ sort: val })}
>
<SelectTrigger>
<SelectValue placeholder="Sort" />
</SelectTrigger>
<SelectContent>
<SelectItem value="newest">Newest</SelectItem>
<SelectItem value="oldest">Oldest</SelectItem>
<SelectItem value="most_viewed">Most viewed</SelectItem>
<SelectItem value="featured">Featured first</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex gap-2 items-end">
<div className="flex-1">
<Input
name="tags"
defaultValue={currentTags}
placeholder="Tags (comma separated): nextjs, typescript"
/>
</div>
<Button type="submit">Apply</Button>
{hasFilters && (
<Button type="button" variant="ghost" onClick={clearFilters}>
<X className="h-4 w-4" />
</Button>
)}
</div>
</form>
);
}

View File

@@ -0,0 +1,196 @@
"use client"
import * as React from "react"
import { AlertDialog as AlertDialogPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
function AlertDialog({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
)
}
function AlertDialogPortal({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
)
}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function AlertDialogContent({
className,
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content> & {
size?: "default" | "sm"
}) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
data-size={size}
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 group/alert-dialog-content fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-lg",
className
)}
{...props}
/>
</AlertDialogPortal>
)
}
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn(
"grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-6 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]",
className
)}
{...props}
/>
)
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn(
"text-lg font-semibold sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",
className
)}
{...props}
/>
)
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function AlertDialogMedia({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-media"
className={cn(
"bg-muted mb-2 inline-flex size-16 items-center justify-center rounded-md sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-8",
className
)}
{...props}
/>
)
}
function AlertDialogAction({
className,
variant = "default",
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Action
data-slot="alert-dialog-action"
className={cn(className)}
{...props}
/>
</Button>
)
}
function AlertDialogCancel({
className,
variant = "outline",
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Cancel
data-slot="alert-dialog-cancel"
className={cn(className)}
{...props}
/>
</Button>
)
}
export {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogMedia,
AlertDialogOverlay,
AlertDialogPortal,
AlertDialogTitle,
AlertDialogTrigger,
}

95
frontend/lib/api.ts Normal file
View File

@@ -0,0 +1,95 @@
/**
* API helpers for server components (forwards cookies) and client components (credentials: include).
*/
const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
// ─── Server-side fetch (use in Server Components / Route Handlers) ─────────────
export async function apiFetch<T = unknown>(
path: string,
init?: RequestInit
): Promise<T> {
// Dynamic import so this module can also be imported in client components
// The `cookies` call only runs on the server side
let cookieHeader = "";
try {
const { cookies } = await import("next/headers");
const store = await cookies();
cookieHeader = store
.getAll()
.map((c) => `${c.name}=${c.value}`)
.join("; ");
} catch {
// We're on the client — skip cookie forwarding
}
const res = await fetch(`${API_URL}${path}`, {
...init,
cache: "no-store",
headers: {
"Content-Type": "application/json",
...(cookieHeader ? { Cookie: cookieHeader } : {}),
...(init?.headers as Record<string, string> | undefined),
},
});
if (!res.ok) {
let msg = `API error ${res.status}`;
try {
const body = await res.json();
msg = body?.error?.message || body?.message || msg;
} catch {
/* ignore */
}
throw new ApiError(msg, res.status);
}
// Some endpoints return 204 No Content
const text = await res.text();
if (!text) return undefined as T;
return JSON.parse(text) as T;
}
// ─── Client-side fetch (use in Client Components) ─────────────────────────────
export async function clientFetch<T = unknown>(
path: string,
init?: RequestInit
): Promise<T> {
const res = await fetch(`${API_URL}${path}`, {
...init,
credentials: "include",
headers: {
"Content-Type": "application/json",
...(init?.headers as Record<string, string> | undefined),
},
});
if (!res.ok) {
let msg = `API error ${res.status}`;
try {
const body = await res.json();
msg = body?.error?.message || body?.message || msg;
} catch {
/* ignore */
}
throw new ApiError(msg, res.status);
}
const text = await res.text();
if (!text) return undefined as T;
return JSON.parse(text) as T;
}
export class ApiError extends Error {
constructor(
message: string,
public status: number
) {
super(message);
this.name = "ApiError";
}
}
export { API_URL };

136
frontend/lib/auth.tsx Normal file
View File

@@ -0,0 +1,136 @@
"use client";
import {
createContext,
useCallback,
useContext,
useEffect,
useState,
} from "react";
import { clientFetch, ApiError } from "./api";
import { CurrentUser, UserRole } from "./types";
interface AuthContextValue {
currentUser: CurrentUser | null;
loading: boolean;
login: (email: string, password: string) => Promise<void>;
register: (name: string, email: string, password: string) => Promise<void>;
logout: () => Promise<void>;
refresh: () => Promise<void>;
}
const AuthContext = createContext<AuthContextValue | null>(null);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [currentUser, setCurrentUser] = useState<CurrentUser | null>(null);
const [loading, setLoading] = useState(true);
/** Decode the JWT access token stored in the browser cookie (non-httpOnly portion).
* Since accessToken is httpOnly, we detect auth state by calling a lightweight
* authenticated endpoint. If it returns 401 → not logged in. */
const refresh = useCallback(async () => {
try {
// Call GET /blog-posts?pageSize=1 — requires auth. If cookie is valid, returns data.
// We only care about the response headers/status here, not the body.
const data = await clientFetch<{
posts?: unknown[];
total?: number;
// The JWT payload fields we need come from the cookie;
// we parse them via a lightweight /auth/me-style endpoint.
// Since we don't have /auth/me, we use the blog-posts endpoint response
// and get user info from a separate call to /users (ADMIN only) or just
// decode what we need from the refresh token.
// Simpler: call GET /blog-posts and use the response to confirm auth,
// then store minimal info from localStorage if previously set.
}>(
"/blog-posts?pageSize=1"
);
// Auth succeeded — try to restore user from sessionStorage
const cached = sessionStorage.getItem("currentUser");
if (cached) {
setCurrentUser(JSON.parse(cached));
}
} catch (err) {
if (err instanceof ApiError && err.status === 401) {
setCurrentUser(null);
sessionStorage.removeItem("currentUser");
}
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
refresh();
}, [refresh]);
const login = useCallback(async (email: string, password: string) => {
const data = await clientFetch<{
success: boolean;
user?: CurrentUser;
accessToken?: string;
}>("/auth/login", {
method: "POST",
body: JSON.stringify({ email, password }),
});
// The NestJS login returns { success, accessToken, user } for JSON clients
if (data.user) {
// Normalize role to uppercase enum
const user: CurrentUser = {
sub: data.user.sub || (data.user as unknown as { id?: string }).id || "",
email: data.user.email,
role: (data.user.role as string).toUpperCase() as UserRole,
name: data.user.name,
};
setCurrentUser(user);
sessionStorage.setItem("currentUser", JSON.stringify(user));
}
}, []);
const register = useCallback(
async (name: string, email: string, password: string) => {
const data = await clientFetch<{
success: boolean;
user?: CurrentUser;
}>("/auth/register", {
method: "POST",
body: JSON.stringify({ name, email, password }),
});
if (data.user) {
const user: CurrentUser = {
sub: data.user.sub || (data.user as unknown as { id?: string }).id || "",
email: data.user.email,
role: (data.user.role as string).toUpperCase() as UserRole,
name: data.user.name,
};
setCurrentUser(user);
sessionStorage.setItem("currentUser", JSON.stringify(user));
}
},
[]
);
const logout = useCallback(async () => {
try {
await clientFetch("/auth/logout", { method: "POST" });
} catch {
/* ignore */
}
setCurrentUser(null);
sessionStorage.removeItem("currentUser");
}, []);
return (
<AuthContext.Provider
value={{ currentUser, loading, login, register, logout, refresh }}
>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error("useAuth must be used within AuthProvider");
return ctx;
}

86
frontend/lib/types.ts Normal file
View File

@@ -0,0 +1,86 @@
export enum PostStatus {
DRAFT = "draft",
PUBLISHED = "published",
ARCHIVED = "archived",
}
export enum ContentFormat {
MARKDOWN = "markdown",
HTML = "html",
}
export enum UserRole {
ADMIN = "ADMIN",
MANAGER = "MANAGER",
MEMBER = "MEMBER",
}
export interface User {
id: string;
email: string;
name?: string;
role: UserRole;
isActive: boolean;
createdAt: string;
}
export interface FeaturedImage {
url: string;
alt: string;
}
export interface BlogPost {
id: string;
title: string;
slug: string;
status: PostStatus;
excerpt: string;
content: string;
contentFormat: ContentFormat;
authorId: string;
author?: Pick<User, "id" | "email" | "name" | "role">;
featuredImageUrl?: string;
featuredImageAlt?: string;
isFeatured: boolean;
views: number;
tags: string[];
categories: string[];
createdAt: string;
updatedAt: string;
}
export interface PaginatedResult<T> {
items: T[];
total: number;
page: number;
pageSize: number;
totalPages: number;
}
export interface TagCloudItem {
name: string;
count: number;
}
export interface CreatePostDto {
title: string;
slug?: string;
excerpt?: string;
content: string;
contentFormat?: ContentFormat;
status?: PostStatus;
featuredImageUrl?: string;
featuredImageAlt?: string;
isFeatured?: boolean;
tags?: string; // comma-separated string
categories?: string; // comma-separated string
}
export interface CurrentUser {
sub: string;
email: string;
role: UserRole;
name?: string;
iat?: number;
exp?: number;
}

View File

@@ -1,7 +1,22 @@
import type { NextConfig } from "next";
import path from "path";
const nextConfig: NextConfig = {
/* config options here */
turbopack: {
root: path.resolve(__dirname),
},
images: {
remotePatterns: [
{
protocol: "https",
hostname: "images.unsplash.com",
},
{
protocol: "https",
hostname: "**.unsplash.com",
},
],
},
};
export default nextConfig;

View File

@@ -8,10 +8,12 @@
"name": "frontend",
"version": "0.1.0",
"dependencies": {
"@tailwindcss/typography": "^0.5.19",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"embla-carousel-react": "^8.6.0",
"lucide-react": "^0.574.0",
"marked": "^17.0.3",
"next": "16.1.6",
"next-themes": "^0.4.6",
"radix-ui": "^1.4.3",
@@ -3757,6 +3759,31 @@
"tailwindcss": "4.1.18"
}
},
"node_modules/@tailwindcss/typography": {
"version": "0.5.19",
"resolved": "https://registry.npmjs.org/@tailwindcss/typography/-/typography-0.5.19.tgz",
"integrity": "sha512-w31dd8HOx3k9vPtcQh5QHP9GwKcgbMp87j58qi6xgiBnFFtKEAgCWnDw4qUT8aHwkCp8bKvb/KGKWWHedP0AAg==",
"license": "MIT",
"dependencies": {
"postcss-selector-parser": "6.0.10"
},
"peerDependencies": {
"tailwindcss": ">=3.0.0 || insiders || >=4.0.0-alpha.20 || >=4.0.0-beta.1"
}
},
"node_modules/@tailwindcss/typography/node_modules/postcss-selector-parser": {
"version": "6.0.10",
"resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.10.tgz",
"integrity": "sha512-IQ7TZdoaqbT+LCpShg46jnZVlhWD2w6iQYAcYXfHARZ7X1t/UGhhceQDs5X0cGqKvYlHNOuv7Oa1xmb0oQuA3w==",
"license": "MIT",
"dependencies": {
"cssesc": "^3.0.0",
"util-deprecate": "^1.0.2"
},
"engines": {
"node": ">=4"
}
},
"node_modules/@ts-morph/common": {
"version": "0.27.0",
"resolved": "https://registry.npmjs.org/@ts-morph/common/-/common-0.27.0.tgz",
@@ -5390,7 +5417,6 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz",
"integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==",
"dev": true,
"license": "MIT",
"bin": {
"cssesc": "bin/cssesc"
@@ -8565,6 +8591,18 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/marked": {
"version": "17.0.3",
"resolved": "https://registry.npmjs.org/marked/-/marked-17.0.3.tgz",
"integrity": "sha512-jt1v2ObpyOKR8p4XaUJVk3YWRJ5n+i4+rjQopxvV32rSndTJXvIzuUdWWIy/1pFQMkQmvTXawzDNqOH/CUmx6A==",
"license": "MIT",
"bin": {
"marked": "bin/marked.js"
},
"engines": {
"node": ">= 20"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
@@ -10888,7 +10926,6 @@
"version": "4.1.18",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.1.18.tgz",
"integrity": "sha512-4+Z+0yiYyEtUVCScyfHCxOYP06L5Ne+JiHhY2IjR2KWMIWhJOYZKLSGZaP5HkZ8+bY0cxfzwDE5uOmzFXyIwxw==",
"dev": true,
"license": "MIT"
},
"node_modules/tapable": {
@@ -11453,7 +11490,6 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"dev": true,
"license": "MIT"
},
"node_modules/validate-npm-package-name": {

View File

@@ -9,10 +9,12 @@
"lint": "eslint"
},
"dependencies": {
"@tailwindcss/typography": "^0.5.19",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"embla-carousel-react": "^8.6.0",
"lucide-react": "^0.574.0",
"marked": "^17.0.3",
"next": "16.1.6",
"next-themes": "^0.4.6",
"radix-ui": "^1.4.3",

View File

@@ -10,6 +10,14 @@ import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
// ─── CORS — allow Next.js frontend ──────────────────────────────────────────
app.enableCors({
origin: process.env.FRONTEND_URL || 'http://localhost:3000',
credentials: true,
methods: ['GET', 'POST', 'PATCH', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'x-csrf-token'],
});
// ─── Static assets ──────────────────────────────────────────────────────────
app.useStaticAssets(join(process.cwd(), 'public'));