Fastify plugin for Fire Shield RBAC authorization.
npm install @fire-shield/fastify@3.1.1 @fire-shield/core@3.1.1import Fastify from 'fastify';
import { RBAC } from '@fire-shield/core';
import { FastifyRBACAdapter, fastifyRBACPlugin } from '@fire-shield/fastify';
const fastify = Fastify();
const rbac = new RBAC();
// Setup roles
rbac.createRole('admin', ['user:*', 'post:*']);
rbac.createRole('editor', ['post:read', 'post:write']);
// Create adapter
const rbacPlugin = new FastifyRBACAdapter(rbac);
// Optionally register as a Fastify plugin (decorates fastify.rbac and fastify.authorize)
fastify.register(fastifyRBACPlugin(rbac));
// Add user to request
fastify.addHook('preHandler', (request, reply, done) => {
request.user = { id: 'user-1', roles: ['editor'] };
done();
});
// Protect routes with permission check
fastify.get('/admin/users', {
preHandler: rbacPlugin.permission('user:read')
}, async (request, reply) => {
return { users: [] };
});
// Protect with role check
fastify.post('/posts', {
preHandler: rbacPlugin.role('editor')
}, async (request, reply) => {
return { success: true };
});
fastify.listen({ port: 3000 });Creates a new Fastify adapter instance.
Options:
getUser?: (request) => RBACUser- Extract user from requestonUnauthorized?: (result, request, reply) => void- Custom unauthorized handleronError?: (error, request, reply) => void- Custom error handler
Returns a Fastify plugin function that decorates the instance with rbac and authorize.
import { fastifyRBACPlugin } from '@fire-shield/fastify';
fastify.register(fastifyRBACPlugin(rbac));Hook to check if user has specific permission.
fastify.get('/admin', {
preHandler: rbacPlugin.permission('admin:access')
}, handler);Hook to check if user has specific role.
fastify.get('/admin', {
preHandler: rbacPlugin.role('admin')
}, handler);Hook to check resource:action permission.
fastify.delete('/users/:id', {
preHandler: rbacPlugin.resourceAction('user', 'delete')
}, handler);const rbacPlugin = new FastifyRBACAdapter(rbac, {
getUser: (request) => request.session?.user || request.user
});const rbacPlugin = new FastifyRBACAdapter(rbac, {
onUnauthorized: (result, request, reply) => {
reply.status(403).send({
error: 'Access Denied',
required: result.reason,
user: result.user?.id
});
}
});fastify.register(async (fastify) => {
// All routes in this context require admin role
fastify.addHook('preHandler', rbacPlugin.role('admin'));
fastify.get('/users', handler);
fastify.post('/users', handler);
fastify.delete('/users/:id', handler);
});DIB © Fire Shield Team