From 5d036e6580a93f03e73691c0ef206d2e759c718d Mon Sep 17 00:00:00 2001 From: Yedidia Alebachew <201823786+yedidiaalebachew@users.noreply.github.com> Date: Fri, 23 Oct 2026 22:33:59 -0400 Subject: [PATCH 1/5] feat: connect sign-in form, logout, and proxy to the real session flow (cherry picked from commit 7f8927daa6685f31c7f7d71532436b01f8595d8b) --- prisma/seed.ts | 50 +++-- src/actions/chapters.ts | 3 + src/actions/partners.ts | 3 + src/actions/projects.ts | 3 + src/actions/volunteers.ts | 3 + src/app/(auth)/sign-in/SignInForm.tsx | 206 ++++++++++++++---- src/app/(auth)/sign-in/page.tsx | 27 ++- .../(directory)/chapters/[id]/edit/page.tsx | 2 + .../(directory)/chapters/new/page.tsx | 4 +- .../(directory)/partners/[id]/edit/page.tsx | 2 + .../(directory)/partners/new/page.tsx | 4 +- .../(directory)/projects/[id]/edit/page.tsx | 2 + .../(directory)/projects/new/page.tsx | 4 +- .../(directory)/volunteers/[id]/edit/page.tsx | 2 + .../(directory)/volunteers/new/page.tsx | 4 +- src/app/(protected)/layout.tsx | 10 +- src/app/api/auth/login/route.ts | 57 +++-- src/app/api/auth/logout/route.ts | 25 ++- src/app/api/auth/magic-link/route.ts | 9 +- src/app/api/auth/magic-link/verify/route.ts | 17 +- src/app/page.tsx | 7 +- src/components/layout/Sidebar.tsx | 53 ++++- src/lib/auth/cookies.ts | 33 +++ src/lib/auth/guards.ts | 75 +++++++ src/lib/auth/session.ts | 50 ++++- src/proxy.ts | 63 ++++-- src/types/index.ts | 2 +- 27 files changed, 581 insertions(+), 139 deletions(-) create mode 100644 src/lib/auth/cookies.ts create mode 100644 src/lib/auth/guards.ts diff --git a/prisma/seed.ts b/prisma/seed.ts index 20303f6..9b65325 100644 --- a/prisma/seed.ts +++ b/prisma/seed.ts @@ -1,3 +1,6 @@ +// Loads .env so DATABASE_URL is set — tsx does not do this automatically. +// Matches prisma.config.ts, which imports dotenv for the same reason. +import "dotenv/config"; import { PrismaClient } from "@prisma/client"; import { PrismaPg } from "@prisma/adapter-pg"; import bcrypt from "bcryptjs"; @@ -5,21 +8,42 @@ import bcrypt from "bcryptjs"; const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL! }); const db = new PrismaClient({ adapter }); +// Cost factor 12 — matches hashPassword() in src/lib/auth/password.ts. +const COST = 12; + +// Dev-only accounts. All share the same password, matching the README +// and the old Auth.js dev constant. 8 chars = the minimum loginRequestSchema allows. +const DEV_PASSWORD = "password"; + +const users = [ + { email: "admin@hack4impact.org", role: "ADMIN" as const }, + { email: "lead@hack4impact.org", role: "PROJECT_LEAD" as const }, + { email: "volunteer@hack4impact.org", role: "VOLUNTEER" as const }, +]; + async function main() { - await db.user.upsert({ - where: { email: "admin@hack4impact.org" }, - update: {}, - create: { - name: "Admin", - email: "admin@hack4impact.org", - password: await bcrypt.hash("password", 10), - role: "ADMIN", - }, - }); - - console.log("Seed complete"); + const passwordHash = await bcrypt.hash(DEV_PASSWORD, COST); + + for (const user of users) { + await db.user.upsert({ + where: { email: user.email }, + update: { role: user.role, passwordHash }, + create: { + email: user.email, + passwordHash, + role: user.role, + directoryOptIn: true, + }, + }); + console.log(` ${user.role.padEnd(12)} ${user.email}`); + } + + console.log(`\nSeed complete. Password for all accounts: ${DEV_PASSWORD}`); } main() - .catch(console.error) + .catch((error) => { + console.error(error); + process.exitCode = 1; + }) .finally(() => db.$disconnect()); diff --git a/src/actions/chapters.ts b/src/actions/chapters.ts index 1515e43..1e3c45a 100644 --- a/src/actions/chapters.ts +++ b/src/actions/chapters.ts @@ -1,7 +1,10 @@ "use server"; +import { assertSession } from "@/lib/auth/guards"; + import { getChapters as _getChapters } from "@/lib/notion/api"; export async function getChapters() { + await assertSession(); return _getChapters(); } diff --git a/src/actions/partners.ts b/src/actions/partners.ts index 282bf24..9e02653 100644 --- a/src/actions/partners.ts +++ b/src/actions/partners.ts @@ -1,7 +1,10 @@ "use server"; +import { assertSession } from "@/lib/auth/guards"; + import { getPartners as _getPartners } from "@/lib/notion/api"; export async function getPartners() { + await assertSession(); return _getPartners(); } diff --git a/src/actions/projects.ts b/src/actions/projects.ts index d52f8f0..49607c4 100644 --- a/src/actions/projects.ts +++ b/src/actions/projects.ts @@ -1,7 +1,10 @@ "use server"; +import { assertSession } from "@/lib/auth/guards"; + import { getProjects as _getProjects } from "@/lib/notion/api"; export async function getProjects() { + await assertSession(); return _getProjects(); } diff --git a/src/actions/volunteers.ts b/src/actions/volunteers.ts index f67a7ce..e33a53d 100644 --- a/src/actions/volunteers.ts +++ b/src/actions/volunteers.ts @@ -1,7 +1,10 @@ "use server"; +import { assertSession } from "@/lib/auth/guards"; + import { getVolunteers as _getVolunteers } from "@/lib/notion/api"; export async function getVolunteers() { + await assertSession(); return _getVolunteers(); } diff --git a/src/app/(auth)/sign-in/SignInForm.tsx b/src/app/(auth)/sign-in/SignInForm.tsx index 9e852f0..0a4101a 100644 --- a/src/app/(auth)/sign-in/SignInForm.tsx +++ b/src/app/(auth)/sign-in/SignInForm.tsx @@ -1,6 +1,7 @@ "use client"; -import { useState, useTransition } from "react"; +import { useState } from "react"; +import { useRouter } from "next/navigation"; import { Card, CardDivider } from "@/components/ui/Card"; import { Button } from "@/components/ui/Button"; import { @@ -10,21 +11,118 @@ import { FormInput, FormError, } from "@/components/ui/Form"; -import { credentialsSignIn } from "@/actions/auth"; -export default function SignInForm() { +export default function SignInForm({ + callbackUrl = "/dashboard", +}: { + callbackUrl?: string; +}) { + const router = useRouter(); const [showPassword, setShowPassword] = useState(false); const [error, setError] = useState(null); - const [isPending, startTransition] = useTransition(); + const [isPending, setIsPending] = useState(false); + const [mode, setMode] = useState<"password" | "magic">("password"); + // Set once a link has been requested; switches the card to a confirmation. + const [sentTo, setSentTo] = useState(null); + + function switchMode(next: "password" | "magic") { + setMode(next); + setError(null); + } + + async function handleSubmit(e: React.SubmitEvent) { + if (mode === "magic") { + return handleMagicLink(e); + } - function handleSubmit(e: React.SubmitEvent) { e.preventDefault(); setError(null); + setIsPending(true); + const formData = new FormData(e.currentTarget); - startTransition(async () => { - const result = await credentialsSignIn(formData); - if (result?.error) setError(result.error); - }); + + try { + const response = await fetch("/api/auth/login", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + email: formData.get("email"), + password: formData.get("password"), + }), + }); + + // fetch only rejects on network failure. A 401 arrives here as a + // perfectly resolved promise, so the status must be checked by hand -- + // wrapping this in try/catch alone would treat a failed login as success. + if (!response.ok) { + setError("Invalid email or password."); + setIsPending(false); + return; + } + + // The session cookie is set by the response. refresh() re-renders the + // server components, which still have the signed-out state cached. + router.push(callbackUrl); + router.refresh(); + } catch { + setError("Could not reach the server. Please try again."); + setIsPending(false); + } + } + + async function handleMagicLink(e: React.SubmitEvent) { + e.preventDefault(); + setError(null); + setIsPending(true); + + const email = String(new FormData(e.currentTarget).get("email") ?? ""); + + try { + const response = await fetch("/api/auth/magic-link", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email }), + }); + + if (!response.ok) { + setError("Could not send the link. Please try again."); + setIsPending(false); + return; + } + + // The route deliberately answers the same way whether or not the address + // has an account, so this screen cannot be used to discover who is + // registered. Show the confirmation either way. + setSentTo(email); + } catch { + setError("Could not reach the server. Please try again."); + } + + setIsPending(false); + } + + if (sentTo) { + return ( + + +

Check your email

+

+ If an account exists for {sentTo}, a sign-in link is + on its way. The link expires in 15 minutes and can only be used once. +

+ +
+ ); } return ( @@ -54,40 +152,44 @@ export default function SignInForm() { - (!v ? "Password is required." : null)} - > -
- Password - - Forgot password? - -
-
- - -
- -
+ {mode === "password" && ( + (!v ? "Password is required." : null)} + > +
+ Password + + Forgot password? + +
+
+ + +
+ +
+ )} - {error &&

{error}

} + {error && ( +

{error}

+ )} + + diff --git a/src/app/(auth)/sign-in/page.tsx b/src/app/(auth)/sign-in/page.tsx index 4150dda..6219ab6 100644 --- a/src/app/(auth)/sign-in/page.tsx +++ b/src/app/(auth)/sign-in/page.tsx @@ -1,14 +1,33 @@ -import { auth } from "@/lib/auth"; import { redirect } from "next/navigation"; +import { getCurrentSession } from "@/lib/auth/session"; import SignInForm from "./SignInForm"; -export default async function SignInPage() { - const session = await auth(); +/** + * Only accept a relative, single-slash path. A value like + * "https://evil.example" or "//evil.example" would otherwise turn this page + * into an open redirect: an attacker links someone to + * /sign-in?callbackUrl=https://evil.example, they sign in normally, and land + * on a convincing fake. + */ +function safeCallbackUrl(value: string | undefined): string { + if (!value) return "/dashboard"; + if (!value.startsWith("/") || value.startsWith("//")) return "/dashboard"; + return value; +} + +export default async function SignInPage({ + searchParams, +}: { + searchParams: Promise<{ callbackUrl?: string }>; +}) { + const session = await getCurrentSession(); if (session) redirect("/dashboard"); + const { callbackUrl } = await searchParams; + return (
- +
); } diff --git a/src/app/(protected)/(directory)/chapters/[id]/edit/page.tsx b/src/app/(protected)/(directory)/chapters/[id]/edit/page.tsx index 9c5102b..7e471cb 100644 --- a/src/app/(protected)/(directory)/chapters/[id]/edit/page.tsx +++ b/src/app/(protected)/(directory)/chapters/[id]/edit/page.tsx @@ -1,3 +1,4 @@ +import { requireRole, EDITOR_ROLES } from "@/lib/auth/guards"; import { PageHeader } from "@/components/ui/PageHeader"; import { Button } from "@/components/ui/Button"; @@ -6,6 +7,7 @@ export default async function EditChapterPage({ }: { params: Promise<{ id: string }>; }) { + await requireRole(EDITOR_ROLES); await params; return (
diff --git a/src/app/(protected)/(directory)/chapters/new/page.tsx b/src/app/(protected)/(directory)/chapters/new/page.tsx index 4d1993d..7421893 100644 --- a/src/app/(protected)/(directory)/chapters/new/page.tsx +++ b/src/app/(protected)/(directory)/chapters/new/page.tsx @@ -1,7 +1,9 @@ +import { requireRole, EDITOR_ROLES } from "@/lib/auth/guards"; import { PageHeader } from "@/components/ui/PageHeader"; import { Button } from "@/components/ui/Button"; -export default function NewChapterPage() { +export default async function NewChapterPage() { + await requireRole(EDITOR_ROLES); return (
diff --git a/src/app/(protected)/(directory)/partners/[id]/edit/page.tsx b/src/app/(protected)/(directory)/partners/[id]/edit/page.tsx index d3cfadc..1be8a29 100644 --- a/src/app/(protected)/(directory)/partners/[id]/edit/page.tsx +++ b/src/app/(protected)/(directory)/partners/[id]/edit/page.tsx @@ -1,3 +1,4 @@ +import { requireRole, EDITOR_ROLES } from "@/lib/auth/guards"; import { PageHeader } from "@/components/ui/PageHeader"; import { Button } from "@/components/ui/Button"; @@ -6,6 +7,7 @@ export default async function EditPartnerPage({ }: { params: Promise<{ id: string }>; }) { + await requireRole(EDITOR_ROLES); await params; return (
diff --git a/src/app/(protected)/(directory)/partners/new/page.tsx b/src/app/(protected)/(directory)/partners/new/page.tsx index 1aff28f..8829dd0 100644 --- a/src/app/(protected)/(directory)/partners/new/page.tsx +++ b/src/app/(protected)/(directory)/partners/new/page.tsx @@ -1,7 +1,9 @@ +import { requireRole, EDITOR_ROLES } from "@/lib/auth/guards"; import { PageHeader } from "@/components/ui/PageHeader"; import { Button } from "@/components/ui/Button"; -export default function NewPartnerPage() { +export default async function NewPartnerPage() { + await requireRole(EDITOR_ROLES); return (
diff --git a/src/app/(protected)/(directory)/projects/[id]/edit/page.tsx b/src/app/(protected)/(directory)/projects/[id]/edit/page.tsx index c04ced1..acb065e 100644 --- a/src/app/(protected)/(directory)/projects/[id]/edit/page.tsx +++ b/src/app/(protected)/(directory)/projects/[id]/edit/page.tsx @@ -1,3 +1,4 @@ +import { requireRole, EDITOR_ROLES } from "@/lib/auth/guards"; import { PageHeader } from "@/components/ui/PageHeader"; import { Button } from "@/components/ui/Button"; @@ -6,6 +7,7 @@ export default async function EditProjectPage({ }: { params: Promise<{ id: string }>; }) { + await requireRole(EDITOR_ROLES); await params; return (
diff --git a/src/app/(protected)/(directory)/projects/new/page.tsx b/src/app/(protected)/(directory)/projects/new/page.tsx index 75723da..f2617ee 100644 --- a/src/app/(protected)/(directory)/projects/new/page.tsx +++ b/src/app/(protected)/(directory)/projects/new/page.tsx @@ -1,7 +1,9 @@ +import { requireRole, EDITOR_ROLES } from "@/lib/auth/guards"; import { PageHeader } from "@/components/ui/PageHeader"; import { Button } from "@/components/ui/Button"; -export default function NewProjectPage() { +export default async function NewProjectPage() { + await requireRole(EDITOR_ROLES); return (
diff --git a/src/app/(protected)/(directory)/volunteers/[id]/edit/page.tsx b/src/app/(protected)/(directory)/volunteers/[id]/edit/page.tsx index b7ba63a..29feba8 100644 --- a/src/app/(protected)/(directory)/volunteers/[id]/edit/page.tsx +++ b/src/app/(protected)/(directory)/volunteers/[id]/edit/page.tsx @@ -1,3 +1,4 @@ +import { requireRole, EDITOR_ROLES } from "@/lib/auth/guards"; import { PageHeader } from "@/components/ui/PageHeader"; import { Button } from "@/components/ui/Button"; @@ -6,6 +7,7 @@ export default async function EditVolunteerPage({ }: { params: Promise<{ id: string }>; }) { + await requireRole(EDITOR_ROLES); await params; return (
diff --git a/src/app/(protected)/(directory)/volunteers/new/page.tsx b/src/app/(protected)/(directory)/volunteers/new/page.tsx index 8d0ba97..1cf4ce1 100644 --- a/src/app/(protected)/(directory)/volunteers/new/page.tsx +++ b/src/app/(protected)/(directory)/volunteers/new/page.tsx @@ -1,7 +1,9 @@ +import { requireRole, EDITOR_ROLES } from "@/lib/auth/guards"; import { PageHeader } from "@/components/ui/PageHeader"; import { Button } from "@/components/ui/Button"; -export default function NewVolunteerPage() { +export default async function NewVolunteerPage() { + await requireRole(EDITOR_ROLES); return (
diff --git a/src/app/(protected)/layout.tsx b/src/app/(protected)/layout.tsx index 4790acf..2e75dae 100644 --- a/src/app/(protected)/layout.tsx +++ b/src/app/(protected)/layout.tsx @@ -1,13 +1,19 @@ import { Sidebar } from "@/components/layout/Sidebar"; +import { requireSession } from "@/lib/auth/guards"; -export default function DashboardLayout({ +export default async function DashboardLayout({ children, }: { children: React.ReactNode; }) { + // The real gate. proxy.ts only checked that a cookie existed; this looks the + // session up in the database and redirects if it is missing or expired. + // Applies to every page nested under (protected). + const session = await requireSession(); + return (
- +
{children}
); diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.ts index 30e9c1d..e264bf6 100644 --- a/src/app/api/auth/login/route.ts +++ b/src/app/api/auth/login/route.ts @@ -1,9 +1,17 @@ +import { randomBytes } from "crypto"; +import { NextResponse } from "next/server"; import { db } from "@/lib/db"; import { loginRequestSchema } from "@/lib/validators/auth"; -import { NextResponse } from "next/server"; import { verifyPassword } from "@/lib/auth/password"; +import { + SESSION_COOKIE, + SESSION_MAX_AGE_SECONDS, + sessionCookieOptions, +} from "@/lib/auth/cookies"; export async function POST(request: Request) { + // One generic response for every failure. Telling an unknown email apart + // from a wrong password would let someone enumerate who has an account. const errorResponse = NextResponse.json( { error: "Invalid email or password" }, { status: 401 } @@ -12,32 +20,43 @@ export async function POST(request: Request) { try { const body = await request.json(); const login = loginRequestSchema.parse(body); + const user = await db.user.findUnique({ where: { email: login.email } }); + + // passwordHash is null for accounts created via magic link. if (user == null || user.passwordHash == null) { return errorResponse; } - const verified = await verifyPassword(login.password, user.passwordHash); - if (verified) { - const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000); - const session = await db.session.create({ - data: { userId: user.id, expiresAt }, - }); - - return NextResponse.json( - { message: "Logged in" }, - { - status: 200, - headers: { - "Set-Cookie": `session=${session.id}; HttpOnly; Secure; path=/; SameSite=Lax; Max-Age=2592000`, - }, - } - ); - } else { + const verified = await verifyPassword(login.password, user.passwordHash); + if (!verified) { return errorResponse; } + + // The session id IS the bearer token in the cookie, so it must be + // unguessable. Generated explicitly rather than relying on the schema's + // @default(cuid()) — cuid is collision-resistant, not cryptographically + // random, and a predictable token means a forgeable login. + const session = await db.session.create({ + data: { + id: randomBytes(32).toString("hex"), + userId: user.id, + expiresAt: new Date(Date.now() + SESSION_MAX_AGE_SECONDS * 1000), + }, + }); + + const response = NextResponse.json( + { message: "Logged in" }, + { status: 200 } + ); + response.cookies.set({ + name: SESSION_COOKIE, + value: session.id, + ...sessionCookieOptions, + }); + return response; } catch (error) { - console.error(error); + console.error("Login error:", error); return errorResponse; } } diff --git a/src/app/api/auth/logout/route.ts b/src/app/api/auth/logout/route.ts index bc103e5..81acf10 100644 --- a/src/app/api/auth/logout/route.ts +++ b/src/app/api/auth/logout/route.ts @@ -1,17 +1,30 @@ +import { NextResponse } from "next/server"; import { db } from "@/lib/db"; -import { getSession } from "@/lib/auth/session"; +import { getSessionFromRequest } from "@/lib/auth/session"; +import { SESSION_COOKIE, sessionCookieOptions } from "@/lib/auth/cookies"; export async function POST(request: Request) { - const session = await getSession(request); + const session = await getSessionFromRequest(request); + // Deleting the row is what actually revokes the login. Clearing the cookie + // is a convenience: a stale cookie now points at nothing. if (session) { try { await db.session.delete({ where: { id: session.id } }); - } catch {} + } catch { + // Already gone — nothing to revoke. + } } - return new Response(null, { - status: 200, - headers: { "Set-Cookie": "session=; Max-Age=0; Path=/; HttpOnly" }, + const response = NextResponse.json( + { message: "Logged out" }, + { status: 200 } + ); + response.cookies.set({ + name: SESSION_COOKIE, + value: "", + ...sessionCookieOptions, + maxAge: 0, // expire immediately }); + return response; } diff --git a/src/app/api/auth/magic-link/route.ts b/src/app/api/auth/magic-link/route.ts index 9c1509c..f89a656 100644 --- a/src/app/api/auth/magic-link/route.ts +++ b/src/app/api/auth/magic-link/route.ts @@ -24,9 +24,7 @@ export async function POST(request: NextRequest) { try { const token = crypto.randomBytes(32).toString("hex"); const expiresAt = new Date(Date.now() + 60 * 15 * 1000); - const email = body.email; - - const plunk = new Plunk(process.env.PLUNK_API_KEY!); + const email = magicLinkRequestSchema.parse(body).email; const user = await db.user.findUnique({ where: { email: email }, @@ -44,6 +42,11 @@ export async function POST(request: NextRequest) { const magicLink = `${process.env.PUBLIC_URL}/api/auth/magic-link/verify?token=${token}`; + // Constructed after the token row exists, so a missing PLUNK_API_KEY + // cannot stop the token being issued — it can still be verified manually + // in development where no mail provider is configured. + const plunk = new Plunk(process.env.PLUNK_API_KEY!); + // send email to the user await plunk.emails.send({ to: email, diff --git a/src/app/api/auth/magic-link/verify/route.ts b/src/app/api/auth/magic-link/verify/route.ts index ea102bf..528d3ef 100644 --- a/src/app/api/auth/magic-link/verify/route.ts +++ b/src/app/api/auth/magic-link/verify/route.ts @@ -1,5 +1,11 @@ import { NextRequest, NextResponse } from "next/server"; +import { randomBytes } from "crypto"; import { db } from "@/lib/db"; +import { + SESSION_COOKIE, + SESSION_MAX_AGE_SECONDS, + sessionCookieOptions, +} from "@/lib/auth/cookies"; /** * Creates 30 day session from token and redirects to dashboard for any user. @@ -56,8 +62,9 @@ export async function GET(request: NextRequest) { // creating session — Session.id is auto-generated by Prisma (cuid); BE-04's getSession should query db.session.findUnique({ where: { id } }) const session = await db.session.create({ data: { + id: randomBytes(32).toString("hex"), userId: userId!, - expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), + expiresAt: new Date(Date.now() + SESSION_MAX_AGE_SECONDS * 1000), }, }); @@ -65,13 +72,9 @@ export async function GET(request: NextRequest) { const response = NextResponse.redirect(new URL("/dashboard", request.url)); response.cookies.set({ - name: "sessionToken", + name: SESSION_COOKIE, value: session.id, - httpOnly: true, - secure: process.env.NODE_ENV === "production", - sameSite: "lax", - maxAge: 30 * 24 * 60 * 60, - path: "/", + ...sessionCookieOptions, }); return response; diff --git a/src/app/page.tsx b/src/app/page.tsx index b82dbfa..74dfe97 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -1,8 +1,7 @@ import { redirect } from "next/navigation"; -import { auth } from "@/lib/auth"; +import { getCurrentSession } from "@/lib/auth/session"; export default async function RootPage() { - const session = await auth(); - if (session) redirect("/dashboard"); - redirect("/sign-in"); + const session = await getCurrentSession(); + redirect(session ? "/dashboard" : "/sign-in"); } diff --git a/src/components/layout/Sidebar.tsx b/src/components/layout/Sidebar.tsx index 69bfcb1..3e33b3d 100644 --- a/src/components/layout/Sidebar.tsx +++ b/src/components/layout/Sidebar.tsx @@ -1,6 +1,7 @@ "use client"; +import { useState } from "react"; import Link from "next/link"; -import { usePathname } from "next/navigation"; +import { usePathname, useRouter } from "next/navigation"; import { Menu } from "@base-ui/react/menu"; import { LayoutDashboard, @@ -10,13 +11,44 @@ import { Users, ChevronDown, } from "lucide-react"; -import { credentialsSignOut } from "@/actions/auth"; import { cn } from "@/lib/utils"; -function UserMenu() { - const initials = "AD"; - const name = "Administrator"; - const email = "admin@hack4impact.org"; +export type SidebarUser = { + email: string; + role: string; +}; + +/** "ada@x.org" -> "AD". Users have no name column, so initials come from the email. */ +function initialsFromEmail(email: string) { + return email.slice(0, 2).toUpperCase(); +} + +/** "PROJECT_LEAD" -> "Project lead" */ +function formatRole(role: string) { + const words = role.toLowerCase().replace(/_/g, " "); + return words.charAt(0).toUpperCase() + words.slice(1); +} + +function UserMenu({ user }: { user: SidebarUser }) { + const router = useRouter(); + const [isSigningOut, setIsSigningOut] = useState(false); + + const initials = initialsFromEmail(user.email); + const name = formatRole(user.role); + const email = user.email; + + async function handleSignOut() { + setIsSigningOut(true); + try { + // POST, not a link: a GET logout can be triggered by any tag + // pointing at the URL, which would sign people out unexpectedly. + await fetch("/api/auth/logout", { method: "POST" }); + } catch { + // Network failure -- fall through and send them to sign-in anyway. + } + router.push("/sign-in"); + router.refresh(); + } return ( @@ -45,9 +77,10 @@ function UserMenu() {
credentialsSignOut()} + disabled={isSigningOut} + onClick={handleSignOut} > - Sign out + {isSigningOut ? "Signing out…" : "Sign out"} @@ -88,11 +121,11 @@ function NavItem({ href, label, icon, count }: NavItemProps) { ); } -export function Sidebar() { +export function Sidebar({ user }: { user: SidebarUser }) { return (