npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@techres/authenticate-lib

v1.0.28

Published

Token authentication package with Redis cache and gRPC fallback for restaurant services

Downloads

132

Readme

@techres/authenticate-lib

Token authentication package with Redis cache and gRPC fallback for restaurant services, with built-in NestJS integration.

Features

  • 🔐 Token Authentication - JWT token validation
  • Redis Cache - Fast token caching with TTL
  • 🌐 gRPC Fallback - Reliable backend validation
  • 🛡️ NestJS Guards - Ready-to-use authentication guards
  • 🎯 TypeScript - Full type safety
  • 📝 Annotations - Declarative authentication
  • 🚀 Performance - Cache-first strategy
  • 🔒 Platform Validation - Restrict access by platform ID

Installation

npm install @techres/authenticate-lib

Quick Start

1. Basic Usage (Stateless)

import { authenticateToken, AuthConfig } from '@techres/authenticate-lib';

const config: AuthConfig = {
  redis: { host: 'localhost', port: 6379 },
  grpc: { host: 'localhost', port: 50051 }
};

const result = await authenticateToken('your-token', config);
if (result.success) {
  console.log('User:', result.data);
}

2. NestJS Integration (Guards)

// main.ts
import { AuthGuard, AuthConfig } from '@techres/authenticate-lib';

const globalAuthConfig: AuthConfig = {
  redis: {
    host: process.env.CONFIG_REDIS_OAUTH_HOST,
    port: Number(process.env.CONFIG_REDIS_OAUTH_PORT),
    password: process.env.CONFIG_REDIS_OAUTH_PASSWORD,
    db: Number(process.env.CONFIG_REDIS_OAUTH_DB)
  },
  grpc: {
    host: process.env.CONFIG_GRPC_JAVA_NET_TECHRES_OAUTH_HOST,
    port: Number(process.env.CONFIG_GRPC_JAVA_NET_TECHRES_OAUTH_PORT)
  },
  logging: {
    enabled: true,
  }
};

// Optional: Restrict to specific platforms globally
const globalAuthConfig: AuthConfig = {
  redis: { /* ... */ },
  grpc: { /* ... */ },
  allowedPlatforms: [1, 2] // Only allow platform 1 and 2
};

AuthGuard.setGlobalConfig(globalAuthConfig);

// app.module.ts
import { AuthModule } from '@techres/authenticate-lib';
imports: [AuthModule]
providers: [
  {
    provide: APP_GUARD,
    useFactory: (reflector: Reflector) => new AuthGuard(reflector),
    inject: [Reflector],
  }
]


// controller.ts
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard, User, UserData, AllowedPlatforms, AllowedRoles } from '@techres/authenticate-lib';

@Controller('api')
@AllowedPlatforms([1, 2]) // Controller-level: allow platforms 1 and 2
@UseGuards(AuthGuard)
export class ApiController {
  @Get('profile')
  getProfile(@User() user: UserData) {
    return { user }; // Inherits controller-level platforms [1, 2]
  }

  @Get('admin-only')
  @AllowedPlatforms([3]) // Method-level: override to platform 3 only
  adminOnlyEndpoint(@User() user: UserData) {
    return { message: 'Admin access granted' };
  }

  @Get('public')
  @AllowedPlatforms([]) // Method-level: no platform restriction
  publicEndpoint(@User() user: UserData) {
    return { message: 'Public access' };
  }
}

3. NestJS Integration (Middleware)

// main.ts
import { AuthMiddleware, AuthConfig } from '@techres/authenticate-lib';

const globalAuthConfig: AuthConfig = {
  redis: {
    host: process.env.CONFIG_REDIS_OAUTH_HOST,
    port: Number(process.env.CONFIG_REDIS_OAUTH_PORT),
    password: process.env.CONFIG_REDIS_OAUTH_PASSWORD,
    db: Number(process.env.CONFIG_REDIS_OAUTH_DB)
  },
  grpc: {
    host: process.env.CONFIG_GRPC_JAVA_NET_TECHRES_OAUTH_HOST,
    port: Number(process.env.CONFIG_GRPC_JAVA_NET_TECHRES_OAUTH_PORT)
  },
  logging: {
    enabled: true,
  }
};

AuthMiddleware.setGlobalConfig(globalAuthConfig);

// app.module.ts
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { AuthMiddleware } from '@techres/authenticate-lib';

@Module({})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(AuthMiddleware)
      .forRoutes('api/*'); // Apply to all /api/* routes
  }
}

// controller.ts
import { Controller, Get, Req } from '@nestjs/common';
import { MiddlewareAuthenticatedRequest, UserData } from '@techres/authenticate-lib';

@Controller('api')
export class ApiController {
  @Get('profile')
  getProfile(@Req() req: MiddlewareAuthenticatedRequest) {
    return { user: req.user };
  }

  @Get('user-info')
  getUserInfo(@Req() req: MiddlewareAuthenticatedRequest) {
    const user: UserData = req.user;
    return {
      userId: user.user_id,
      username: user.username,
      platform: user.platform
    };
  }
}

API Reference

Core Functions

  • authenticateToken(token, config) - Stateless authentication
  • createAuthService(config) - Create reusable service
  • initializeGlobalAuthService(config) - Global service setup
  • authenticateTokenWithGlobalService(token) - Use global service

NestJS Components

Guards

  • SimpleAuthGuard - Basic authentication guard
  • AuthGuard - Advanced guard with per-route config

Middleware

  • AuthMiddleware - Authentication middleware for request pipeline

Decorators

  • @User() - Extract user data decorator
  • @SetAuthConfig() - Per-route configuration
  • @AllowedPlatforms() - Platform restriction decorator (Guards only)
  • @AllowedRoles() - Role restriction decorator (Guards only)

Error Handling

  • AuthException - Standard auth exceptions
  • AuthExceptionFilter - Error response formatter

Types

  • AuthConfig - Configuration interface
  • AuthResult - Authentication result
  • UserData - User information
  • AuthErrorResponse - Error response format
  • AuthenticatedRequest - Request with user data (Guards)
  • MiddlewareAuthenticatedRequest - Request with user data (Middleware)

Configuration

interface AuthConfig {
  redis: {
    host: string;
    port: number;
    password?: string;
    db?: number;
  };
  grpc: {
    host: string;
    port: number;
  };
  logging?: {
    enabled: boolean;
    level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR';
  };
  allowedPlatforms?: number[]; // Optional: restrict to specific platforms
}

Platform Validation

You can restrict access to specific platforms using the @AllowedPlatforms() decorator:

Controller-Level Platform Restriction

@Controller('api')
@AllowedPlatforms([1, 2, 3]) // All routes in this controller allow platforms 1, 2, 3
@UseGuards(AuthGuard)
export class ApiController {
  @Get('general')
  generalEndpoint(@User() user: UserData) {
    // Accessible by platforms 1, 2, 3
    return { platform: user.platform };
  }
}

Method-Level Platform Restriction

@Controller('api')
@AllowedPlatforms([1, 2]) // Controller-level default
@UseGuards(AuthGuard)
export class ApiController {
  @Get('admin')
  @AllowedPlatforms([3]) // Method-level overrides controller-level
  adminEndpoint(@User() user: UserData) {
    // Only accessible by platform 3
    return { message: 'Admin access' };
  }

  @Get('public')
  @AllowedPlatforms([]) // Empty array = no platform restriction
  publicEndpoint(@User() user: UserData) {
    // Accessible by any platform (overrides controller restriction)
    return { message: 'Public access' };
  }
}

Priority Order:

  1. Method-level @AllowedPlatforms() (highest priority)
  2. Controller-level @AllowedPlatforms()
  3. No restriction (if no decorator is present)

If a token has a platform not in the allowed list, a 401 Unauthorized error is returned.

Role Validation

You can restrict access to specific user roles using the @AllowedRoles() decorator:

Controller-Level Role Restriction

@Controller('admin')
@AllowedRoles(['admin', 'manager']) // All routes in this controller allow admin and manager
@UseGuards(AuthGuard)
export class AdminController {
  @Get('reports')
  getReports(@User() user: UserData) {
    // Accessible by admin and manager roles
    return { user_role: user.user_role };
  }
}

Method-Level Role Restriction

@Controller('api')
@AllowedRoles(['user', 'admin']) // Controller-level default
@UseGuards(AuthGuard)
export class ApiController {
  @Get('super-admin-only')
  @AllowedRoles(['super_admin']) // Method-level overrides controller-level
  superAdminEndpoint(@User() user: UserData) {
    // Only accessible by super_admin role
    return { message: 'Super admin access' };
  }

  @Get('public-data')
  @AllowedRoles([]) // Empty array = no role restriction
  publicData(@User() user: UserData) {
    // Accessible by any role (overrides controller restriction)
    return { message: 'Public data' };
  }
}

Combining Platform and Role Validation

@Controller('restricted')
@AllowedPlatforms([1, 2]) // Only platforms 1 and 2
@AllowedRoles(['admin']) // Only admin role
@UseGuards(AuthGuard)
export class RestrictedController {
  @Get('data')
  getRestrictedData(@User() user: UserData) {
    // User must have platform 1 or 2 AND admin role
    return { 
      platform: user.platform, 
      role: user.user_role 
    };
  }

  @Get('manager-special')
  @AllowedRoles(['manager']) // Override to manager role only
  managerEndpoint(@User() user: UserData) {
    // User must have platform 1 or 2 AND manager role
    return { message: 'Manager access' };
  }
}

Priority Order for Both Platform and Role:

  1. Method-level decorators (highest priority)
  2. Controller-level decorators
  3. No restriction (if no decorator is present)

Validation Order: Token authentication → Platform validation → Role validation → Success

If a token has a role not in the allowed list, a 401 Unauthorized error is returned.

Note: Platform and role validation are only available with Guards (AuthGuard, SimpleAuthGuard). The AuthMiddleware only performs token authentication and user data attachment.

Guards vs Middleware

When to use Guards

  • Advanced Features: Need platform/role validation using decorators
  • Route-specific Config: Different auth configs per route
  • Granular Control: Method-level access control
  • Decorator Support: Want to use @AllowedPlatforms(), @AllowedRoles(), @SetAuthConfig()
// Use Guards for advanced authentication with decorators
@Controller('admin')
@AllowedRoles(['admin', 'manager'])
@AllowedPlatforms([1, 2])
@UseGuards(AuthGuard)
export class AdminController {
  @Get('reports')
  @AllowedRoles(['admin']) // Override to admin only
  getReports(@User() user: UserData) {
    return { data: 'sensitive admin data' };
  }
}

When to use Middleware

  • Simple Authentication: Only need token validation + user data
  • Global Application: Apply to many routes at once
  • Performance: Runs earlier in request pipeline
  • Simplicity: No need for platform/role restrictions
// Use Middleware for simple, global authentication
@Module({})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(AuthMiddleware)
      .forRoutes('api/*'); // Apply to all API routes
  }
}

@Controller('api')
export class ApiController {
  @Get('data')
  getData(@Req() req: MiddlewareAuthenticatedRequest) {
    // User is automatically authenticated via middleware
    return { user: req.user };
  }
}

Comparison Table

| Feature | AuthGuard | AuthMiddleware | |---------|-----------|----------------| | Token Authentication | ✅ | ✅ | | User Data Attachment | ✅ | ✅ | | Platform Validation | ✅ | ❌ | | Role Validation | ✅ | ❌ | | Route-specific Config | ✅ | ❌ | | Decorator Support | ✅ | ❌ | | Global Application | ✅ | ✅ | | Pipeline Position | Guard Phase | Middleware Phase | | Performance | Standard | Slightly faster | | Complexity | Higher | Lower |

Error Handling

All authentication errors return a standardized format:

{
  "status": 401,
  "message": "Token validation failed",
  "data": null
}

Platform and role validation errors return:

{
  "status": 401,
  "message": "Unauthorized",
  "data": null
}

License

MIT