Skip to main content

Authentication and Authorization Middleware

This document describes the authMiddleware.js file, which provides authentication and authorization functionalities for the ChainAlign backend.

Overview

This middleware is responsible for verifying user identity via Firebase ID tokens and enriching the request object with user details, including roles and permissions from the application database. It ensures that only authenticated and authorized users can access protected resources.

Key Enhancements (M24)

During the M24 refactoring, the following enhancements were made:

  • File-level Comments and JSDoc: Comprehensive documentation was added to improve code readability and maintainability.
  • appLogger Integration: All console calls were replaced with appLogger for centralized and structured logging.
  • Redundant dotenv.config() Removal: The redundant call to dotenv.config() was removed, as environment variables are expected to be loaded at application startup.

Middleware Functions

verifyToken(req, res, next)

Verifies the Firebase ID token provided in the Authorization header. If the token is valid, it fetches the user's application-specific data (like tenant_id, roles, and permissions) from the database and attaches it to the req.user object.

This middleware also includes a bypass for testing purposes when BYPASS_AUTH_FOR_TESTING is set to 'true', attaching a mock user object to the request.

Parameters:

  • req: The Express request object.
  • res: The Express response object.
  • next: The Express next middleware function.

checkPermission(requiredPermission)

Middleware to check if a user has a specific permission. This middleware should run after verifyToken.

Parameters:

  • requiredPermission (string): The name of the permission to check for.

Returns:

  • Express middleware function.

Future Refactoring (TODOs)

The following points are identified for future refactoring:

  • Database Query Abstraction: Abstract the database query for user data into a dedicated service or repository (e.g., a userRepository).
  • Dynamic Admin Check: Make the isChainAlignAdmin check more dynamic or configurable, rather than hardcoding the role name 'ChainAlignAdmin'.