@pulzar/core
Version:
Next-generation Node.js framework for ultra-fast web applications with zero-reflection DI, GraphQL, WebSockets, events, and edge runtime support
63 lines • 2.46 kB
JavaScript
import { logger } from "../utils/logger";
export function createAuthGuard(options = {}) {
const defaultOptions = {
required: true,
roles: [],
permissions: [],
};
const guardOptions = { ...defaultOptions, ...options };
return async (request, reply) => {
try {
// Check if authentication is required
if (!guardOptions.required) {
return;
}
// Get token from header
const authHeader = request.headers.authorization;
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return reply.code(401).send({ error: "No valid authorization header" });
}
const token = authHeader.substring(7);
// Verify token (placeholder implementation)
const user = await verifyToken(token);
if (!user) {
return reply.code(401).send({ error: "Invalid token" });
}
// Check roles if specified
if (guardOptions.roles &&
guardOptions.roles.length > 0 &&
!guardOptions.roles.includes(user.role)) {
return reply.code(403).send({ error: "Insufficient role permissions" });
}
// Check permissions if specified
if (guardOptions.permissions && guardOptions.permissions.length > 0) {
const hasPermission = guardOptions.permissions.some((permission) => user.permissions?.includes(permission));
if (!hasPermission) {
return reply.code(403).send({ error: "Insufficient permissions" });
}
}
// Attach user to request
request.user = user;
}
catch (error) {
logger.error("Auth guard error", { error });
return reply.code(500).send({ error: "Authentication error" });
}
};
}
async function verifyToken(token) {
// Placeholder implementation
// In a real implementation, this would verify JWT or session
return {
id: 1,
email: "user@example.com",
role: "user",
permissions: ["read", "write"],
};
}
export function registerAuthGuardPlugin(fastify, options = {}) {
const authGuardHook = createAuthGuard(options);
fastify.addHook("preHandler", authGuardHook);
}
export const authGuard = createAuthGuard();
//# sourceMappingURL=auth.guard.js.map