feat: add role-based access control
This commit is contained in:
parent
c42b8e2904
commit
8ab9a9a497
21 changed files with 629 additions and 46 deletions
|
|
@ -1,6 +1,7 @@
|
|||
import { initTRPC, TRPCError } from "@trpc/server";
|
||||
|
||||
import type { Context } from "./context";
|
||||
import type { Permission } from "./permissions";
|
||||
|
||||
export const t = initTRPC.context<Context>().create();
|
||||
|
||||
|
|
@ -23,3 +24,33 @@ export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
|
|||
},
|
||||
});
|
||||
});
|
||||
|
||||
export function requirePermission(permission: Permission) {
|
||||
return t.middleware(({ ctx, next }) => {
|
||||
if (!ctx.session) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "Authentication required",
|
||||
cause: "No session",
|
||||
});
|
||||
}
|
||||
|
||||
if (!ctx.authorization.permissions.includes(permission)) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: `Missing permission: ${permission}`,
|
||||
});
|
||||
}
|
||||
|
||||
return next({
|
||||
ctx: {
|
||||
...ctx,
|
||||
session: ctx.session,
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function permissionedProcedure(permission: Permission) {
|
||||
return t.procedure.use(requirePermission(permission));
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue