exguard-endpoint
v2.0.20
Published
Simple RBAC permission guard for NestJS with auto-configuration
Maintainers
Readme
ExGuard Endpoint - v2.0.13
Simple Role & Permission Management for NestJS with Auto-Configuration
A lightweight, focused package that handles user authentication using access_token, role checking, and permission management with built-in caching, automatic cache reset when tokens change, and auto-generated configuration files for zero-setup integration.
Features
- 🚀 Auto-Configuration - Generates all config files automatically
- Access Token Authentication - Uses access_token for secure authentication
- Smart Caching - Caches roles and permissions with automatic reset on token changes
- Fast Permission Checks - Single API call to get user data, then cached lookups
- Zero Setup Required - Just install and run auto-config
- Type Safe - Full TypeScript support
- Lightweight - Minimal dependencies and small bundle size
Installation
npm install [email protected]Quick Setup (Zero Configuration Required)
Option 1: Auto-Configure (Recommended)
npx exguard-endpointOption 2: Post-Install Auto-Configure
npm install [email protected]
# Auto-config runs automatically during postinstallOption 3: Manual Auto-Config
node node_modules/exguard-endpoint/dist/auto-config.cjsWhat Auto-Configuration Creates
📁 Generated Files Structure:
src/
├── config/
│ └── exguard.config.ts # Type-safe configuration
├── controllers/
│ └── exguard-example.controller.ts # Complete usage examples
└── app.module.ts # Auto-configured with ExGuardModule
.env and .env.example # Environment variables🔧 Auto-Generated Configuration
src/config/exguard.config.ts:
export interface ExGuardConfig {
baseUrl: string;
cache?: {
enabled: boolean;
ttl: number;
};
}
export const exguardConfig: ExGuardConfig = {
baseUrl: process.env.EXGUARD_BASE_URL || 'http://localhost:3000',
cache: {
enabled: process.env.EXGUARD_CACHE_ENABLED === 'true',
ttl: parseInt(process.env.EXGUARD_CACHE_TTL || '300'),
},
};Environment Variables (.env):
EXGUARD_BASE_URL=http://localhost:3000
EXGUARD_CACHE_ENABLED=true
EXGUARD_CACHE_TTL=300Auto-Configured app.module.ts:
import { ExGuardModule } from 'exguard-endpoint';
import { exguardConfig } from './config/exguard.config';
@Module({
imports: [
// ... your existing imports
ExGuardModule.forRoot(exguardConfig),
]
})
export class AppModule {}Usage Examples
Complete Controller Example
The auto-generated src/controllers/exguard-example.controller.ts provides comprehensive examples:
import {
Controller,
Get,
Post,
UseGuards,
SetMetadata,
Request,
Body
} from '@nestjs/common';
import { ExGuardPermissionGuard, ExGuardAuthService } from 'exguard-endpoint';
@Controller('api/v1/exguard')
@UseGuards(ExGuardPermissionGuard)
export class ExGuardExampleController {
constructor(private exGuard: ExGuardAuthService) {}
@Get('profile')
@SetMetadata('permissions', ['profile:view'])
async getProfile(@Request() req) {
return {
user: req.user,
message: 'User profile accessed successfully'
};
}
@Get('admin-only')
@SetMetadata('roles', ['admin'])
async adminOnly(@Request() req) {
return {
message: 'Admin access granted',
user: req.user
};
}
@Post('check-permissions')
async checkPermissions(@Body() body: { access_token: string; permissions: string[] }) {
const results = await Promise.all(
body.permissions.map(permission =>
this.exGuard.hasPermission(body.access_token, permission)
)
);
return {
permissions: body.permissions.reduce((acc, permission, index) => {
acc[permission] = results[index];
return acc;
}, {})
};
}
@Post('update-token')
async updateToken(@Body() body: { oldToken: string; newToken: string }) {
await this.exGuard.updateAccessToken(body.oldToken, body.newToken);
return { message: 'Token updated and cache reset' };
}
}Basic Controller Setup
// users.controller.ts
import { Controller, Get, UseGuards, SetMetadata } from '@nestjs/common';
import { ExGuardPermissionGuard, ExGuardAuthService } from 'exguard-endpoint';
@Controller('users')
@UseGuards(ExGuardPermissionGuard)
@SetMetadata('permissions', ['users:view'])
export class UsersController {
constructor(private exGuard: ExGuardAuthService) {}
@Get('profile')
async getProfile(@Request() req) {
return { user: req.user };
}
}API Reference
ExGuardAuthService
authenticate(access_token: string)
Get user information with cached roles and permissions.
const { user } = await exGuardService.authenticate(access_token);
// Returns: { user: UserPermissions }hasPermission(access_token: string, permission: string)
Check if user has a specific permission.
const canViewUsers = await exGuardService.hasPermission(access_token, 'users:view');hasAnyPermission(access_token: string, permissions: string[])
Check if user has any of the specified permissions.
const hasAny = await exGuardService.hasAnyPermission(access_token, ['users:view', 'users:edit']);hasAllPermissions(access_token: string, permissions: string[])
Check if user has all specified permissions.
const hasAll = await exGuardService.hasAllPermissions(access_token, ['users:view', 'users:edit']);hasRole(access_token: string, role: string)
Check if user has a specific role.
const isAdmin = await exGuardService.hasRole(access_token, 'admin');hasAnyRole(access_token: string, roles: string[])
Check if user has any of the specified roles.
const hasAnyRole = await exGuardService.hasAnyRole(access_token, ['admin', 'moderator']);updateAccessToken(oldToken: string, newToken: string)
Auto-reset cache when access_token changes.
await exGuardService.updateAccessToken(oldToken, newToken);
// This will:
// 1. Clear cache for old token
// 2. Clear any existing cache for new token
// 3. Next authentication call will fetch fresh datainvalidateCache(access_token: string)
Clear cached user data for specific token.
await exGuardService.invalidateCache(access_token);UserPermissions Interface
interface UserPermissions {
id: string;
username: string;
email: string;
roles: string[];
permissions: string[];
fieldOffices?: string[];
modules?: string[];
}ExGuardPermissionGuard
Protect routes with permission and role checking using access_token.
@Controller('admin')
@UseGuards(ExGuardPermissionGuard)
@SetMetadata('permissions', ['admin:access'])
export class AdminController {
// Only users with 'admin:access' permission can access
}@Controller('users')
@UseGuards(ExGuardPermissionGuard)
@SetMetadata('roles', ['admin', 'moderator'])
export class UsersController {
// Only users with 'admin' or 'moderator' role can access
}Token Management & Cache Reset
Automatic Cache Reset
When you call updateAccessToken(), the system automatically:
- Clears old token cache - Removes cached data for old access_token
- Clears new token cache - Ensures no stale data for new access_token
- Forces fresh data fetch - Next authentication call will fetch fresh roles and permissions
Token Lifecycle Management
@Injectable()
export class TokenService {
constructor(private exGuard: ExGuardAuthService) {}
async handleTokenRefresh(userId: string, oldToken: string, newToken: string) {
// Update token and reset cache automatically
await this.exGuard.updateAccessToken(oldToken, newToken);
// Get fresh user data with new token
const { user } = await this.exGuard.authenticate(newToken);
return { success: true, user };
}
}Configuration Options
interface ExGuardConfig {
baseUrl: string; // ExGuard API URL
cache?: {
enabled: boolean; // Enable/disable caching
ttl: number; // Cache TTL in seconds (default: 300)
};
}Custom Cache Implementation
You can provide your own cache implementation:
import { Module } from '@nestjs/common';
import { ExGuardModule, ExGuardCache } from 'exguard-endpoint';
// Custom cache implementation
class CustomCache implements ExGuardCache {
async get(key: string): Promise<string | null> { /* ... */ }
async set(key: string, value: string, ttl?: number): Promise<void> { /* ... */ }
async del(key: string): Promise<void> { /* ... */ }
async clear(): Promise<void> { /* ... */ }
}
@Module({
imports: [
ExGuardModule.forRoot(config),
],
providers: [
{ provide: ExGuardCache, useClass: CustomCache }
]
})
export class AppModule {}Getting Started
1. Install Package
npm install [email protected]2. Run Auto-Configuration
npx exguard-endpoint3. Update Environment
Edit .env file with your ExGuard API URL:
EXGUARD_BASE_URL=https://your-exguard-api.com4. Start Using
import { ExGuardPermissionGuard, ExGuardAuthService } from 'exguard-endpoint';
@Controller('api/v1/users')
@UseGuards(ExGuardPermissionGuard)
export class UsersController {
constructor(private exGuard: ExGuardAuthService) {}
@Get('profile')
@SetMetadata('permissions', ['profile:view'])
async getProfile(@Request() req) {
return { user: req.user };
}
}Security Notes
- Access Token Security: Always use HTTPS when transmitting access tokens
- Cache Security: Cached data is stored in memory and cleared when tokens change
- Token Rotation: Use
updateAccessToken()when rotating tokens to ensure cache consistency - Cache TTL: Set appropriate TTL based on your security requirements
License
MIT License - see LICENSE file for details.
Support
For issues and questions, please use the GitHub repository.
🎉 Ready to Use!
Just install the package and run npx exguard-endpoint - everything else is handled automatically!
