Skip to content

Policies

Policies define authorization rules for specific resources.

import { definePolicy } from '@veloxts/auth';
const postPolicy = definePolicy('posts', {
view: (user, post) => post.published || post.authorId === user.id,
edit: (user, post) => post.authorId === user.id,
delete: (user, post) => post.authorId === user.id || user.role === 'admin',
});
import { authorize } from '@veloxts/auth';
updatePost: procedure()
.guard(authenticated)
.input(z.object({ id: z.string(), data: UpdatePostSchema }))
.mutation(async ({ input, ctx }) => {
const post = await ctx.db.post.findUnique({ where: { id: input.id } });
// Check policy
await authorize(ctx, 'posts', 'edit', post);
return ctx.db.post.update({
where: { id: input.id },
data: input.data,
});
}),
import { can, cannot } from '@veloxts/auth';
// Check without throwing
if (await can(ctx, 'posts', 'edit', post)) {
// User can edit
}
if (await cannot(ctx, 'posts', 'delete', post)) {
// User cannot delete
}
FeatureGuardsPolicies
ScopeRequest-levelResource-level
Example”Is user admin?""Can user edit THIS post?”
CheckBefore handlerInside handler
  • Guards - Request authorization
  • JWT - Authentication