@opensourcekd/ng-common-libs 1.2.3 → 1.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,691 +1,349 @@
1
- import { Observable } from 'rxjs';
2
- import { CanActivateFn } from '@angular/router';
3
- import { HttpInterceptorFn, HttpErrorResponse } from '@angular/common/http';
1
+ import { HttpClient } from '@angular/common/http';
2
+ import { ReplaySubject, Observable } from 'rxjs';
3
+ import { EventType } from 'mitt';
4
4
 
5
5
  /**
6
- * Event payload interface
7
- */
8
- interface EventPayload<T = any> {
9
- type: string;
10
- data: T;
11
- timestamp?: number;
12
- }
13
- /**
14
- * EventBus - A centralized event bus for application-wide communication
15
- * Framework-agnostic implementation using only RxJS
6
+ * EventBusService - Angular service for cross-application event communication
7
+ * Uses mitt library for efficient event handling and RxJS ReplaySubject for observable stream
16
8
  *
17
- * @example
18
- * ```typescript
19
- * // Create an instance
20
- * const eventBus = new EventBus();
21
- *
22
- * // Emit an event
23
- * eventBus.emit('user:login', { userId: '123', username: 'john' });
24
- *
25
- * // Subscribe to an event
26
- * eventBus.on('user:login').subscribe(data => {
27
- * console.log('User logged in:', data);
28
- * });
29
- * ```
30
- */
31
- declare class EventBus {
32
- private eventSubject;
33
- /**
34
- * Emit an event with optional data
35
- * @param eventType - The type/name of the event
36
- * @param data - Optional data to send with the event
37
- */
38
- emit<T = any>(eventType: string, data?: T): void;
39
- /**
40
- * Subscribe to a specific event type
41
- * @param eventType - The type/name of the event to listen for
42
- * @returns Observable that emits the event data
43
- */
44
- on<T = any>(eventType: string): Observable<T>;
45
- /**
46
- * Subscribe to multiple event types
47
- * @param eventTypes - Array of event types to listen for
48
- * @returns Observable that emits the full event payload
49
- */
50
- onMultiple(eventTypes: string[]): Observable<EventPayload>;
51
- /**
52
- * Subscribe to all events
53
- * @returns Observable that emits all event payloads
54
- */
55
- onAll(): Observable<EventPayload>;
56
- }
57
-
58
- /**
59
- * NgEventEmitter - Angular service wrapper for EventBus
60
- * Provides Angular dependency injection support for the framework-agnostic EventBus
9
+ * This service is designed for MicroFrontend architectures where different apps need to communicate
10
+ * The ReplaySubject keeps last 100 events in memory for late subscribers
61
11
  *
62
12
  * @example
63
13
  * ```typescript
64
- * import { Component, inject } from '@angular/core';
65
- * import { NgEventEmitter } from 'common-libs';
14
+ * import { Component, inject, OnInit } from '@angular/core';
15
+ * import { EventBusService } from '@opensourcekd/ng-common-libs';
66
16
  *
67
17
  * @Component({
68
18
  * selector: 'app-example',
69
19
  * template: '...'
70
20
  * })
71
- * export class ExampleComponent {
72
- * private eventEmitter = inject(NgEventEmitter);
21
+ * export class ExampleComponent implements OnInit {
22
+ * private eventBus = inject(EventBusService);
73
23
  *
74
24
  * ngOnInit() {
75
- * this.eventEmitter.on('user:login').subscribe(data => {
76
- * console.log('User logged in:', data);
25
+ * // Subscribe to all events
26
+ * this.eventBus.onePlusNEvents.subscribe(event => {
27
+ * console.log('Event received:', event);
77
28
  * });
78
29
  * }
79
30
  *
80
- * login() {
81
- * this.eventEmitter.emit('user:login', { userId: '123' });
82
- * }
83
- * }
84
- * ```
85
- */
86
- declare class NgEventEmitter extends EventBus {
87
- constructor();
88
- }
89
-
90
- /**
91
- * Token configuration interface
92
- */
93
- interface TokenConfig {
94
- tokenKey?: string;
95
- refreshTokenKey?: string;
96
- useSessionStorage?: boolean;
97
- }
98
- /**
99
- * TokenManager - Manages authentication tokens
100
- * Framework-agnostic implementation using browser storage APIs
101
- * Handles storage, retrieval, and validation of JWT tokens
102
- *
103
- * @example
104
- * ```typescript
105
- * const tokenManager = new TokenManager();
106
- *
107
- * // Store a token
108
- * tokenManager.setToken('your-jwt-token');
109
- *
110
- * // Check if authenticated
111
- * if (tokenManager.isAuthenticated()) {
112
- * const userData = tokenManager.getUserFromToken();
113
- * }
114
- * ```
115
- */
116
- declare class TokenManager {
117
- private TOKEN_KEY;
118
- private REFRESH_TOKEN_KEY;
119
- private useSessionStorage;
120
- /**
121
- * Configure token manager
122
- */
123
- configure(config: TokenConfig): void;
124
- /**
125
- * Get the storage mechanism based on configuration
126
- */
127
- private getStorage;
128
- /**
129
- * Set authentication token
130
- */
131
- setToken(token: string): void;
132
- /**
133
- * Get authentication token
134
- */
135
- getToken(): string | null;
136
- /**
137
- * Remove authentication token
138
- */
139
- removeToken(): void;
140
- /**
141
- * Set refresh token
142
- */
143
- setRefreshToken(token: string): void;
144
- /**
145
- * Get refresh token
146
- */
147
- getRefreshToken(): string | null;
148
- /**
149
- * Remove refresh token
150
- */
151
- removeRefreshToken(): void;
152
- /**
153
- * Clear all tokens
154
- */
155
- clearTokens(): void;
156
- /**
157
- * Check if token exists
158
- */
159
- hasToken(): boolean;
160
- /**
161
- * Decode JWT token (without verification)
162
- * @param token - JWT token to decode
163
- * @returns Decoded token payload or null if invalid
164
- */
165
- decodeToken(token?: string): any;
166
- /**
167
- * Check if token is expired
168
- * @param token - Optional token to check (defaults to stored token)
169
- * @returns true if token is expired or invalid
170
- */
171
- isTokenExpired(token?: string): boolean;
172
- /**
173
- * Check if user is authenticated (has valid, non-expired token)
174
- */
175
- isAuthenticated(): boolean;
176
- /**
177
- * Get token expiration date
178
- */
179
- getTokenExpirationDate(token?: string): Date | null;
180
- /**
181
- * Get user data from token
182
- */
183
- getUserFromToken(token?: string): any;
184
- }
185
-
186
- /**
187
- * TokenService - Angular service wrapper for TokenManager
188
- * Provides Angular dependency injection support for the framework-agnostic TokenManager
189
- *
190
- * @example
191
- * ```typescript
192
- * import { Component, inject } from '@angular/core';
193
- * import { TokenService } from 'common-libs';
194
- *
195
- * export class AuthService {
196
- * private tokenService = inject(TokenService);
197
- *
198
- * login(token: string) {
199
- * this.tokenService.setToken(token);
200
- * }
31
+ * sendCustomEvent() {
32
+ * // Send a custom event
33
+ * this.eventBus.sendEvent('user:action');
201
34
  *
202
- * isAuthenticated(): boolean {
203
- * return this.tokenService.isAuthenticated();
35
+ * // Or send structured event with data
36
+ * this.eventBus.sendEvent(JSON.stringify({
37
+ * type: 'user:login',
38
+ * payload: { userId: '123' },
39
+ * timestamp: new Date().toISOString()
40
+ * }));
204
41
  * }
205
42
  * }
206
43
  * ```
207
44
  */
208
- declare class TokenService extends TokenManager {
209
- constructor();
210
- }
211
-
212
- /**
213
- * StorageManager - Type-safe wrapper for browser storage
214
- * Framework-agnostic implementation using browser storage APIs
215
- * Provides JSON serialization/deserialization and error handling
216
- *
217
- * @example
218
- * ```typescript
219
- * const storage = new StorageManager();
220
- *
221
- * // Store data
222
- * storage.setLocal('user-prefs', { theme: 'dark', lang: 'en' });
223
- *
224
- * // Retrieve data
225
- * const prefs = storage.getLocal('user-prefs');
226
- *
227
- * // With expiration
228
- * storage.setWithExpiration('temp-data', someData, 3600000); // 1 hour
229
- * ```
230
- */
231
- declare class StorageManager {
232
- /**
233
- * Set item in localStorage with JSON serialization
234
- */
235
- setLocal<T>(key: string, value: T): boolean;
236
- /**
237
- * Get item from localStorage with JSON deserialization
238
- */
239
- getLocal<T>(key: string, defaultValue?: T): T | null;
240
- /**
241
- * Remove item from localStorage
242
- */
243
- removeLocal(key: string): void;
244
- /**
245
- * Clear all localStorage items
246
- */
247
- clearLocal(): void;
248
- /**
249
- * Check if key exists in localStorage
250
- */
251
- hasLocal(key: string): boolean;
252
- /**
253
- * Get all localStorage keys
254
- */
255
- getLocalKeys(): string[];
256
- /**
257
- * Set item in sessionStorage with JSON serialization
258
- */
259
- setSession<T>(key: string, value: T): boolean;
260
- /**
261
- * Get item from sessionStorage with JSON deserialization
262
- */
263
- getSession<T>(key: string, defaultValue?: T): T | null;
264
- /**
265
- * Remove item from sessionStorage
266
- */
267
- removeSession(key: string): void;
268
- /**
269
- * Clear all sessionStorage items
270
- */
271
- clearSession(): void;
272
- /**
273
- * Check if key exists in sessionStorage
274
- */
275
- hasSession(key: string): boolean;
276
- /**
277
- * Get all sessionStorage keys
278
- */
279
- getSessionKeys(): string[];
45
+ declare class EventBusService {
280
46
  /**
281
- * Set item with expiration time
282
- * @param key - Storage key
283
- * @param value - Value to store
284
- * @param expirationMs - Expiration time in milliseconds
285
- * @param useSession - Use sessionStorage instead of localStorage
47
+ * ReplaySubject that buffers the last 100 events for late subscribers
48
+ * Subscribe to this observable to receive all events
286
49
  */
287
- setWithExpiration<T>(key: string, value: T, expirationMs: number, useSession?: boolean): boolean;
50
+ onePlusNEvents: ReplaySubject<EventType>;
288
51
  /**
289
- * Get item with expiration check
290
- * Returns null if item is expired
52
+ * mitt event emitter instance
53
+ * Lightweight event emitter library
291
54
  */
292
- getWithExpiration<T>(key: string, useSession?: boolean): T | null;
293
- }
294
-
295
- /**
296
- * StorageService - Angular service wrapper for StorageManager
297
- * Provides Angular dependency injection support for the framework-agnostic StorageManager
298
- *
299
- * @example
300
- * ```typescript
301
- * import { Component, inject } from '@angular/core';
302
- * import { StorageService } from 'common-libs';
303
- *
304
- * export class UserPreferencesService {
305
- * private storage = inject(StorageService);
306
- *
307
- * savePreferences(prefs: any) {
308
- * this.storage.setLocal('user-prefs', prefs);
309
- * }
310
- *
311
- * getPreferences() {
312
- * return this.storage.getLocal('user-prefs');
313
- * }
314
- * }
315
- * ```
316
- */
317
- declare class StorageService extends StorageManager {
55
+ private emitter;
318
56
  constructor();
57
+ /**
58
+ * Send an event through the event bus
59
+ * The event will be forwarded to all subscribers via the ReplaySubject
60
+ *
61
+ * @param s - Event string, can be a simple event name or JSON stringified structured data
62
+ *
63
+ * @example
64
+ * ```typescript
65
+ * // Simple event
66
+ * eventBus.sendEvent('user:logout');
67
+ *
68
+ * // Structured event
69
+ * eventBus.sendEvent(JSON.stringify({
70
+ * type: 'auth:token_updated',
71
+ * payload: { token: 'abc123' },
72
+ * timestamp: new Date().toISOString()
73
+ * }));
74
+ * ```
75
+ */
76
+ sendEvent(s: string): void;
319
77
  }
320
78
 
321
79
  /**
322
- * Log level enum
323
- */
324
- declare enum LogLevel {
325
- DEBUG = 0,
326
- INFO = 1,
327
- WARN = 2,
328
- ERROR = 3,
329
- NONE = 4
80
+ * User information from ID token
81
+ * Standard OIDC claims compatible with Auth0
82
+ */
83
+ interface UserInfo {
84
+ sub: string;
85
+ name?: string;
86
+ email?: string;
87
+ email_verified?: boolean;
88
+ preferred_username?: string;
89
+ given_name?: string;
90
+ family_name?: string;
91
+ nickname?: string;
92
+ locale?: string;
93
+ picture?: string;
94
+ phone?: string;
95
+ phone_verified?: boolean;
96
+ updated_at?: string;
97
+ role?: string;
98
+ org?: string;
99
+ organization?: string;
100
+ [key: string]: any;
330
101
  }
331
102
  /**
332
- * Logger configuration
103
+ * Simplified user data extracted from token
333
104
  */
334
- interface LoggerConfig {
335
- level?: LogLevel;
336
- enableTimestamp?: boolean;
337
- enableStackTrace?: boolean;
338
- prefix?: string;
105
+ interface UserData {
106
+ id: string;
107
+ name: string;
108
+ email: string;
109
+ role: string;
110
+ org: string;
339
111
  }
340
112
  /**
341
- * Logger - Centralized logging utility
342
- * Framework-agnostic implementation using browser console APIs
343
- * Supports different log levels and can be configured globally
344
- *
345
- * @example
346
- * ```typescript
347
- * const logger = new Logger();
113
+ * Authentication service for Auth0 integration
114
+ * Handles login, logout, token management, and user session
115
+ * Uses sessionStorage for sensitive data and emits authentication events for MicroApps
348
116
  *
349
- * // Configure
350
- * logger.configure({
351
- * level: LogLevel.DEBUG,
352
- * enableTimestamp: true,
353
- * prefix: 'MyApp'
354
- * });
117
+ * Configuration is centralized in config/auth.config.ts for easy management
355
118
  *
356
- * // Use
357
- * logger.info('User logged in', { userId: '123' });
358
- * logger.error('Failed to load data', error);
359
- * ```
119
+ * NOTE: All navigation logic using setTimeout is commented out as per requirements.
120
+ * To enable navigation after auth operations, uncomment the marked sections in consuming components.
360
121
  */
361
- declare class Logger {
362
- private config;
122
+ declare class AuthService {
123
+ private http;
124
+ private eventBus;
125
+ id: string;
126
+ private readonly STANDARD_JWT_CLAIMS;
127
+ private auth0Client;
128
+ private initializationPromise;
129
+ private userSubject;
130
+ user$: Observable<UserInfo | null>;
131
+ constructor(http: HttpClient, eventBus: EventBusService);
363
132
  /**
364
- * Configure the logger
133
+ * Initialize Auth0 client
365
134
  */
366
- configure(config: LoggerConfig): void;
135
+ private initializeAuth0;
367
136
  /**
368
- * Set log level
137
+ * Ensure Auth0 client is initialized before use
369
138
  */
370
- setLevel(level: LogLevel): void;
139
+ private ensureInitialized;
371
140
  /**
372
- * Get current log level
141
+ * Login with Auth0
142
+ * Redirects to Auth0 Universal Login
143
+ * Preserves current URL parameters (like invitation tokens) through the auth flow
144
+ *
145
+ * @param user - Optional user identifier for logging
146
+ * @param options - Optional login options including invitation and organization parameters
373
147
  */
374
- getLevel(): LogLevel;
148
+ login(user?: string, options?: {
149
+ invitation?: string;
150
+ organization?: string;
151
+ }): Promise<void>;
375
152
  /**
376
- * Format log message with timestamp and prefix
153
+ * Handle OAuth2 callback after successful authorization
154
+ * Processes the callback and retrieves user info
155
+ *
156
+ * NOTE: Navigation after successful/failed authentication should be handled in the calling component
157
+ * using setTimeout. See commented examples in app.component.ts
158
+ *
159
+ * @returns Promise<{ success: boolean, appState?: any }> - Success status and preserved appState
377
160
  */
378
- private formatMessage;
161
+ handleCallback(): Promise<{
162
+ success: boolean;
163
+ appState?: any;
164
+ }>;
379
165
  /**
380
- * Check if log level should be logged
166
+ * Log all user claims for debugging
167
+ * @param user - User info from Auth0
381
168
  */
382
- private shouldLog;
169
+ private logUserClaims;
383
170
  /**
384
- * Log debug message
171
+ * Log standard OIDC claims
172
+ * @param user - User info from Auth0
385
173
  */
386
- debug(message: string, ...args: any[]): void;
174
+ private logStandardClaims;
387
175
  /**
388
- * Log info message
176
+ * Log claims with consistent formatting
177
+ * @param header - Section header to display
178
+ * @param claims - Array of claim keys to log
179
+ * @param user - User info object
389
180
  */
390
- info(message: string, ...args: any[]): void;
181
+ private logClaims;
391
182
  /**
392
- * Log warning message
183
+ * Get custom namespaced claims from user info
184
+ * @param user - User info object
185
+ * @returns Array of custom claim keys
393
186
  */
394
- warn(message: string, ...args: any[]): void;
187
+ private getCustomClaims;
395
188
  /**
396
- * Log error message
189
+ * Get additional non-namespaced claims from user info
190
+ * @param user - User info object
191
+ * @returns Array of additional claim keys
397
192
  */
398
- error(message: string, error?: any, ...args: any[]): void;
193
+ private getAdditionalClaims;
399
194
  /**
400
- * Log a group of messages
195
+ * Check if a claim key is namespaced
196
+ * @param key - Claim key to check
197
+ * @returns True if the key starts with http:// or https://
401
198
  */
402
- group(label: string, callback: () => void): void;
199
+ private isNamespacedClaim;
403
200
  /**
404
- * Log a collapsed group of messages
201
+ * Logout user and clear authentication state
202
+ * Redirects to Auth0 logout endpoint and clears local state
405
203
  */
406
- groupCollapsed(label: string, callback: () => void): void;
204
+ logout(): Promise<void>;
407
205
  /**
408
- * Log a table (useful for arrays of objects)
206
+ * Get current access token from storage or Auth0 client
207
+ * @returns string | null - Access token or null if not authenticated
409
208
  */
410
- table(data: any, columns?: string[]): void;
209
+ getToken(): Promise<string | null>;
411
210
  /**
412
- * Log execution time of a function
211
+ * Get current access token synchronously from storage only
212
+ * Use this for synchronous operations like interceptors
213
+ * @returns string | null - Access token or null if not authenticated
413
214
  */
414
- time<T>(label: string, fn: () => Promise<T> | T): Promise<T>;
415
- }
416
-
417
- /**
418
- * LoggerService - Angular service wrapper for Logger
419
- * Provides Angular dependency injection support for the framework-agnostic Logger
420
- *
421
- * @example
422
- * ```typescript
423
- * import { Component, inject } from '@angular/core';
424
- * import { LoggerService, LogLevel } from 'common-libs';
425
- *
426
- * export class MyService {
427
- * private logger = inject(LoggerService);
428
- *
429
- * constructor() {
430
- * this.logger.configure({
431
- * level: LogLevel.DEBUG,
432
- * prefix: 'MyApp'
433
- * });
434
- * }
435
- *
436
- * doSomething() {
437
- * this.logger.info('Doing something');
438
- * }
439
- * }
440
- * ```
441
- */
442
- declare class LoggerService extends Logger {
443
- constructor();
444
- }
445
-
446
- /**
447
- * PermissionService - Manages user permissions and roles
448
- */
449
- declare class PermissionService {
450
- private tokenService;
215
+ getTokenSync(): string | null;
451
216
  /**
452
- * Check if user has a specific permission
217
+ * Set access token in storage and emit event for MicroApps
218
+ * @param token - Access token to store
453
219
  */
454
- hasPermission(permission: string): boolean;
220
+ private setToken;
455
221
  /**
456
- * Check if user has any of the specified permissions
222
+ * Check if user is authenticated
223
+ * @returns boolean - True if user has valid token
457
224
  */
458
- hasAnyPermission(permissions: string[]): boolean;
225
+ isAuthenticated(): Promise<boolean>;
459
226
  /**
460
- * Check if user has all of the specified permissions
227
+ * Check if user is authenticated synchronously
228
+ * Only checks storage, doesn't verify with Auth0
229
+ * @returns boolean - True if user has token in storage
461
230
  */
462
- hasAllPermissions(permissions: string[]): boolean;
231
+ isAuthenticatedSync(): boolean;
463
232
  /**
464
- * Check if user has a specific role
233
+ * Get current user information
234
+ * @returns UserInfo | null - Current user or null if not authenticated
465
235
  */
466
- hasRole(role: string): boolean;
236
+ getUser(): UserInfo | null;
467
237
  /**
468
- * Check if user has any of the specified roles
238
+ * Get simplified user data from token
239
+ * Extracts user details, role, and organization from ID token claims
240
+ * Checks both top-level claims and namespaced custom claims
241
+ * @returns UserData | null - Simplified user data or null if not authenticated
469
242
  */
470
- hasAnyRole(roles: string[]): boolean;
243
+ getUserData(): UserData | null;
471
244
  /**
472
- * Check if user has all of the specified roles
245
+ * Extract claim value from user info, checking both direct properties and namespaced custom claims
246
+ * @param userInfo - User info object
247
+ * @param claimNames - Single claim name or array of claim names to search for
248
+ * @param defaultValue - Default value if claim is not found
249
+ * @returns Extracted claim value or default value
473
250
  */
474
- hasAllRoles(roles: string[]): boolean;
251
+ private extractClaimValue;
475
252
  /**
476
- * Get all user permissions
253
+ * Get user information from storage
254
+ * @returns UserInfo | null - Stored user info or null
477
255
  */
478
- getPermissions(): string[];
256
+ private getUserInfoFromStorage;
479
257
  /**
480
- * Get all user roles
258
+ * Set user information in storage, update observable and emit event for MicroApps
259
+ * Logs all Auth0 claims for debugging
260
+ * @param userInfo - User information to store
481
261
  */
482
- getRoles(): string[];
262
+ private setUserInfo;
483
263
  /**
484
- * Get user ID from token
264
+ * Emit authentication event for MicroApps to consume
265
+ * Events are emitted via EventBus for cross-MFE communication
266
+ * @param eventType - Type of authentication event
267
+ * @param payload - Event payload
485
268
  */
486
- getUserId(): string | null;
487
- /**
488
- * Get username from token
489
- */
490
- getUsername(): string | null;
491
- /**
492
- * Get user email from token
493
- */
494
- getUserEmail(): string | null;
495
- }
496
-
497
- /**
498
- * Auth guard configuration
499
- */
500
- interface AuthGuardConfig {
501
- redirectUrl?: string;
502
- checkExpiration?: boolean;
503
- }
504
- /**
505
- * Factory function to create an auth guard with configuration
506
- *
507
- * @example
508
- * ```typescript
509
- * // In routes
510
- * {
511
- * path: 'dashboard',
512
- * component: DashboardComponent,
513
- * canActivate: [createAuthGuard({ redirectUrl: '/login' })]
514
- * }
515
- * ```
516
- */
517
- declare function createAuthGuard(config?: AuthGuardConfig): CanActivateFn;
518
- /**
519
- * Default auth guard - redirects to '/login' if not authenticated
520
- */
521
- declare const authGuard: CanActivateFn;
522
- /**
523
- * Permission-based guard factory
524
- * Checks if user has required permissions from token
525
- *
526
- * @example
527
- * ```typescript
528
- * {
529
- * path: 'admin',
530
- * component: AdminComponent,
531
- * canActivate: [createPermissionGuard(['admin', 'editor'])]
532
- * }
533
- * ```
534
- */
535
- declare function createPermissionGuard(requiredPermissions: string[], config?: AuthGuardConfig): CanActivateFn;
536
- /**
537
- * Role-based guard factory
538
- * Checks if user has required role from token
539
- *
540
- * @example
541
- * ```typescript
542
- * {
543
- * path: 'admin',
544
- * component: AdminComponent,
545
- * canActivate: [createRoleGuard(['admin'])]
546
- * }
547
- * ```
548
- */
549
- declare function createRoleGuard(requiredRoles: string[], config?: AuthGuardConfig): CanActivateFn;
550
-
551
- /**
552
- * Auth interceptor configuration
553
- */
554
- interface AuthInterceptorConfig {
555
- headerName?: string;
556
- tokenPrefix?: string;
557
- excludedUrls?: string[];
269
+ private emitAuthEvent;
558
270
  }
559
- /**
560
- * Configure the auth interceptor
561
- */
562
- declare function configureAuthInterceptor(config: AuthInterceptorConfig): void;
563
- /**
564
- * Auth Interceptor - Automatically adds authentication token to HTTP requests
565
- *
566
- * @example
567
- * ```typescript
568
- * // In app.config.ts
569
- * export const appConfig: ApplicationConfig = {
570
- * providers: [
571
- * provideHttpClient(
572
- * withInterceptors([authInterceptor])
573
- * )
574
- * ]
575
- * };
576
- * ```
577
- */
578
- declare const authInterceptor: HttpInterceptorFn;
579
271
 
580
272
  /**
581
- * Error handling configuration
582
- */
583
- interface ErrorHandlingConfig {
584
- enableLogging?: boolean;
585
- retryAttempts?: number;
586
- retryDelay?: number;
587
- retryStatusCodes?: number[];
588
- excludedUrls?: string[];
589
- }
590
- /**
591
- * Configure the error handling interceptor
592
- */
593
- declare function configureErrorHandling(config: ErrorHandlingConfig): void;
594
- /**
595
- * Error handling interceptor - Handles HTTP errors and retries
596
- *
597
- * @example
598
- * ```typescript
599
- * // In app.config.ts
600
- * export const appConfig: ApplicationConfig = {
601
- * providers: [
602
- * provideHttpClient(
603
- * withInterceptors([errorHandlingInterceptor])
604
- * )
605
- * ]
606
- * };
273
+ * Auth0 Configuration
274
+ * Centralized configuration for Auth0 integration
607
275
  *
608
- * // Configure retry behavior
609
- * configureErrorHandling({
610
- * retryAttempts: 3,
611
- * retryDelay: 2000,
612
- * retryStatusCodes: [500, 502, 503]
613
- * });
614
- * ```
276
+ * Environment variables are typically set in consuming applications
277
+ * Default values are provided for development/testing
615
278
  */
616
- declare const errorHandlingInterceptor: HttpInterceptorFn;
617
279
  /**
618
- * HTTP Error class with additional context
280
+ * Auth0 client configuration
281
+ * Override these values in your consuming application by setting them before importing AuthService
619
282
  */
620
- declare class HttpError extends Error {
621
- status: number;
622
- statusText: string;
623
- url: string;
624
- originalError: HttpErrorResponse;
625
- constructor(status: number, statusText: string, url: string, originalError: HttpErrorResponse);
626
- }
283
+ declare const AUTH0_CONFIG: {
284
+ domain: string;
285
+ clientId: string;
286
+ redirectUri: string;
287
+ logoutUri: string;
288
+ audience: string;
289
+ scope: string;
290
+ connection: string | undefined;
291
+ };
627
292
  /**
628
- * Parse HTTP error and return user-friendly message
293
+ * Storage configuration
294
+ * Controls where sensitive data is stored
629
295
  */
630
- declare function parseHttpError(error: HttpErrorResponse): string;
296
+ declare const STORAGE_CONFIG: {
297
+ TOKEN_STORAGE: "localStorage" | "sessionStorage";
298
+ USER_INFO_STORAGE: "localStorage" | "sessionStorage";
299
+ };
631
300
  /**
632
- * Check if error is a network error
301
+ * Storage keys for auth data
633
302
  */
634
- declare function isNetworkError(error: HttpErrorResponse): boolean;
303
+ declare const STORAGE_KEYS: {
304
+ ACCESS_TOKEN: string;
305
+ USER_INFO: string;
306
+ };
635
307
  /**
636
- * Check if error is a server error (5xx)
308
+ * Helper functions for storage operations
309
+ * These work with both localStorage and sessionStorage
637
310
  */
638
- declare function isServerError(error: HttpErrorResponse): boolean;
639
- /**
640
- * Check if error is a client error (4xx)
641
- */
642
- declare function isClientError(error: HttpErrorResponse): boolean;
643
-
644
- /**
645
- * Cache configuration
646
- */
647
- interface CacheConfig {
648
- enabled?: boolean;
649
- maxAge?: number;
650
- excludedUrls?: string[];
651
- cacheableUrls?: string[];
652
- cacheMethods?: string[];
653
- }
654
311
  /**
655
- * Configure the caching interceptor
312
+ * Get item from storage
313
+ * @param key - Storage key
314
+ * @param storageType - Type of storage to use
315
+ * @returns Stored value or null
656
316
  */
657
- declare function configureCaching(config: CacheConfig): void;
317
+ declare function getStorageItem(key: string, storageType?: 'localStorage' | 'sessionStorage'): string | null;
658
318
  /**
659
- * Clear all cached entries
319
+ * Set item in storage
320
+ * @param key - Storage key
321
+ * @param value - Value to store
322
+ * @param storageType - Type of storage to use
660
323
  */
661
- declare function clearCache(): void;
324
+ declare function setStorageItem(key: string, value: string, storageType?: 'localStorage' | 'sessionStorage'): void;
662
325
  /**
663
- * Clear cache entry for specific URL
326
+ * Remove item from storage
327
+ * @param key - Storage key
328
+ * @param storageType - Type of storage to use
664
329
  */
665
- declare function clearCacheEntry(url: string): void;
330
+ declare function removeStorageItem(key: string, storageType?: 'localStorage' | 'sessionStorage'): void;
666
331
  /**
667
- * Caching interceptor - Caches HTTP GET requests
332
+ * Configure Auth0 settings
333
+ * Call this function in your consuming application before using AuthService
668
334
  *
669
335
  * @example
670
336
  * ```typescript
671
- * // In app.config.ts
672
- * export const appConfig: ApplicationConfig = {
673
- * providers: [
674
- * provideHttpClient(
675
- * withInterceptors([cachingInterceptor])
676
- * )
677
- * ]
678
- * };
337
+ * import { configureAuth0 } from '@opensourcekd/ng-common-libs';
679
338
  *
680
- * // Configure caching
681
- * configureCaching({
682
- * enabled: true,
683
- * maxAge: 300000, // 5 minutes
684
- * cacheableUrls: ['/api/users', '/api/products']
339
+ * configureAuth0({
340
+ * domain: 'your-domain.auth0.com',
341
+ * clientId: 'your-client-id',
342
+ * audience: 'https://your-api.com'
685
343
  * });
686
344
  * ```
687
345
  */
688
- declare const cachingInterceptor: HttpInterceptorFn;
346
+ declare function configureAuth0(config: Partial<typeof AUTH0_CONFIG>): void;
689
347
 
690
- export { HttpError, LogLevel, LoggerService, NgEventEmitter, PermissionService, StorageService, TokenService, authGuard, authInterceptor, cachingInterceptor, clearCache, clearCacheEntry, configureAuthInterceptor, configureCaching, configureErrorHandling, createAuthGuard, createPermissionGuard, createRoleGuard, errorHandlingInterceptor, isClientError, isNetworkError, isServerError, parseHttpError };
691
- export type { AuthGuardConfig, AuthInterceptorConfig, CacheConfig, ErrorHandlingConfig, LoggerConfig, TokenConfig };
348
+ export { AUTH0_CONFIG, AuthService, EventBusService, STORAGE_CONFIG, STORAGE_KEYS, configureAuth0, getStorageItem, removeStorageItem, setStorageItem };
349
+ export type { UserData, UserInfo };