Files
sign/packages/trpc/server/trpc.ts

67 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-06-09 18:21:18 +10:00
import { TRPCError, initTRPC } from '@trpc/server';
import SuperJSON from 'superjson';
2023-10-11 12:32:33 +03:00
import { isAdmin } from '@documenso/lib/next-auth/guards/is-admin';
import type { TrpcContext } from './context';
2023-06-09 18:21:18 +10:00
const t = initTRPC.context<TrpcContext>().create({
transformer: SuperJSON,
});
/**
* Middlewares
*/
2023-08-29 13:01:19 +10:00
export const authenticatedMiddleware = t.middleware(async ({ ctx, next }) => {
2023-06-09 18:21:18 +10:00
if (!ctx.session) {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: 'You must be logged in to perform this action.',
});
}
2023-08-29 13:01:19 +10:00
return await next({
2023-06-09 18:21:18 +10:00
ctx: {
...ctx,
user: ctx.user,
session: ctx.session,
},
});
});
2023-10-11 12:32:33 +03:00
export const adminMiddleware = t.middleware(async ({ ctx, next }) => {
if (!ctx.session || !ctx.user) {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: 'You must be logged in to perform this action.',
});
}
const isUserAdmin = isAdmin(ctx.user);
if (!isUserAdmin) {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: 'Not authorized to perform this action.',
});
}
return await next({
ctx: {
...ctx,
user: ctx.user,
session: ctx.session,
},
});
});
2023-06-09 18:21:18 +10:00
/**
* Routers and Procedures
*/
export const router = t.router;
export const procedure = t.procedure;
export const authenticatedProcedure = t.procedure.use(authenticatedMiddleware);
2023-10-11 12:32:33 +03:00
export const adminProcedure = t.procedure.use(adminMiddleware);