JSPM

exguard-cached

1.0.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 40
  • Score
    100M100P100Q107562F
  • License MIT

ExGuard cached user data handling package for backend integration

Package Exports

  • exguard-cached
  • exguard-cached/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (exguard-cached) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

ExGuard Cached

A reusable npm package for handling cached user data and permission checking across different backends.

Installation

pnpm add exguard-cached

Features

  • 🚀 Unified Cache Management: Single cache entry per user with CognitoId as identifier
  • 🔐 Permission Checking: Fast permission validation using cached data
  • 🏢 Field Office Support: Built-in field office information access
  • 📊 Rich User Data: Complete user profile, roles, groups, and modules
  • 🛡️ TypeScript Support: Full type safety with TypeScript definitions
  • 🔧 Flexible Cache Adapters: Support for Redis and custom cache implementations

Quick Start

1. Environment Configuration

Create a .env file in your project root:

# Copy the example environment file
cp .env.example .env

Required Environment Variables:

# Redis Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=your_redis_password
REDIS_DB=0
REDIS_KEY_PREFIX=guard:
REDIS_TTL=300

# Cache Configuration
CACHE_DEFAULT_TTL=300
CACHE_KEY_PREFIX=guard:
CACHE_ENABLE_LOGGING=true

# Permission Configuration
PERMISSION_CACHE_ENABLED=true
PERMISSION_CACHE_TTL=300

2. Setup Cache Module

import { Module } from '@nestjs/common';
import { ExGuardCacheModule } from 'exguard-cached';

@Module({
  imports: [
    ExGuardCacheModule.forRoot({
      redisClient: redisClient, // Your Redis client instance
      config: {
        cache: {
          defaultTtl: 600, // 10 minutes
          enableLogging: true,
        }
      }
    })
  ],
})
export class AppModule {}

3. Alternative: Using Redis URL

import { Module } from '@nestjs/common';
import { ExGuardCacheModule } from 'exguard-cached';

@Module({
  imports: [
    ExGuardCacheModule.forRoot({
      redisUrl: 'redis://localhost:6379',
      config: {
        cache: {
          defaultTtl: 600,
        }
      }
    })
  ],
})
export class AppModule {}

2. Use Decorators in Controllers

import { Controller, Get } from '@nestjs/common';
import { 
  RequireCachedUserPermission, 
  CachedUser, 
  CachedUserData 
} from 'exguard-cached';

@Controller('users')
export class UsersController {
  @Get()
  @RequireCachedUserPermission('exGUARD', 'user_roles:view_all')
  async getUsers(@CachedUser() cachedUser: CachedUserData) {
    // Access field office information
    const fieldOffice = cachedUser.user?.fieldOffice;
    
    return {
      user: cachedUser.user,
      fieldOffice: fieldOffice,
      permissions: cachedUser.permissions,
    };
  }
}

3. Access Cached Data

import { CachedUserService } from 'exguard-cached';

@Injectable()
export class MyService {
  constructor(private cachedUserService: CachedUserService) {}

  async getUserFieldOffice(cognitoSubId: string) {
    return await this.cachedUserService.getUserFieldOffice(cognitoSubId);
  }

  async checkPermission(cognitoSubId: string, module: string, action: string) {
    return await this.cachedUserService.hasPermission(cognitoSubId, module, action);
  }
}

API Reference

Decorators

@RequireCachedUserPermission(module, action)

Protects endpoints with permission checking using cached data.

@RequireCachedUserPermission('exGUARD', 'user_roles:view_all')
async myMethod() { ... }

@CachedUser()

Parameter decorator to get cached user data.

async myMethod(@CachedUser() user: CachedUserData) {
  console.log(user.user?.fieldOffice);
}

@CachedUserWithPermission(module, action)

Parameter decorator with automatic permission checking.

async myMethod(@CachedUserWithPermission('exGUARD', 'admin:view') user: CachedUserData) {
  // User has the required permission
}

Services

CachedUserService

Main service for cache operations.

// Get cached user data
const user = await cachedUserService.getCachedUser(cognitoSubId);

// Set cached user data
await cachedUserService.setCachedUser(cognitoSubId, userData, 300);

// Check permission
const hasPermission = await cachedUserService.hasPermission(cognitoSubId, 'exGUARD', 'view_all');

// Get field office
const fieldOffice = await cachedUserService.getUserFieldOffice(cognitoSubId);

RedisCacheAdapter

Redis implementation of cache adapter.

const adapter = new RedisCacheAdapter(redisClient);

Utilities

CacheUtils

Utility functions for cache operations.

import { CacheUtils } from 'exguard-cached';

// Generate cache key
const key = CacheUtils.generateUserKey(cognitoSubId);

// Extract field office
const fieldOffice = CacheUtils.extractFieldOffice(cachedUser);

// Check permissions
const hasPermission = CacheUtils.hasPermission(cachedUser, 'exGUARD', 'view_all');

// Get field office ID
const officeId = CacheUtils.getFieldOfficeId(cachedUser);

Data Structures

CachedUserData

interface CachedUserData {
  user: UserInfo | null;
  groups: string[];
  roles: string[];
  modules: ModulePermission[];
  fieldOffices: string[];
  permissions: string[];
  cacheInfo: CacheInfo;
}

FieldOffice

interface FieldOffice {
  id: string;
  code: string;
  name: string;
}

Integration with Existing Backend

To integrate with your existing backend:

  1. Install the package:

    pnpm add exguard-cached
  2. Create a cache module:

    // cache.module.ts
    import { Module } from '@nestjs/common';
    import { CachedUserService, RedisCacheAdapter } from 'exguard-cached';
    
    @Module({
      providers: [
        CachedUserService,
        {
          provide: 'CACHE_ADAPTER',
          useFactory: (redisClient) => new RedisCacheAdapter(redisClient),
          inject: ['REDIS_CLIENT'],
        },
      ],
      exports: [CachedUserService],
    })
    export class CacheModule {}
  3. Import in your app module:

    // app.module.ts
    import { CacheModule } from './cache.module';
    
    @Module({
      imports: [CacheModule],
      // ...
    })
    export class AppModule {}
  4. Update your controllers:

    import { RequireCachedUserPermission, CachedUser } from 'exguard-cached';
    
    @Controller()
    export class MyController {
      @Get()
      @RequireCachedUserPermission('exGUARD', 'view_all')
      async getData(@CachedUser() user: CachedUserData) {
        return {
          fieldOffice: user.user?.fieldOffice,
          permissions: user.permissions,
        };
      }
    }

Cache Key Format

The package uses the following cache key format:

guard:user:{cognitoSubId}

Example: guard:user:09eaa52c-50d1-7054-5769-8819ac43eeed

Permission Format

Permissions are stored in the format: module:resource:action

Examples:

  • exGUARD:user_roles:view_all
  • exGUARD:modules:create
  • Profile:profile:update

License

MIT

Contributing

Please read the contributing guidelines before submitting pull requests.