51 lines
2.0 KiB
TypeScript
51 lines
2.0 KiB
TypeScript
import { ExecutionContext, ForbiddenException } from "@nestjs/common";
|
|
import { Reflector } from "@nestjs/core";
|
|
import { RolesGuard } from "../src/common/guards/roles.guard";
|
|
import { ROLES_KEY } from "../src/common/decorators/roles.decorator";
|
|
import { IS_PUBLIC_KEY } from "../src/common/guards/jwt-auth.guard";
|
|
import { createPrismaMock } from "./utils/mock-prisma";
|
|
|
|
const createContext = (userId?: string) =>
|
|
({
|
|
getHandler: jest.fn(),
|
|
getClass: jest.fn(),
|
|
switchToHttp: () => ({
|
|
getRequest: () => ({ user: userId ? { sub: userId } : undefined }),
|
|
}),
|
|
}) as unknown as ExecutionContext;
|
|
|
|
describe("RolesGuard", () => {
|
|
it("allows users with the required role", async () => {
|
|
const prisma = createPrismaMock();
|
|
prisma.user.findUnique.mockResolvedValue({ role: "admin" });
|
|
const reflector = {
|
|
getAllAndOverride: jest.fn((key: string) => key === ROLES_KEY ? ["admin"] : undefined),
|
|
} as unknown as Reflector;
|
|
const guard = new RolesGuard(reflector, prisma as any);
|
|
|
|
await expect(guard.canActivate(createContext("user_1"))).resolves.toBe(true);
|
|
});
|
|
|
|
it("blocks users without the required role", async () => {
|
|
const prisma = createPrismaMock();
|
|
prisma.user.findUnique.mockResolvedValue({ role: "user" });
|
|
const reflector = {
|
|
getAllAndOverride: jest.fn((key: string) => key === ROLES_KEY ? ["admin"] : undefined),
|
|
} as unknown as Reflector;
|
|
const guard = new RolesGuard(reflector, prisma as any);
|
|
|
|
await expect(guard.canActivate(createContext("user_1"))).rejects.toBeInstanceOf(ForbiddenException);
|
|
});
|
|
|
|
it("skips checks for public routes", async () => {
|
|
const prisma = createPrismaMock();
|
|
const reflector = {
|
|
getAllAndOverride: jest.fn((key: string) => key === IS_PUBLIC_KEY ? true : ["admin"]),
|
|
} as unknown as Reflector;
|
|
const guard = new RolesGuard(reflector, prisma as any);
|
|
|
|
await expect(guard.canActivate(createContext())).resolves.toBe(true);
|
|
expect(prisma.user.findUnique).not.toHaveBeenCalled();
|
|
});
|
|
});
|