Authorization
Authorization configuration and utilities
Classes
AuthConfig
Defined in: packages/core/src/core/authz/authConfig.ts:182
Global authentication configuration
Constructors
Constructor
new AuthConfig(): AuthConfig;
Returns
Methods
configure()
static configure(options): void;
Defined in: packages/core/src/core/authz/authConfig.ts:198
Configure global auth settings
Parameters
options
Returns
void
Example
AuthConfig.configure({
userObjectPath: "session.user",
enableAuditLog: true,
cacheValidationResults: true,
cacheTTL: 300000
});
extractUserContext()
static extractUserContext(req): object;
Defined in: packages/core/src/core/authz/authConfig.ts:232
Extract user context from request using configured extractor
Checks in order:
- req.authContext (new strategy-based system)
- Custom userContextExtractor (if configured)
- Path-based extraction from req[userObjectPath] (legacy)
Parameters
req
Request
Express request object
Returns
object
User context with userType, groups, permissions, and raw user object
groups?
optional groups: string[];
permissions?
optional permissions: string[];
raw?
optional raw: any;
userType?
optional userType: string;
getCacheMaxSize()
static getCacheMaxSize(): number;
Defined in: packages/core/src/core/authz/authConfig.ts:376
Get cache max size
Returns
number
Maximum number of cache entries
getCacheTTL()
static getCacheTTL(decoratorOptions?): number;
Defined in: packages/core/src/core/authz/authConfig.ts:349
Get cache TTL
Parameters
decoratorOptions?
Optional per-decorator options
Returns
number
Cache TTL in milliseconds
getConfig()
static getConfig(): Readonly<Required<AuthConfigOptions>>;
Defined in: packages/core/src/core/authz/authConfig.ts:210
Get current configuration
Returns
Readonly<Required<AuthConfigOptions>>
getErrorHandler()
static getErrorHandler(decoratorOptions?): AuthErrorHandler;
Defined in: packages/core/src/core/authz/authConfig.ts:362
Get error handler
Parameters
decoratorOptions?
Optional per-decorator options
Returns
Custom error handler if configured
getUnauthorizedTracker()
static getUnauthorizedTracker(): UnauthorizedTracker;
Defined in: packages/core/src/core/authz/authConfig.ts:383
Get the globally configured unauthorized tracker.
Returns
isAuditLogEnabled()
static isAuditLogEnabled(decoratorOptions?): boolean;
Defined in: packages/core/src/core/authz/authConfig.ts:323
Check if audit logging is enabled
Parameters
decoratorOptions?
Optional per-decorator options
Returns
boolean
true if audit logging should be enabled
isCachingEnabled()
static isCachingEnabled(decoratorOptions?): boolean;
Defined in: packages/core/src/core/authz/authConfig.ts:336
Check if caching is enabled
Parameters
decoratorOptions?
Optional per-decorator options
Returns
boolean
true if caching should be enabled
reset()
static reset(): void;
Defined in: packages/core/src/core/authz/authConfig.ts:217
Reset to default configuration (useful for testing)
Returns
void
trackUnauthorized()
static trackUnauthorized(req, error): void;
Defined in: packages/core/src/core/authz/authConfig.ts:391
Fire the unauthorized tracker (if configured), swallowing any errors so that tracking issues never affect the HTTP response.
Parameters
req
Request
error
Returns
void
AuthErrorFactory
Defined in: packages/core/src/core/authz/authErrors.ts:88
Factory functions for creating common authorization errors
Constructors
Constructor
new AuthErrorFactory(): AuthErrorFactory;
Returns
Methods
accessDenied()
static accessDenied(
requiredAccess,
userType,
userGroups,
validatorName): AuthorizationError;
Defined in: packages/core/src/core/authz/authErrors.ts:129
Create error for access requirements mismatch
Parameters
requiredAccess
string
userType
string
userGroups
string[]
validatorName
string
Returns
andModeFailure()
static andModeFailure(
failedValidator,
userType?,
userGroups?): AuthorizationError;
Defined in: packages/core/src/core/authz/authErrors.ts:185
Create error for AND mode validation failure
Parameters
failedValidator
name
string
reason
string
userType?
string
userGroups?
string[]
Returns
groupMismatch()
static groupMismatch(
requiredGroups,
actualGroups,
validatorName,
userType?): AuthorizationError;
Defined in: packages/core/src/core/authz/authErrors.ts:108
Create error for group mismatch
Parameters
requiredGroups
string[]
actualGroups
string[]
validatorName
string
userType?
string
Returns
missingUserContext()
static missingUserContext(validatorName): AuthorizationError;
Defined in: packages/core/src/core/authz/authErrors.ts:149
Create error for missing user context
Parameters
validatorName
string
Returns
orModeFailure()
static orModeFailure(
validators,
userType?,
userGroups?): AuthorizationError;
Defined in: packages/core/src/core/authz/authErrors.ts:160
Create error for OR mode validation failure
Parameters
validators
object[]
userType?
string
userGroups?
string[]
Returns
userTypeMismatch()
static userTypeMismatch(
required,
actual,
validatorName): AuthorizationError;
Defined in: packages/core/src/core/authz/authErrors.ts:92
Create error for user type mismatch
Parameters
required
string[]
actual
string
validatorName
string
Returns
AuthorizationError
Defined in: packages/core/src/core/authz/authErrors.ts:22
Authorization error class with detailed information
Extends
Error
Constructors
Constructor
new AuthorizationError(message, details): AuthorizationError;
Defined in: packages/core/src/core/authz/authErrors.ts:27
Parameters
message
string
details
Returns
Overrides
Error.constructor
Properties
code
readonly code: "NOT_AUTHORIZED" = "NOT_AUTHORIZED";
Defined in: packages/core/src/core/authz/authErrors.ts:23
details
readonly details: AuthErrorDetails;
Defined in: packages/core/src/core/authz/authErrors.ts:25
message
message: string;
Defined in: node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es5.d.ts:1077
Inherited from
Error.message
name
name: string;
Defined in: node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es5.d.ts:1076
Inherited from
Error.name
stack?
optional stack: string;
Defined in: node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es5.d.ts:1078
Inherited from
Error.stack
statusCode
readonly statusCode: 403 = 403;
Defined in: packages/core/src/core/authz/authErrors.ts:24
Methods
toClientResponse()
toClientResponse(): object;
Defined in: packages/core/src/core/authz/authErrors.ts:57
Get a safe error response for client (without sensitive details)
Returns
object
code
code: string;
error
error: string;
message
message: string;
toFullResponse()
toFullResponse(): object;
Defined in: packages/core/src/core/authz/authErrors.ts:68
Get full error details (for internal logging/debugging)
Returns
object
code
code: string;
details
details: AuthErrorDetails;
error
error: string;
message
message: string;
statusCode
statusCode: number;
toLogString()
toLogString(): string;
Defined in: packages/core/src/core/authz/authErrors.ts:41
Get a formatted error message for logging
Returns
string
Interfaces
AuthConfigOptions
Defined in: packages/core/src/core/authz/authConfig.ts:36
Global configuration options
Properties
cacheMaxSize?
optional cacheMaxSize: number;
Defined in: packages/core/src/core/authz/authConfig.ts:78
Maximum number of cache entries Default: 1000
cacheTTL?
optional cacheTTL: number;
Defined in: packages/core/src/core/authz/authConfig.ts:72
Cache TTL in milliseconds Default: 60000 (1 minute)
cacheValidationResults?
optional cacheValidationResults: boolean;
Defined in: packages/core/src/core/authz/authConfig.ts:66
Enable caching of validation results Default: false
enableAuditLog?
optional enableAuditLog: boolean;
Defined in: packages/core/src/core/authz/authConfig.ts:60
Enable audit logging for all auth decisions Default: false Note: Logging implementation will be added in future
environment?
optional environment: string;
Defined in: packages/core/src/core/authz/authConfig.ts:84
Environment (used for conditional behavior) Default: process.env.NODE_ENV
errorHandler?
optional errorHandler: AuthErrorHandler;
Defined in: packages/core/src/core/authz/authConfig.ts:53
Custom error handler Default: uses core error handler
onUnauthorized?
optional onUnauthorized: UnauthorizedTracker;
Defined in: packages/core/src/core/authz/authConfig.ts:104
Callback invoked on every unauthorized request. Receives the original request and the AuthorizationError. Errors thrown inside this callback are silently swallowed.
Example
AuthConfig.configure({
onUnauthorized: async (req, error) => {
await auditService.log({
userId: req.user?.id,
path: req.path,
reason: error.details.failedValidator,
});
},
});
userContextExtractor?
optional userContextExtractor: UserContextExtractor;
Defined in: packages/core/src/core/authz/authConfig.ts:47
Custom function to extract user context from request If provided, overrides userObjectPath
userObjectPath?
optional userObjectPath: string;
Defined in: packages/core/src/core/authz/authConfig.ts:41
Path to user object in request (e.g., "user", "session.user") Default: "user"
AuthErrorDetails
Defined in: packages/core/src/core/authz/authErrors.ts:4
Detailed authorization error information
Properties
actual
actual: string;
Defined in: packages/core/src/core/authz/authErrors.ts:8
What the user actually has
context?
optional context: Record<string, any>;
Defined in: packages/core/src/core/authz/authErrors.ts:16
Additional context
failedValidator
failedValidator: string;
Defined in: packages/core/src/core/authz/authErrors.ts:10
Which decorator/validator failed
required
required: string;
Defined in: packages/core/src/core/authz/authErrors.ts:6
What authorization was required
userGroups?
optional userGroups: string[];
Defined in: packages/core/src/core/authz/authErrors.ts:14
User groups if available
userType?
optional userType: string;
Defined in: packages/core/src/core/authz/authErrors.ts:12
User type if available
DecoratorOptions
Defined in: packages/core/src/core/authz/authConfig.ts:110
Per-decorator configuration options
Extended by
Properties
auditLog?
optional auditLog: boolean;
Defined in: packages/core/src/core/authz/authConfig.ts:120
Enable audit logging for this endpoint Overrides global setting
cache?
optional cache: boolean;
Defined in: packages/core/src/core/authz/authConfig.ts:126
Enable caching for this endpoint Overrides global setting
cacheTTL?
optional cacheTTL: number;
Defined in: packages/core/src/core/authz/authConfig.ts:132
Cache TTL for this endpoint in milliseconds Overrides global setting
disabled?
optional disabled: boolean;
Defined in: packages/core/src/core/authz/authConfig.ts:142
Disable this auth check (useful for testing)
errorHandler?
optional errorHandler: AuthErrorHandler;
Defined in: packages/core/src/core/authz/authConfig.ts:137
Custom error handler for this endpoint
errorMessage?
optional errorMessage: string;
Defined in: packages/core/src/core/authz/authConfig.ts:114
Custom error message for this endpoint
HasPermissionsOptions
Defined in: packages/core/src/core/authz/authConfig.ts:149
Options specific to the HasPermissions decorator. Extends DecoratorOptions with permission-pattern-related settings.
Extends
Properties
auditLog?
optional auditLog: boolean;
Defined in: packages/core/src/core/authz/authConfig.ts:120
Enable audit logging for this endpoint Overrides global setting
Inherited from
cache?
optional cache: boolean;
Defined in: packages/core/src/core/authz/authConfig.ts:126
Enable caching for this endpoint Overrides global setting
Inherited from
cacheTTL?
optional cacheTTL: number;
Defined in: packages/core/src/core/authz/authConfig.ts:132
Cache TTL for this endpoint in milliseconds Overrides global setting
Inherited from
disabled?
optional disabled: boolean;
Defined in: packages/core/src/core/authz/authConfig.ts:142
Disable this auth check (useful for testing)
Inherited from
errorHandler?
optional errorHandler: AuthErrorHandler;
Defined in: packages/core/src/core/authz/authConfig.ts:137
Custom error handler for this endpoint
Inherited from
errorMessage?
optional errorMessage: string;
Defined in: packages/core/src/core/authz/authConfig.ts:114
Custom error message for this endpoint
Inherited from
separator?
optional separator: string;
Defined in: packages/core/src/core/authz/authConfig.ts:161
Separator character for permission patterns with wildcards. Default: ":"
Example
// With default separator ":"
@HasPermissions(["idm:user:*"]) // matches idm:user:read, idm:user:write
// With custom separator "."
@HasPermissions(["idm.user.*"], { separator: "." }) // matches idm.user.read
UserCacheContext
Defined in: packages/core/src/core/authz/authCacheUtils.ts:8
User context for cache key generation
Properties
groups?
optional groups: string[];
Defined in: packages/core/src/core/authz/authCacheUtils.ts:11
userId?
optional userId: string;
Defined in: packages/core/src/core/authz/authCacheUtils.ts:9
userType?
optional userType: string;
Defined in: packages/core/src/core/authz/authCacheUtils.ts:10
ValidationResult
Defined in: packages/core/src/core/authz/authOrchestrator.ts:10
Result from an authorization validator
Properties
passed
passed: boolean;
Defined in: packages/core/src/core/authz/authOrchestrator.ts:11
reason?
optional reason: string;
Defined in: packages/core/src/core/authz/authOrchestrator.ts:12
ValidatorMetadata
Defined in: packages/core/src/core/authz/authOrchestrator.ts:27
Type definition for validator metadata stored on methods.
Properties
name
name: string;
Defined in: packages/core/src/core/authz/authOrchestrator.ts:28
options?
optional options: DecoratorOptions;
Defined in: packages/core/src/core/authz/authOrchestrator.ts:30
validator
validator: AuthValidator;
Defined in: packages/core/src/core/authz/authOrchestrator.ts:29
Type Aliases
AuthErrorHandler()
type AuthErrorHandler = (res, error) => void;
Defined in: packages/core/src/core/authz/authConfig.ts:18
Error handler function type
Parameters
res
error
Returns
void
AuthValidator()
type AuthValidator = (req) =>
| ValidationResult
| Promise<ValidationResult>;
Defined in: packages/core/src/core/authz/authOrchestrator.ts:20
Type definition for an authorization validator function. Returns validation result with pass/fail and optional reason. Can be async for validators that need to perform async operations.
Parameters
req
Returns
| ValidationResult
| Promise<ValidationResult>
UnauthorizedTracker()
type UnauthorizedTracker = (req, error) => void | Promise<void>;
Defined in: packages/core/src/core/authz/authConfig.ts:10
Callback invoked whenever an authorization check fails. Receives the original request and the full authorization error. Use this to write audit logs, database records, metrics, etc.
Parameters
req
error
Returns
void | Promise<void>
UserContextExtractor()
type UserContextExtractor = (req) =>
| {
[key: string]: any;
groups?: (
| {
name: string;
}
| string)[];
userType?: string;
}
| null;
Defined in: packages/core/src/core/authz/authConfig.ts:27
User context extractor function Allows custom logic for extracting user from request
Parameters
req
Returns
| {
[key: string]: any;
groups?: (
| {
name: string;
}
| string)[];
userType?: string;
}
| null
Variables
authCache
const authCache: Cache<ValidationResult>;
Defined in: packages/core/src/core/authz/authCacheUtils.ts:104
Singleton cache instance for authorization results. Use this instance throughout your application.
Example
import { authCache } from '@giusmento/mangojs-core';
// Get cache statistics
const stats = authCache.getStats();
// Clear cache for specific user
import { clearUserCache } from '@giusmento/mangojs-core';
clearUserCache(authCache, 'user-123');
// Clear entire cache
authCache.clear();
defaultUserContextExtractor
const defaultUserContextExtractor: UserContextExtractor;
Defined in: packages/core/src/core/authz/authConfig.ts:417
Default user context extractor Extracts user from req.user (standard Express pattern)
Functions
clearUserCache()
function clearUserCache(cache, userId): number;
Defined in: packages/core/src/core/authz/authCacheUtils.ts:78
Clear cache entries for a specific user. Useful when user permissions change.
Parameters
cache
Cache instance to clear from
userId
string
User identifier
Returns
number
Number of entries removed
createAuthOrchestrator()
function createAuthOrchestrator(
validators,
useOrMode,
methodName): (req, res, next) => Promise<void>;
Defined in: packages/core/src/core/authz/authOrchestrator.ts:42
Creates an orchestrator middleware that runs multiple authorization validators with either AND or OR logic.
Parameters
validators
Array of validator functions to run
useOrMode
boolean
If true, use OR logic (at least one passes); if false, use AND logic (all must pass)
methodName
Name of the method being protected (for logging)
string | symbol
Returns
Express middleware function
(
req,
res,
next): Promise<void>;
Parameters
req
Request
res
Response
next
NextFunction
Returns
Promise<void>
generateCacheKey()
function generateCacheKey(
userContext,
methodName,
validatorName): string;
Defined in: packages/core/src/core/authz/authCacheUtils.ts:48
Generate cache key for validation result.
The cache key is composed of:
- User identifier (userId or 'anonymous')
- User type
- Groups hash (MD5 hash of sorted groups for consistent key)
- Method name
- Validator name
This ensures that:
- Different users get different cache entries
- Same user with different permissions gets different cache entries
- Same validation on different methods uses different cache entries
Parameters
userContext
User context information
methodName
Method/endpoint name
string | symbol
validatorName
string
Name of the validator
Returns
string
Cache key string
Example
const key = generateCacheKey(
{
userId: '123',
userType: 'PARTNER',
groups: ['partner_admin', 'partner_user']
},
'getPartnerUsers',
'HasUserType([PARTNER])'
);
// Result: "auth:user:123:PARTNER:a1b2c3d4:getPartnerUsers:HasUserType([PARTNER])"