Add logout flow and header sign-out button

This commit is contained in:
爱喝水的木子
2026-03-20 12:50:44 +08:00
parent 33fbf38820
commit e6788d0e8f
3 changed files with 67 additions and 3 deletions

16
app/api/logout/route.ts Normal file
View File

@@ -0,0 +1,16 @@
import { NextResponse } from "next/server";
import { cookieName } from "@/lib/auth";
export async function POST() {
const res = NextResponse.json({ ok: true });
res.cookies.set(cookieName, "", {
httpOnly: true,
sameSite: "lax",
secure: process.env.NODE_ENV === "production",
maxAge: 0,
expires: new Date(0),
path: "/"
});
return res;
}

View File

@@ -3,6 +3,7 @@ import type { Metadata } from "next";
import Link from "next/link"; import Link from "next/link";
import { ReactNode } from "react"; import { ReactNode } from "react";
import { cookies } from "next/headers"; import { cookies } from "next/headers";
import { LogoutButton } from "@/components/LogoutButton";
import { cookieName, verifySession } from "@/lib/auth"; import { cookieName, verifySession } from "@/lib/auth";
export const metadata: Metadata = { export const metadata: Metadata = {
@@ -44,9 +45,12 @@ export default async function RootLayout({ children }: { children: ReactNode })
</nav> </nav>
{session ? ( {session ? (
<span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-medium text-slate-700"> <div className="flex items-center gap-2">
{userName} <span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-medium text-slate-700">
</span> {userName}
</span>
<LogoutButton />
</div>
) : ( ) : (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Link <Link

View File

@@ -0,0 +1,44 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
const LOGOUT_FAILED_TEXT = "\u9000\u51fa\u767b\u5f55\u5931\u8d25";
const LOGGING_OUT_TEXT = "\u9000\u51fa\u4e2d...";
const LOGOUT_TEXT = "\u9000\u51fa\u767b\u5f55";
export function LogoutButton() {
const router = useRouter();
const [loading, setLoading] = useState(false);
async function handleLogout() {
if (loading) return;
setLoading(true);
try {
const res = await fetch("/api/logout", { method: "POST" });
const data = await res.json().catch(() => ({}));
if (!res.ok) {
alert(data.error || LOGOUT_FAILED_TEXT);
return;
}
router.replace("/");
router.refresh();
} finally {
setLoading(false);
}
}
return (
<button
type="button"
onClick={handleLogout}
disabled={loading}
className="rounded-full bg-red-50 px-3 py-1 text-xs font-medium text-red-600 ring-1 ring-red-100 hover:bg-red-100 disabled:cursor-not-allowed disabled:opacity-60"
>
{loading ? LOGGING_OUT_TEXT : LOGOUT_TEXT}
</button>
);
}