infoalloggi-monorepo/apps/infoalloggi/src/server/utils/ctxChecker.ts
2025-08-04 17:45:44 +02:00

39 lines
1.1 KiB
TypeScript

import { TRPCError } from "@trpc/server";
import type { NextApiRequest, NextApiResponse } from "next";
import type { Context, Session } from "~/server/api/trpc";
import type { Prettify } from "TypeHelpers.type";
export const checkCtx = (props: {
res: NextApiResponse | undefined;
req: NextApiRequest | undefined;
}) => {
const { req, res } = props;
if (!req || !res)
throw new TRPCError({ code: "BAD_REQUEST", message: "res o req mancanti" });
};
type CtxWSession = Prettify<Context & { session: Session }>;
export const checkCtxSession = ({ ctx }: { ctx: Context }) => {
if (!ctx.session) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "Utente non autorizzato",
});
}
return ctx as CtxWSession;
};
export const checkCtxAdmin = ({ ctx }: { ctx: Context }) => {
const ckd_ctx = checkCtxSession({ ctx });
if (!ckd_ctx.session.isAdmin) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "Utente non autorizzato",
});
}
return ckd_ctx as Context & {
session: Session & {
isAdmin: true;
};
};
};