1.223345677995555.2 • Published 10 months ago

auth-interceptor-lib2 v1.223345677995555.2

Weekly downloads
-
License
ISC
Repository
-
Last release
10 months ago

AuthInterceptor

Middleware for authentication using a token provider. This middleware validates the authentication token by comparing it with the defined protected routes. Additionally, it uses a global logger to record information about unauthorized requests.

Parameters

TokenProvider

  • Type: AuthProviderInterface
  • Description: Implementation of the token provider. Examples of implementations include CognitoProvider.

ConsoleLogger

  • Type: LoggerInterface
  • Description: Logger instance used to record logs in the system.

Functionality

  1. Initializes the global logger using LoggerSingleton.initialize(ConsoleLogger).
  2. Checks if the current route is a public route. If it is, access is allowed directly.
  3. Validates the token provided in the authorization header.
  4. If the token is invalid:
    • Uses the logger to record the unauthorized attempt.
    • Returns a response with the status 401 Unauthorized.
  5. If the token is valid:
    • Allows the request to continue by calling next().

Return

A middleware function compatible with frameworks like Express.

Usage Example with Express

import ConsoleLogger from './logger/console.logger';
import express from 'express';
import AuthInterceptor, { CognitoProvider } from 'auth-interceptor-lib';

const app = express();

// Initialize the global logger, type LoggerInterface exported by: import { LoggerInterface } from 'auth-interceptor-lib'
const logger = new ConsoleLogger();

// Initialize the AuthInterceptor with the TokenProvider and Logger
const authMiddleware = AuthInterceptor(new CognitoProvider(), logger);

// Use the middleware in the application
app.use(authMiddleware);

Usage Example with NestJS

import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'
import AuthProvider, { CognitoProvider } from 'auth-interceptor-lib';
import { ConsoleLogger } from '@/@core/infra/middlewares/logger';

@Module({
  imports: [],
  providers: [],
})

export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    const userPoolId = process.env.USER_POOL_ID || '';
    if (!userPoolId) {
      throw new Error('USER_POOL_ID is not set in the environment variables.');
    }
    consumer
      .apply(AuthProvider(new CognitoProvider(userPoolId), new ConsoleLogger()))
      .forRoutes('*');
  }
}
1.22334567799.2

10 months ago

1.223345.2

10 months ago

1.22334567799111.2

10 months ago

1.223345677995555.2

10 months ago

1.2233456.2

10 months ago

1.223345677.2

10 months ago

1.22334.2

10 months ago

1.2233.2

10 months ago

1.223.2

10 months ago

1.22.2

10 months ago