@opensourcekd/ng-common-libs 1.2.6 → 1.2.7

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.
package/dist/index.cjs CHANGED
@@ -284,11 +284,15 @@ function jwtDecode(token, options) {
284
284
  /**
285
285
  * Auth0 client configuration
286
286
  * Override these values in your consuming application by setting them before importing AuthService
287
+ *
288
+ * Note: redirectUri defaults to window.location.origin (base URL without path).
289
+ * Auth0 will redirect back to this URL after authentication.
290
+ * You can override this to a specific callback URL (e.g., '/auth-callback') using configureAuth0().
287
291
  */
288
292
  const AUTH0_CONFIG = {
289
293
  domain: '', // Set in consuming app: process.env['NX_AUTH0_DOMAIN'] || 'your-domain.auth0.com'
290
294
  clientId: '', // Set in consuming app: process.env['NX_AUTH0_CLIENT_ID'] || 'your-client-id'
291
- redirectUri: typeof window !== 'undefined' ? window.location.origin + '/auth-callback' : '',
295
+ redirectUri: typeof window !== 'undefined' ? window.location.origin : '',
292
296
  logoutUri: typeof window !== 'undefined' ? window.location.origin : '',
293
297
  audience: '', // Optional: Set in consuming app if using API authorization
294
298
  scope: 'openid profile email', // Default scopes
@@ -349,22 +353,55 @@ function removeStorageItem(key, storageType = 'sessionStorage') {
349
353
  storage.removeItem(key);
350
354
  }
351
355
  /**
352
- * Configure Auth0 settings
353
- * Call this function in your consuming application before using AuthService
356
+ * Configure Auth0 settings (OPTIONAL)
357
+ * Call this function in your consuming application to override default Auth0 configuration.
358
+ * Only the values you provide will be overridden; all other defaults remain unchanged.
359
+ *
360
+ * Note: This function is optional. If not called, default values will be used.
361
+ *
362
+ * @param config - Partial Auth0 configuration object with values to override
354
363
  *
355
364
  * @example
356
365
  * ```typescript
357
366
  * import { configureAuth0 } from '@opensourcekd/ng-common-libs';
358
367
  *
368
+ * // Only override specific values - others keep their defaults
359
369
  * configureAuth0({
360
370
  * domain: 'your-domain.auth0.com',
361
371
  * clientId: 'your-client-id',
362
372
  * audience: 'https://your-api.com'
373
+ * // redirectUri, logoutUri, scope, etc. will use defaults
374
+ * });
375
+ *
376
+ * // Or override just redirectUri to use a specific callback page
377
+ * configureAuth0({
378
+ * redirectUri: window.location.origin + '/auth-callback'
363
379
  * });
364
380
  * ```
365
381
  */
366
382
  function configureAuth0(config) {
383
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
384
+ console.log('[AuthConfig] 🔍 DEBUG: configureAuth0() called with config:', {
385
+ domain: config.domain || 'not provided',
386
+ clientId: config.clientId ? '[REDACTED]' : 'not provided',
387
+ redirectUri: config.redirectUri || 'not provided',
388
+ logoutUri: config.logoutUri || 'not provided',
389
+ audience: config.audience || 'not provided',
390
+ scope: config.scope || 'not provided',
391
+ connection: config.connection || 'not provided'
392
+ });
393
+ // Only override provided values, keeping defaults for others
367
394
  Object.assign(AUTH0_CONFIG, config);
395
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
396
+ console.log('[AuthConfig] 🔍 DEBUG: AUTH0_CONFIG after merge:', {
397
+ domain: AUTH0_CONFIG.domain,
398
+ clientId: AUTH0_CONFIG.clientId ? '[REDACTED]' : undefined,
399
+ redirectUri: AUTH0_CONFIG.redirectUri,
400
+ logoutUri: AUTH0_CONFIG.logoutUri,
401
+ audience: AUTH0_CONFIG.audience || 'not set',
402
+ scope: AUTH0_CONFIG.scope,
403
+ connection: AUTH0_CONFIG.connection || 'not set'
404
+ });
368
405
  }
369
406
 
370
407
  /**
@@ -393,6 +430,8 @@ exports.AuthService = class AuthService {
393
430
  constructor(eventBus) {
394
431
  this.eventBus = eventBus;
395
432
  console.log("[AuthService] Initializing Auth0 authentication service");
433
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
434
+ console.log('[AuthService] 🔍 DEBUG: Constructor called, starting initialization');
396
435
  this.initializationPromise = this.initializeAuth0();
397
436
  }
398
437
  /**
@@ -401,13 +440,30 @@ exports.AuthService = class AuthService {
401
440
  async initializeAuth0() {
402
441
  try {
403
442
  console.log("[AuthService] Starting Auth0 client initialization...");
443
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
444
+ console.log('[AuthService] 🔍 DEBUG: initializeAuth0 called');
404
445
  // Defensive check for AUTH0_CONFIG
405
446
  if (!AUTH0_CONFIG || typeof AUTH0_CONFIG !== 'object') {
447
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
448
+ console.error('[AuthService] 🔍 DEBUG: AUTH0_CONFIG validation failed - invalid or undefined');
406
449
  throw new Error('[AuthService] AUTH0_CONFIG is not defined or invalid');
407
450
  }
408
451
  if (!AUTH0_CONFIG.domain || !AUTH0_CONFIG.clientId) {
452
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
453
+ console.error('[AuthService] 🔍 DEBUG: AUTH0_CONFIG validation failed - missing domain or clientId', {
454
+ domain: AUTH0_CONFIG.domain,
455
+ clientId: AUTH0_CONFIG.clientId ? '[REDACTED]' : undefined
456
+ });
409
457
  throw new Error('[AuthService] AUTH0_CONFIG is missing required fields (domain, clientId)');
410
458
  }
459
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
460
+ console.log('[AuthService] 🔍 DEBUG: Creating Auth0 client with config:', {
461
+ domain: AUTH0_CONFIG.domain,
462
+ clientId: AUTH0_CONFIG.clientId ? '[REDACTED]' : undefined,
463
+ redirectUri: AUTH0_CONFIG.redirectUri,
464
+ scope: AUTH0_CONFIG.scope,
465
+ audience: AUTH0_CONFIG.audience || 'not set'
466
+ });
411
467
  this.auth0Client = await oa({
412
468
  domain: AUTH0_CONFIG.domain,
413
469
  clientId: AUTH0_CONFIG.clientId,
@@ -420,9 +476,13 @@ exports.AuthService = class AuthService {
420
476
  useRefreshTokens: true, // Enable refresh tokens for better security
421
477
  });
422
478
  console.log("[AuthService] Auth0 client initialized successfully");
479
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
480
+ console.log('[AuthService] 🔍 DEBUG: Auth0 client created successfully');
423
481
  }
424
482
  catch (error) {
425
483
  console.error("[AuthService] Failed to initialize Auth0 client:", error);
484
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
485
+ console.error('[AuthService] 🔍 DEBUG: initializeAuth0 failed with error:', error);
426
486
  throw error;
427
487
  }
428
488
  }
@@ -444,21 +504,24 @@ exports.AuthService = class AuthService {
444
504
  * @param options - Optional login options including invitation and organization parameters
445
505
  */
446
506
  async login(user, options) {
507
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
508
+ console.log('[AuthService] 🔍 DEBUG: login() called', { user, options });
447
509
  if (user) {
448
510
  console.log(`[AuthService] Logging in: ${user}`);
449
511
  }
450
512
  try {
451
513
  // Ensure Auth0 client is initialized
452
514
  await this.ensureInitialized();
515
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
516
+ console.log('[AuthService] 🔍 DEBUG: Auth0 client ensured initialized for login');
453
517
  // Capture current URL search parameters to preserve through auth flow
454
- // Only capture if we're not already on the callback page
455
- const currentPath = window.location.pathname;
456
- const isCallbackPage = currentPath.includes('auth-callback');
457
518
  let appState = undefined;
458
- if (!isCallbackPage && window.location.search) {
519
+ if (window.location.search) {
459
520
  const currentSearchParams = window.location.search;
460
521
  appState = { returnTo: currentSearchParams };
461
522
  console.log('[AuthService] Preserving URL parameters through auth flow:', currentSearchParams);
523
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
524
+ console.log('[AuthService] 🔍 DEBUG: Captured URL search params for preservation:', currentSearchParams);
462
525
  }
463
526
  // Build authorization parameters
464
527
  const authorizationParams = {
@@ -476,14 +539,30 @@ exports.AuthService = class AuthService {
476
539
  authorizationParams.organization = options.organization;
477
540
  console.log('[AuthService] Including organization parameter:', options.organization);
478
541
  }
542
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
543
+ console.log('[AuthService] 🔍 DEBUG: Authorization params prepared:', {
544
+ redirect_uri: authorizationParams.redirect_uri,
545
+ scope: authorizationParams.scope,
546
+ audience: authorizationParams.audience || 'not set',
547
+ connection: authorizationParams.connection || 'not set',
548
+ invitation: authorizationParams.invitation || 'not set',
549
+ organization: authorizationParams.organization || 'not set',
550
+ hasAppState: !!appState
551
+ });
479
552
  console.log('[AuthService] Starting Auth0 login redirect...');
553
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
554
+ console.log('[AuthService] 🔍 DEBUG: About to call loginWithRedirect');
480
555
  await this.auth0Client.loginWithRedirect({
481
556
  authorizationParams,
482
557
  ...(appState && { appState })
483
558
  });
559
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
560
+ console.log('[AuthService] 🔍 DEBUG: loginWithRedirect completed (this may not be visible due to redirect)');
484
561
  }
485
562
  catch (error) {
486
563
  console.error("[AuthService] Login failed:", error);
564
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
565
+ console.error('[AuthService] 🔍 DEBUG: login() failed with error:', error);
487
566
  // Emit login failure event
488
567
  this.emitAuthEvent('login_failure', { error: error instanceof Error ? error.message : String(error) });
489
568
  throw error; // Re-throw to allow caller to handle
@@ -501,11 +580,19 @@ exports.AuthService = class AuthService {
501
580
  async handleCallback() {
502
581
  try {
503
582
  console.log("[AuthService] Processing Auth0 callback...");
583
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
584
+ console.log('[AuthService] 🔍 DEBUG: handleCallback() called');
585
+ console.log('[AuthService] 🔍 DEBUG: Current URL:', window.location.href);
586
+ console.log('[AuthService] 🔍 DEBUG: URL params:', window.location.search);
504
587
  // Ensure Auth0 client is initialized
505
588
  await this.ensureInitialized();
589
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
590
+ console.log('[AuthService] 🔍 DEBUG: Auth0 client ensured initialized for callback');
506
591
  // Process the callback
507
592
  const result = await this.auth0Client.handleRedirectCallback();
508
593
  console.log("[AuthService] Callback processed successfully");
594
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
595
+ console.log('[AuthService] 🔍 DEBUG: handleRedirectCallback result:', result);
509
596
  // Log preserved appState if present
510
597
  if (result.appState) {
511
598
  console.log('[AuthService] Restored appState from auth flow:', JSON.stringify(result.appState));
@@ -514,23 +601,35 @@ exports.AuthService = class AuthService {
514
601
  console.log('[AuthService] No appState restored (user may not have started from invitation link)');
515
602
  }
516
603
  // Get user info
604
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
605
+ console.log('[AuthService] 🔍 DEBUG: Fetching user info from Auth0');
517
606
  const user = await this.auth0Client.getUser();
518
607
  if (user) {
608
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
609
+ console.log('[AuthService] 🔍 DEBUG: User info retrieved successfully');
519
610
  this.logUserClaims(user);
520
611
  this.setUserInfo(user);
521
612
  }
522
613
  else {
523
614
  console.warn('[AuthService] No user info returned from Auth0');
615
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
616
+ console.warn('[AuthService] 🔍 DEBUG: getUser() returned null or undefined');
524
617
  // Emit login failure event
525
618
  this.emitAuthEvent('login_failure', { error: 'No user info returned from Auth0' });
526
619
  return { success: false };
527
620
  }
528
621
  // Get and store access token
622
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
623
+ console.log('[AuthService] 🔍 DEBUG: Fetching access token');
529
624
  const token = await this.auth0Client.getTokenSilently();
625
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
626
+ console.log('[AuthService] 🔍 DEBUG: Access token retrieved, length:', token?.length || 0);
530
627
  this.setToken(token);
531
628
  // Decode and print the token to console
532
629
  this.decodeAndLogToken(token);
533
630
  console.log("[AuthService] Authentication successful");
631
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
632
+ console.log('[AuthService] 🔍 DEBUG: handleCallback() completed successfully');
534
633
  // Emit login success event
535
634
  this.emitAuthEvent('login_success', { user, appState: result.appState });
536
635
  return { success: true, appState: result.appState };
@@ -538,6 +637,10 @@ exports.AuthService = class AuthService {
538
637
  catch (error) {
539
638
  console.error("[AuthService] Error processing callback:", error);
540
639
  console.error("[AuthService] Error details:", JSON.stringify(error, null, 2));
640
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
641
+ console.error('[AuthService] 🔍 DEBUG: handleCallback() failed with error:', error);
642
+ console.error('[AuthService] 🔍 DEBUG: Error type:', typeof error);
643
+ console.error('[AuthService] 🔍 DEBUG: Error stack:', error?.stack);
541
644
  // Emit login failure event
542
645
  this.emitAuthEvent('login_failure', { error: error instanceof Error ? error.message : String(error) });
543
646
  return { success: false };
@@ -644,23 +747,33 @@ exports.AuthService = class AuthService {
644
747
  * Redirects to Auth0 logout endpoint and clears local state
645
748
  */
646
749
  async logout() {
750
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
751
+ console.log('[AuthService] 🔍 DEBUG: logout() called');
647
752
  // Clear local storage
648
753
  removeStorageItem(STORAGE_KEYS.ACCESS_TOKEN, STORAGE_CONFIG.TOKEN_STORAGE);
649
754
  removeStorageItem(STORAGE_KEYS.USER_INFO, STORAGE_CONFIG.USER_INFO_STORAGE);
755
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
756
+ console.log('[AuthService] 🔍 DEBUG: Storage cleared (token and user info removed)');
650
757
  this.userSubject.next(null);
651
758
  this.emitAuthEvent('logout', null);
652
759
  console.log('[AuthService] User logged out, clearing Auth0 session');
653
760
  // Logout from Auth0
654
761
  try {
655
762
  await this.ensureInitialized();
763
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
764
+ console.log('[AuthService] 🔍 DEBUG: About to call Auth0 logout, returnTo:', AUTH0_CONFIG.logoutUri);
656
765
  await this.auth0Client.logout({
657
766
  logoutParams: {
658
767
  returnTo: AUTH0_CONFIG.logoutUri
659
768
  }
660
769
  });
770
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
771
+ console.log('[AuthService] 🔍 DEBUG: Auth0 logout completed (this may not be visible due to redirect)');
661
772
  }
662
773
  catch (error) {
663
774
  console.error('[AuthService] Error during Auth0 logout:', error);
775
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
776
+ console.error('[AuthService] 🔍 DEBUG: logout() failed with error:', error);
664
777
  }
665
778
  }
666
779
  /**
@@ -668,20 +781,30 @@ exports.AuthService = class AuthService {
668
781
  * @returns string | null - Access token or null if not authenticated
669
782
  */
670
783
  async getToken() {
784
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
785
+ console.log('[AuthService] 🔍 DEBUG: getToken() called');
671
786
  // Try to get from storage first
672
787
  const storedToken = getStorageItem(STORAGE_KEYS.ACCESS_TOKEN, STORAGE_CONFIG.TOKEN_STORAGE);
673
788
  if (storedToken) {
789
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
790
+ console.log('[AuthService] 🔍 DEBUG: Token found in storage, length:', storedToken.length);
674
791
  return storedToken;
675
792
  }
793
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
794
+ console.log('[AuthService] 🔍 DEBUG: Token not in storage, fetching from Auth0');
676
795
  // If not in storage, try to get from Auth0 client
677
796
  try {
678
797
  await this.ensureInitialized();
679
798
  const token = await this.auth0Client.getTokenSilently();
799
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
800
+ console.log('[AuthService] 🔍 DEBUG: Token retrieved from Auth0, length:', token?.length || 0);
680
801
  this.setToken(token);
681
802
  return token;
682
803
  }
683
804
  catch (error) {
684
805
  console.error('[AuthService] Error getting token from Auth0:', error);
806
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
807
+ console.error('[AuthService] 🔍 DEBUG: getToken() failed:', error);
685
808
  return null;
686
809
  }
687
810
  }
@@ -698,22 +821,34 @@ exports.AuthService = class AuthService {
698
821
  * @param token - Access token to store
699
822
  */
700
823
  setToken(token) {
824
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
825
+ console.log('[AuthService] 🔍 DEBUG: setToken() called, storing token in storage');
701
826
  setStorageItem(STORAGE_KEYS.ACCESS_TOKEN, token, STORAGE_CONFIG.TOKEN_STORAGE);
702
827
  this.emitAuthEvent('token_updated', { token });
828
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
829
+ console.log('[AuthService] 🔍 DEBUG: Token stored and token_updated event emitted');
703
830
  }
704
831
  /**
705
832
  * Check if user is authenticated
706
833
  * @returns boolean - True if user has valid token
707
834
  */
708
835
  async isAuthenticated() {
836
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
837
+ console.log('[AuthService] 🔍 DEBUG: isAuthenticated() called');
709
838
  try {
710
839
  await this.ensureInitialized();
711
- return await this.auth0Client.isAuthenticated();
840
+ const result = await this.auth0Client.isAuthenticated();
841
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
842
+ console.log('[AuthService] 🔍 DEBUG: isAuthenticated() result from Auth0:', result);
843
+ return result;
712
844
  }
713
845
  catch (error) {
714
846
  console.error('[AuthService] Error checking authentication status:', error);
715
847
  // Fallback to checking storage
716
- return !!getStorageItem(STORAGE_KEYS.ACCESS_TOKEN, STORAGE_CONFIG.TOKEN_STORAGE);
848
+ const hasToken = !!getStorageItem(STORAGE_KEYS.ACCESS_TOKEN, STORAGE_CONFIG.TOKEN_STORAGE);
849
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
850
+ console.error('[AuthService] 🔍 DEBUG: isAuthenticated() failed, falling back to storage check:', hasToken);
851
+ return hasToken;
717
852
  }
718
853
  }
719
854
  /**
@@ -793,6 +928,8 @@ exports.AuthService = class AuthService {
793
928
  * @param userInfo - User information to store
794
929
  */
795
930
  setUserInfo(userInfo) {
931
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
932
+ console.log('[AuthService] 🔍 DEBUG: setUserInfo() called');
796
933
  setStorageItem(STORAGE_KEYS.USER_INFO, JSON.stringify(userInfo), STORAGE_CONFIG.USER_INFO_STORAGE);
797
934
  this.userSubject.next(userInfo);
798
935
  // Log stored user info with all claims
@@ -811,6 +948,8 @@ exports.AuthService = class AuthService {
811
948
  console.log(` • ${claim}:`, userInfo[claim]);
812
949
  });
813
950
  }
951
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
952
+ console.log('[AuthService] 🔍 DEBUG: User info stored in storage and userSubject updated');
814
953
  this.emitAuthEvent('user_info_updated', userInfo);
815
954
  }
816
955
  /**
@@ -825,6 +964,8 @@ exports.AuthService = class AuthService {
825
964
  payload,
826
965
  timestamp: new Date().toISOString()
827
966
  };
967
+ // TODO_REMOVE_DEBUG: Temporary debug log - remove after debugging
968
+ console.log('[AuthService] 🔍 DEBUG: emitAuthEvent() called, event type:', event.type);
828
969
  this.eventBus.sendEvent(JSON.stringify(event));
829
970
  console.log('[AuthService] Auth event emitted:', event.type);
830
971
  }