All files / src/lib/auth auth-utils.ts

97.56% Statements 80/82
94.28% Branches 33/35
100% Functions 5/5
97.56% Lines 80/82

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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 831x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 40x 40x 14x 14x 23x 23x 1x 1x 1x 1x 1x 1x 1x 12x 12x 3x 3x 8x 12x 5x 5x 3x 3x 1x 1x 1x 1x 1x 1x 10x 10x 2x 2x 2x 2x 2x 8x 10x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 13x 13x     8x 8x 1x 1x 1x 1x 1x 1x 15x 15x 15x  
import { auth } from "./auth";
import { NextResponse } from "next/server";
 
/**
 * Re-export auth as getServerSession for compatibility
 * This is the Next.js App Router way to get the session on the server
 */
export const getServerSession = auth;
 
/**
 * Ensures user is authenticated
 * @throws Error if not authenticated
 * @returns Session with user data
 */
export async function requireAuth() {
  const session = await auth();
  if (!session?.user?.id) {
    throw new Error("Unauthorized");
  }
  return session;
}
 
/**
 * Ensures user has ADMIN role
 * @throws Error if not admin
 * @returns Session with user data
 */
export async function requireAdminRole() {
  const session = await auth();
  if (!session?.user?.id) {
    throw new Error("Unauthorized");
  }
  const userRole = session.user.role;
  if (userRole !== "ADMIN") {
    throw new Error("Forbidden: Admin access required");
  }
  return session;
}
 
/**
 * Handles authentication and authorization errors
 * @param error Error that occurred
 * @returns NextResponse with appropriate status code, or null if not an auth error
 */
export function handleAuthError(error: Error) {
  if (error.message === "Unauthorized") {
    return NextResponse.json(
      { error: "Unauthorized" },
      { status: 401 }
    );
  }
 
  if (error.message.includes("Forbidden")) {
    return NextResponse.json(
      { error: error.message },
      { status: 403 }
    );
  }
 
  return null;
}
 
/**
 * Gets the current user's ID from session
 * @throws Error if not authenticated
 */
export async function getCurrentUserId(): Promise<number> {
  const session = await requireAuth();
  if (!session.user?.id) {
    throw new Error("Unauthorized");
  }
  return session.user.id;
}
 
/**
 * Gets the current user's role from session
 * @throws Error if not authenticated
 */
export async function getCurrentUserRole(): Promise<string> {
  const session = await requireAuth();
  return session.user.role || "CUSTOMER";
}