@techres/authenticate-lib
v1.0.28
Published
Token authentication package with Redis cache and gRPC fallback for restaurant services
Downloads
132
Maintainers
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-libQuick 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 authenticationcreateAuthService(config)- Create reusable serviceinitializeGlobalAuthService(config)- Global service setupauthenticateTokenWithGlobalService(token)- Use global service
NestJS Components
Guards
SimpleAuthGuard- Basic authentication guardAuthGuard- 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 exceptionsAuthExceptionFilter- Error response formatter
Types
AuthConfig- Configuration interfaceAuthResult- Authentication resultUserData- User informationAuthErrorResponse- Error response formatAuthenticatedRequest- 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:
- Method-level
@AllowedPlatforms()(highest priority) - Controller-level
@AllowedPlatforms() - 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:
- Method-level decorators (highest priority)
- Controller-level decorators
- 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
