Filters and Route Security
Diesel makes it easy to manage both public and protected routes using the powerful setupFilter()
method. With setupFilter()
, you can define specific routes as publicly accessible while enforcing authentication or custom middleware for protected routes. This approach enables fine-grained control over route security, ensuring sensitive resources are well-guarded.
How to Use setupFilter()
The setupFilter()
method allows you to selectively secure certain endpoints while keeping others open. With permitAll()
, you can mark specific routes as public, while authenticate()
applies one or more middleware functions to remaining routes. This flexibility helps keep user information secure while providing accessible, unauthenticated routes as needed.
Example Usage
Using setupFilter() with JWT Authentication and Middleware
import { Diesel } from "diesel-core";import authJwt from "./middleware/authJwt";import rateLimiter from "./middleware/rateLimiter";
const app = new Diesel();
// Define routes and apply filtersapp .setupFilter() .routeMatcher("/api/user/register", "/api/user/login", "/test/:id", "/cookie") // Public routes .permitAll() // Mark as public, no authentication required .authenticate([authJwt, rateLimiter]); // Apply multiple middleware to protected routes
// Public route example (no authentication needed)app.get("/api/user/register", async (ctx: ContextType) => { return ctx.json({ msg: "This is a public route. No authentication needed." });});
// Protected route example (requires authentication and rate limiting)app.get("/api/user/profile", async (ctx: ContextType) => { const user = xl.getUser(); return ctx.json({ msg: "You are authenticated!", user, });});
Built-in JWT Authentication Filters
authenticateJwt()
authenticateJwt(jwt) provides an inbuilt JWT authentication filter. Once applied, you can access the user context via ctx.get("user")
.
Example Usage:
import { Diesel } from "diesel-core";import jwt from 'jsonwebtoken'
const app = new Diesel();
// Define routes and apply filtersapp .setupFilter() .routeMatcher("/api/user/register", "/api/user/login", "/test/:id", "/cookie") // Public routes .permitAll() // Mark as public, no authentication required .authenticateJwt(jwt); // Inbuilt jwt filter
// and you will get `user` Context in ctx.get('user') app.get("/profile", async(ctx) => { // you will get user context const userDetails = ctx.get("user")
.... })
authenticateJwtDB()
authenticateJwtDB(jwt, UserModel)
integrates JWT authentication with a database model for user validation.
Example:
import { Diesel } from "diesel-core";import jwt from 'jsonwebtoken'import UserModel from "./schema/userModel"
const app = new Diesel();
// Define routes and apply filtersapp .setupFilter() .routeMatcher("/api/user/register", "/api/user/login", "/test/:id", "/cookie") // Public routes .permitAll() // Mark as public, no authentication required .authenticateJwtDB(jwt,UserModel); // Inbuilt jwt filter
// and you will get `user` Context in ctx.get('user') app.get("/profile", async(ctx) => { // you will get user context const userDetails = ctx.get("user")
.... })
Breakdown of setupFilter()
Methods
routeMatcher(...routes: string[])
: Specifies which routes should be public (unauthenticated). Supports dynamic parameters (e.g., “/api/user/register”, “/api/user/login”).
.routeMatcher("/api/user/register", "/api/user/login", "/test/:id")
permitAll()
: Marks routes inrouteMatcher()
as publicly accessible, bypassing middleware.
.permitAll()
-
authenticate(fnc?: middlewareFunc[])
: Defines one or more middleware functions for routes not included inrouteMatcher()
. If no function is provided, Diesel defaults to an “Unauthorized” response. -
authenticateJwt(jwt)
: Provides built-in JWT authentication middleware. -
authenticateJwtDB(jwt,UserModel)
: Provides built-in more secure JWT authentication middleware
.authenticate([authJwt, rateLimiter])
Use Cases
Public Routes
Routes like /api/user/register
and /api/user/login
are often public to allow user registration and login without prior authentication. These routes can be added to routeMatcher()
and marked with permitAll()
for easy access.
Protected Routes
For routes handling sensitive information (e.g., /api/user/profile
), apply authenticate([authJwt, rateLimiter])
to enforce authentication and other security layers. Only users with valid JWTs and within rate limits will be able to access these routes.
Benefits of Using Filters in Diesel
✅ No Need for app.use()
Middleware – setupFilter()
streamlines route protection, eliminating redundant middleware declarations for individual routes.
✅ Flexible Security – Easily toggle between public and protected routes.
✅ Centralized Authentication – Manage route security in one place for cleaner, more maintainable code.
✅ Scalable Middleware – Supports multiple middleware functions per route for enhanced security and functionality.
With Diesel’s setupFilter()
, securing routes becomes efficient, clear, and adaptable, allowing you to manage public and private endpoints seamlessly.