- Install next-auth@4, bcryptjs, @types/bcryptjs, @types/jest - src/types/next-auth.d.ts: extend Session/JWT with tenantId, roles, isSuperAdmin - src/lib/auth-options.ts: CredentialsProvider + JWT/session callbacks, 24h maxAge - src/lib/auth.ts: getServerSession() and getCurrentUser() server helpers - src/app/api/auth/[...nextauth]/route.ts: NextAuth GET/POST handler - src/middleware.ts: withAuth middleware protecting all routes except /login /signup /api/auth/*
27 lines
791 B
TypeScript
27 lines
791 B
TypeScript
import { getServerSession as nextAuthGetServerSession } from "next-auth";
|
|
import { authOptions } from "@/lib/auth-options";
|
|
|
|
/**
|
|
* Server-side helper to get the current session.
|
|
* Wraps next-auth's getServerSession with the app's authOptions.
|
|
*
|
|
* Usage (in Server Components, Route Handlers, Server Actions):
|
|
* const session = await getServerSession();
|
|
*/
|
|
export async function getServerSession() {
|
|
return nextAuthGetServerSession(authOptions);
|
|
}
|
|
|
|
/**
|
|
* Returns the typed session user or null if not authenticated.
|
|
* Convenience wrapper that extracts session.user.
|
|
*
|
|
* Usage:
|
|
* const user = await getCurrentUser();
|
|
* if (!user) redirect("/login");
|
|
*/
|
|
export async function getCurrentUser() {
|
|
const session = await getServerSession();
|
|
return session?.user ?? null;
|
|
}
|