Package Exports
- exguard-backend
Readme
ExGuard Backend SDK
A simple and lightweight backend SDK for integrating with EmpowerX Guard API to validate user roles and permissions.
Installation
npm install exguard-backend
# or
yarn add exguard-backend
# or
pnpm add exguard-backendQuick Start
import { ExGuardBackend } from 'exguard-backend';
// Initialize the SDK
const exGuard = new ExGuardBackend({
apiUrl: 'https://your-guard-api-url.com'
});
// Get user access information
async function checkUserAccess(token: string) {
try {
const userAccess = await exGuard.getUserAccess(token);
console.log('User roles:', userAccess.roles);
console.log('User permissions:', userAccess.modules);
} catch (error) {
console.error('Error:', error.message);
}
}API Reference
Constructor
new ExGuardBackend(config: ExGuardConfig)Config:
apiUrl(string): Base URL of your Guard APItimeout(number, optional): Request timeout in milliseconds (default: 10000)
Methods
getUserAccess(token: string): Promise<UserAccessResponse>
Get complete user access information including roles, permissions, and field offices.
Returns:
{
user: User,
groups: string[],
roles: string[],
module: string[],
modules: ModulePermission[],
fieldOffices: string[]
}hasPermission(token: string, permission: string): Promise<boolean>
Check if user has a specific permission.
Example:
const canCreateEvent = await exGuard.hasPermission(token, 'events:create');hasRole(token: string, role: string): Promise<boolean>
Check if user has a specific role.
Example:
const isEventManager = await exGuard.hasRole(token, 'Event Manager');getModulePermissions(token: string, moduleKey: string): Promise<string[]>
Get all permissions for a specific module.
Example:
const eventPermissions = await exGuard.getModulePermissions(token, 'events');
// Returns: ['events:create', 'events:read', 'events:update', 'events:delete']getUserRoles(token: string): Promise<string[]>
Get all user roles.
Example:
const roles = await exGuard.getUserRoles(token);
// Returns: ['Event Manager', 'Viewer']getUserFieldOffices(token: string): Promise<string[]>
Get all user field offices.
Example:
const fieldOffices = await exGuard.getUserFieldOffices(token);
// Returns: ['FO-MIMAROPA', 'FO-NCR']Usage Examples
Express.js Middleware
import express from 'express';
import { ExGuardBackend } from 'exguard-backend';
const app = express();
const exGuard = new ExGuardBackend({
apiUrl: process.env.GUARD_API_URL || 'http://localhost:3001'
});
// Middleware to check permissions
const requirePermission = (permission: string) => {
return async (req: express.Request, res: express.Response, next: express.NextFunction) => {
const token = req.headers.authorization?.replace('Bearer ', '');
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
try {
const hasPermission = await exGuard.hasPermission(token, permission);
if (!hasPermission) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
next();
} catch (error) {
return res.status(401).json({ error: 'Invalid token' });
}
};
};
// Use in routes
app.post('/events', requirePermission('events:create'), (req, res) => {
// Your route logic here
});NestJS Guard
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { ExGuardBackend } from 'exguard-backend';
@Injectable()
export class PermissionGuard implements CanActivate {
private exGuard = new ExGuardBackend({
apiUrl: process.env.GUARD_API_URL
});
constructor(private requiredPermission: string) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const token = request.headers.authorization?.replace('Bearer ', '');
if (!token) {
return false;
}
return await this.exGuard.hasPermission(token, this.requiredPermission);
}
}
// Usage in controller
@Get('events')
@UseGuards(new PermissionGuard('events:read'))
async getEvents() {
// Your logic here
}Error Handling
The SDK throws specific errors for different scenarios:
- Unauthorized: Invalid or expired token (401)
- API Error: General API errors with detailed messages
- Network Error: Connection issues
Always wrap SDK calls in try-catch blocks for proper error handling.
License
MIT