All files / src/lib auth-guard.ts

92.85% Statements 13/14
92.85% Branches 13/14
100% Functions 3/3
92.3% Lines 12/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64        1x                                       6x                   6x 6x 1x     5x   6x 2x 2x 1x       4x                         10x    
import { getServerSession } from "next-auth/next";
import { NextResponse } from "next/server";
import { authOptions, type Role } from "@/lib/auth";
 
const IS_STATIC = process.env.NEXT_PUBLIC_STATIC_EXPORT === "true";
 
export interface AuthSession {
  user: { id: string; name?: string | null; email?: string | null };
  roles: string[];
  accessToken: string;
}
 
interface AuthSuccess {
  session: AuthSession;
}
 
/**
 * Require authentication and optionally specific roles.
 * Returns the session on success, or a NextResponse error on failure.
 * In static export mode, returns a synthetic demo session.
 */
export async function requireAuth(
  allowedRoles?: Role[],
): Promise<AuthSuccess | NextResponse> {
  Iif (IS_STATIC) {
    return {
      session: {
        user: { id: "demo-user", name: "Demo User" },
        roles: ["EDC_ADMIN"],
        accessToken: "static-demo-token",
      },
    };
  }
 
  const session = await getServerSession(authOptions);
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
 
  const roles = (session as { roles?: string[] }).roles ?? [];
 
  if (allowedRoles && allowedRoles.length > 0) {
    const hasAny = allowedRoles.some((r) => roles.includes(r));
    if (!hasAny) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }
  }
 
  return {
    session: {
      user: session.user as AuthSession["user"],
      roles,
      accessToken: (session as { accessToken?: string }).accessToken ?? "",
    },
  };
}
 
/** Type guard: true when requireAuth returned an error response. */
export function isAuthError(
  result: AuthSuccess | NextResponse,
): result is NextResponse {
  return result instanceof NextResponse;
}