witspry-auth-ng-client 1.0.0

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.
@@ -0,0 +1,1511 @@
1
+ import * as i0 from '@angular/core';
2
+ import { InjectionToken, PLATFORM_ID, Inject, Injectable, signal, inject, Component, makeEnvironmentProviders, NgModule } from '@angular/core';
3
+ import * as i3 from '@angular/common';
4
+ import { isPlatformBrowser, CommonModule } from '@angular/common';
5
+ import { BehaviorSubject, throwError } from 'rxjs';
6
+ import * as i1 from '@angular/common/http';
7
+ import { HttpHeaders, HttpRequest, HttpResponse, provideHttpClient, withInterceptors } from '@angular/common/http';
8
+ import * as i2 from '@angular/router';
9
+ import { Router } from '@angular/router';
10
+ import { catchError, filter, switchMap, take, map } from 'rxjs/operators';
11
+
12
+ /**
13
+ * OAuth2 Storage Keys Constants
14
+ */
15
+ const OAUTH2_STORAGE_KEYS = {
16
+ CODE_VERIFIER: 'oauth2_code_verifier',
17
+ STATE: 'oauth2_state',
18
+ ACCESS_TOKEN: 'oauth2_access_token',
19
+ REFRESH_TOKEN: 'oauth2_refresh_token',
20
+ TOKEN_EXPIRES_AT: 'oauth2_token_expires_at',
21
+ TOKEN_TYPE: 'oauth2_token_type',
22
+ SCOPE: 'oauth2_scope',
23
+ ID_TOKEN: 'oauth2_id_token',
24
+ NONCE: 'oauth2_nonce'
25
+ };
26
+
27
+ /**
28
+ * Injection token for OAuth2 configuration
29
+ */
30
+ const OAUTH2_CONFIG_TOKEN = new InjectionToken('OAUTH2_CONFIG');
31
+
32
+ /**
33
+ * OAuth2 Storage Service
34
+ * Handles secure storage and retrieval of OAuth2 tokens and data
35
+ */
36
+ class OAuth2StorageService {
37
+ config;
38
+ platformId;
39
+ storage;
40
+ logLevel;
41
+ constructor(config, platformId) {
42
+ this.config = config;
43
+ this.platformId = platformId;
44
+ this.logLevel = config.logLevel || 'warn';
45
+ this.storage = this.initializeStorage();
46
+ }
47
+ /**
48
+ * Initialize storage based on configuration
49
+ */
50
+ initializeStorage() {
51
+ if (!isPlatformBrowser(this.platformId)) {
52
+ // Return a no-op storage for SSR
53
+ return {
54
+ getItem: () => null,
55
+ setItem: () => { },
56
+ removeItem: () => { },
57
+ clear: () => { }
58
+ };
59
+ }
60
+ switch (this.config.storage) {
61
+ case 'sessionStorage':
62
+ return sessionStorage;
63
+ case 'custom':
64
+ if (!this.config.customStorage) {
65
+ this.logError('Custom storage specified but not provided');
66
+ return localStorage;
67
+ }
68
+ return this.config.customStorage;
69
+ case 'localStorage':
70
+ default:
71
+ return localStorage;
72
+ }
73
+ }
74
+ /**
75
+ * Store a value securely
76
+ */
77
+ setItem(key, value) {
78
+ try {
79
+ // In production, consider encrypting sensitive values
80
+ this.storage.setItem(key, value);
81
+ this.logDebug(`Stored item with key: ${key}`);
82
+ }
83
+ catch (error) {
84
+ this.logError('Error storing item:', error);
85
+ throw new Error('Failed to store item');
86
+ }
87
+ }
88
+ /**
89
+ * Retrieve a value securely
90
+ */
91
+ getItem(key) {
92
+ try {
93
+ const value = this.storage.getItem(key);
94
+ this.logDebug(`Retrieved item with key: ${key}`, value ? 'Found' : 'Not found');
95
+ return value;
96
+ }
97
+ catch (error) {
98
+ this.logError('Error retrieving item:', error);
99
+ return null;
100
+ }
101
+ }
102
+ /**
103
+ * Remove a specific item
104
+ */
105
+ removeItem(key) {
106
+ try {
107
+ this.storage.removeItem(key);
108
+ this.logDebug(`Removed item with key: ${key}`);
109
+ }
110
+ catch (error) {
111
+ this.logError('Error removing item:', error);
112
+ }
113
+ }
114
+ /**
115
+ * Clear all OAuth2 related storage
116
+ */
117
+ clearAll() {
118
+ try {
119
+ Object.values(OAUTH2_STORAGE_KEYS).forEach(key => {
120
+ this.storage.removeItem(key);
121
+ });
122
+ this.logDebug('Cleared all OAuth2 storage');
123
+ }
124
+ catch (error) {
125
+ this.logError('Error clearing storage:', error);
126
+ }
127
+ }
128
+ /**
129
+ * Clear only token-related storage, preserve OAuth2 flow storage
130
+ */
131
+ clearTokens() {
132
+ try {
133
+ const tokenKeys = [
134
+ OAUTH2_STORAGE_KEYS.ACCESS_TOKEN,
135
+ OAUTH2_STORAGE_KEYS.REFRESH_TOKEN,
136
+ OAUTH2_STORAGE_KEYS.TOKEN_EXPIRES_AT,
137
+ OAUTH2_STORAGE_KEYS.TOKEN_TYPE,
138
+ OAUTH2_STORAGE_KEYS.SCOPE,
139
+ OAUTH2_STORAGE_KEYS.ID_TOKEN
140
+ ];
141
+ tokenKeys.forEach(key => {
142
+ this.storage.removeItem(key);
143
+ });
144
+ this.logDebug('Cleared token storage (OAuth2 flow storage preserved)');
145
+ }
146
+ catch (error) {
147
+ this.logError('Error clearing token storage:', error);
148
+ }
149
+ }
150
+ /**
151
+ * Clear temporary OAuth2 flow storage
152
+ */
153
+ clearTemporary() {
154
+ try {
155
+ this.storage.removeItem(OAUTH2_STORAGE_KEYS.CODE_VERIFIER);
156
+ this.storage.removeItem(OAUTH2_STORAGE_KEYS.STATE);
157
+ this.storage.removeItem(OAUTH2_STORAGE_KEYS.NONCE);
158
+ this.logDebug('Cleared temporary OAuth2 storage');
159
+ }
160
+ catch (error) {
161
+ this.logError('Error clearing temporary storage:', error);
162
+ }
163
+ }
164
+ /**
165
+ * Check if storage is available
166
+ */
167
+ isAvailable() {
168
+ return isPlatformBrowser(this.platformId);
169
+ }
170
+ /**
171
+ * Get all stored keys (for debugging)
172
+ */
173
+ getStoredKeys() {
174
+ if (!this.isAvailable()) {
175
+ return [];
176
+ }
177
+ try {
178
+ const keys = [];
179
+ for (let i = 0; i < this.storage.length; i++) {
180
+ const key = this.storage.key(i);
181
+ if (key && Object.values(OAUTH2_STORAGE_KEYS).includes(key)) {
182
+ keys.push(key);
183
+ }
184
+ }
185
+ return keys;
186
+ }
187
+ catch (error) {
188
+ this.logError('Error getting stored keys:', error);
189
+ return [];
190
+ }
191
+ }
192
+ /**
193
+ * Debug logging
194
+ */
195
+ logDebug(message, ...args) {
196
+ if (this.logLevel === 'debug') {
197
+ console.log(`[OAuth2StorageService] ${message}`, ...args);
198
+ }
199
+ }
200
+ /**
201
+ * Info logging
202
+ */
203
+ logInfo(message, ...args) {
204
+ if (['debug', 'info'].includes(this.logLevel)) {
205
+ console.info(`[OAuth2StorageService] ${message}`, ...args);
206
+ }
207
+ }
208
+ /**
209
+ * Warning logging
210
+ */
211
+ logWarn(message, ...args) {
212
+ if (['debug', 'info', 'warn'].includes(this.logLevel)) {
213
+ console.warn(`[OAuth2StorageService] ${message}`, ...args);
214
+ }
215
+ }
216
+ /**
217
+ * Error logging
218
+ */
219
+ logError(message, error) {
220
+ if (this.logLevel !== 'none') {
221
+ console.error(`[OAuth2StorageService] ${message}`, error);
222
+ }
223
+ }
224
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: OAuth2StorageService, deps: [{ token: OAUTH2_CONFIG_TOKEN }, { token: PLATFORM_ID }], target: i0.ɵɵFactoryTarget.Injectable });
225
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: OAuth2StorageService, providedIn: 'root' });
226
+ }
227
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: OAuth2StorageService, decorators: [{
228
+ type: Injectable,
229
+ args: [{
230
+ providedIn: 'root'
231
+ }]
232
+ }], ctorParameters: () => [{ type: undefined, decorators: [{
233
+ type: Inject,
234
+ args: [OAUTH2_CONFIG_TOKEN]
235
+ }] }, { type: Object, decorators: [{
236
+ type: Inject,
237
+ args: [PLATFORM_ID]
238
+ }] }] });
239
+
240
+ /**
241
+ * OAuth2 Service with PKCE Support
242
+ * Handles OAuth2 authorization flow, token management, and user authentication
243
+ */
244
+ class OAuth2Service {
245
+ config;
246
+ platformId;
247
+ http;
248
+ router;
249
+ storageService;
250
+ _authState = signal({
251
+ isAuthenticated: false,
252
+ isLoading: false
253
+ });
254
+ _authStateSubject = new BehaviorSubject({
255
+ isAuthenticated: false,
256
+ isLoading: false
257
+ });
258
+ authState$ = this._authStateSubject.asObservable();
259
+ authState = this._authState.asReadonly();
260
+ logLevel;
261
+ constructor(config, platformId, http, router, storageService) {
262
+ this.config = config;
263
+ this.platformId = platformId;
264
+ this.http = http;
265
+ this.router = router;
266
+ this.storageService = storageService;
267
+ this.logLevel = config.logLevel || 'warn';
268
+ this.initializeAuthState();
269
+ }
270
+ /**
271
+ * Initialize authentication state from stored tokens
272
+ */
273
+ initializeAuthState() {
274
+ if (!isPlatformBrowser(this.platformId)) {
275
+ return;
276
+ }
277
+ try {
278
+ const tokenInfo = this.getStoredTokenInfo();
279
+ if (tokenInfo && this.isTokenValid(tokenInfo)) {
280
+ this.updateAuthState({
281
+ isAuthenticated: true,
282
+ isLoading: false,
283
+ tokenInfo
284
+ });
285
+ this.logInfo('Authentication state initialized from stored tokens');
286
+ }
287
+ else if (tokenInfo && tokenInfo.refreshToken) {
288
+ // Access token is expired but refresh token exists
289
+ this.logInfo('Access token expired but refresh token available - preserving for refresh flow');
290
+ this.updateAuthState({
291
+ isAuthenticated: false,
292
+ isLoading: false,
293
+ tokenInfo: undefined
294
+ });
295
+ }
296
+ else {
297
+ // No tokens or no refresh token available - clear everything
298
+ this.storageService.clearTokens();
299
+ this.logInfo('No valid stored tokens found');
300
+ }
301
+ }
302
+ catch (error) {
303
+ this.logError('Error initializing auth state:', error);
304
+ this.storageService.clearTokens();
305
+ }
306
+ }
307
+ /**
308
+ * Generate cryptographically secure PKCE challenge
309
+ */
310
+ async generatePKCEChallenge() {
311
+ const codeVerifier = this.generateSecureCodeVerifier();
312
+ const codeChallenge = await this.createCodeChallenge(codeVerifier);
313
+ return {
314
+ codeVerifier,
315
+ codeChallenge,
316
+ codeChallengeMethod: this.config.codeChallengeMethod || 'S256'
317
+ };
318
+ }
319
+ /**
320
+ * Generate cryptographically secure 6-digit code verifier
321
+ */
322
+ generateSecureCodeVerifier() {
323
+ if (!isPlatformBrowser(this.platformId)) {
324
+ throw new Error('Code verifier generation requires browser environment');
325
+ }
326
+ // Generate 6 cryptographically secure random digits
327
+ const array = new Uint8Array(6);
328
+ crypto.getRandomValues(array);
329
+ // Convert to 6-digit string (000000-999999)
330
+ const codeVerifier = Array.from(array)
331
+ .map(byte => (byte % 10).toString())
332
+ .join('');
333
+ this.logDebug('Generated secure 6-digit code verifier');
334
+ return codeVerifier;
335
+ }
336
+ /**
337
+ * Create SHA-256 hash and base64 encode for code challenge
338
+ */
339
+ async createCodeChallenge(codeVerifier) {
340
+ if (!isPlatformBrowser(this.platformId)) {
341
+ throw new Error('Code challenge creation requires browser environment');
342
+ }
343
+ try {
344
+ // Encode the code verifier as UTF-8
345
+ const encoder = new TextEncoder();
346
+ const data = encoder.encode(codeVerifier);
347
+ // Create SHA-256 hash
348
+ const hashBuffer = await crypto.subtle.digest('SHA-256', data);
349
+ // Convert to base64url encoding
350
+ const hashArray = new Uint8Array(hashBuffer);
351
+ const base64String = btoa(String.fromCharCode(...hashArray))
352
+ .replace(/\+/g, '-')
353
+ .replace(/\//g, '_')
354
+ .replace(/=/g, '');
355
+ this.logDebug('Generated code challenge from verifier');
356
+ return base64String;
357
+ }
358
+ catch (error) {
359
+ this.logError('Error creating code challenge:', error);
360
+ throw new Error('Failed to create code challenge');
361
+ }
362
+ }
363
+ /**
364
+ * Generate cryptographically secure state parameter for CSRF protection
365
+ */
366
+ generateState() {
367
+ if (!isPlatformBrowser(this.platformId)) {
368
+ return 'fallback-state';
369
+ }
370
+ const array = new Uint8Array(32);
371
+ crypto.getRandomValues(array);
372
+ return btoa(String.fromCharCode(...array))
373
+ .replace(/\+/g, '-')
374
+ .replace(/\//g, '_')
375
+ .replace(/=/g, '');
376
+ }
377
+ /**
378
+ * Generate nonce if not provided in config
379
+ */
380
+ generateNonce() {
381
+ if (this.config.nonce) {
382
+ return this.config.nonce;
383
+ }
384
+ if (!isPlatformBrowser(this.platformId)) {
385
+ return 'fallback-nonce';
386
+ }
387
+ const array = new Uint8Array(16);
388
+ crypto.getRandomValues(array);
389
+ return btoa(String.fromCharCode(...array))
390
+ .replace(/\+/g, '-')
391
+ .replace(/\//g, '_')
392
+ .replace(/=/g, '');
393
+ }
394
+ /**
395
+ * Start OAuth2 PKCE authorization flow
396
+ */
397
+ async startAuthorization() {
398
+ if (!isPlatformBrowser(this.platformId)) {
399
+ this.logError('Authorization attempted in non-browser environment', 'SSR or server context detected');
400
+ this.updateAuthState({
401
+ isLoading: false,
402
+ error: 'Authentication not available in server environment'
403
+ });
404
+ return;
405
+ }
406
+ try {
407
+ this.updateAuthState({ isLoading: true, error: undefined });
408
+ // Generate PKCE challenge
409
+ const pkceChallenge = await this.generatePKCEChallenge();
410
+ // Generate state for CSRF protection
411
+ const state = this.generateState();
412
+ // Generate nonce
413
+ const nonce = this.generateNonce();
414
+ // Store code verifier, state, and nonce securely
415
+ this.storageService.setItem(OAUTH2_STORAGE_KEYS.CODE_VERIFIER, pkceChallenge.codeVerifier);
416
+ this.storageService.setItem(OAUTH2_STORAGE_KEYS.STATE, state);
417
+ this.storageService.setItem(OAUTH2_STORAGE_KEYS.NONCE, nonce);
418
+ // Build authorization request
419
+ const authRequest = {
420
+ client_id: this.config.clientId,
421
+ redirect_uri: this.config.redirectUri,
422
+ response_type: this.config.responseType || 'code',
423
+ nonce,
424
+ audience: this.config.audience,
425
+ scope: this.config.scope,
426
+ code_challenge_method: pkceChallenge.codeChallengeMethod,
427
+ code_challenge: pkceChallenge.codeChallenge,
428
+ state
429
+ };
430
+ // Build authorization URL
431
+ const authUrl = this.buildAuthorizationUrl(authRequest);
432
+ this.logInfo('Starting OAuth2 PKCE authorization flow');
433
+ this.logDebug('Authorization URL:', authUrl);
434
+ // Redirect to authorization server
435
+ window.location.href = authUrl;
436
+ }
437
+ catch (error) {
438
+ this.logError('Error starting authorization:', error);
439
+ this.updateAuthState({
440
+ isLoading: false,
441
+ error: 'Failed to start authorization flow'
442
+ });
443
+ throw error;
444
+ }
445
+ }
446
+ /**
447
+ * Build authorization URL with parameters
448
+ */
449
+ buildAuthorizationUrl(request) {
450
+ const params = new URLSearchParams();
451
+ Object.entries(request).forEach(([key, value]) => {
452
+ if (value !== undefined) {
453
+ params.append(key, value.toString());
454
+ }
455
+ });
456
+ return `${this.config.authorizationEndpoint}?${params.toString()}`;
457
+ }
458
+ /**
459
+ * Handle OAuth2 callback and extract tokens
460
+ */
461
+ async handleCallback() {
462
+ if (!isPlatformBrowser(this.platformId)) {
463
+ throw new Error('Callback handling requires browser environment');
464
+ }
465
+ try {
466
+ this.updateAuthState({ isLoading: true, error: undefined });
467
+ const currentUrl = window.location.href;
468
+ this.logInfo('Handling OAuth2 callback:', currentUrl);
469
+ // Check for error in callback
470
+ const error = this.extractErrorFromCallback();
471
+ if (error) {
472
+ throw new Error(`OAuth2 Error: ${error.error} - ${error.error_description || 'Unknown error'}`);
473
+ }
474
+ // Extract authorization code from query parameters or hash fragment
475
+ const authCode = this.extractAuthorizationCode();
476
+ this.logDebug('Extracted authorization code:', authCode ? 'Found' : 'Not found');
477
+ if (authCode) {
478
+ await this.exchangeCodeForTokens(authCode);
479
+ return;
480
+ }
481
+ // Extract tokens from URL fragment (implicit flow)
482
+ const tokens = this.extractTokensFromFragment();
483
+ this.logDebug('Extracted tokens from fragment:', tokens ? 'Found' : 'Not found');
484
+ if (tokens) {
485
+ await this.handleTokenResponse(tokens);
486
+ return;
487
+ }
488
+ throw new Error('No authorization code or tokens found in callback');
489
+ }
490
+ catch (error) {
491
+ this.logError('Error handling callback:', error);
492
+ this.updateAuthState({
493
+ isLoading: false,
494
+ error: error instanceof Error ? error.message : 'Callback handling failed'
495
+ });
496
+ this.storageService.clearAll();
497
+ throw error;
498
+ }
499
+ }
500
+ /**
501
+ * Extract error from callback URL
502
+ */
503
+ extractErrorFromCallback() {
504
+ const urlParams = new URLSearchParams(window.location.search);
505
+ const hashParams = new URLSearchParams(window.location.hash.substring(1));
506
+ const error = urlParams.get('error') || hashParams.get('error');
507
+ if (error) {
508
+ return {
509
+ error,
510
+ error_description: urlParams.get('error_description') || hashParams.get('error_description') || undefined,
511
+ error_uri: urlParams.get('error_uri') || hashParams.get('error_uri') || undefined,
512
+ state: urlParams.get('state') || hashParams.get('state') || undefined
513
+ };
514
+ }
515
+ return null;
516
+ }
517
+ /**
518
+ * Extract authorization code from query parameters
519
+ */
520
+ extractAuthorizationCode() {
521
+ // First check query parameters
522
+ const urlParams = new URLSearchParams(window.location.search);
523
+ let code = urlParams.get('code');
524
+ // If not found in query params, check hash fragment
525
+ if (!code && window.location.hash) {
526
+ const hashParams = new URLSearchParams(window.location.hash.substring(1));
527
+ code = hashParams.get('code');
528
+ }
529
+ if (code) {
530
+ this.logDebug('Authorization code extracted from callback');
531
+ return code;
532
+ }
533
+ return null;
534
+ }
535
+ /**
536
+ * Extract tokens from URL fragment
537
+ */
538
+ extractTokensFromFragment() {
539
+ const fragment = window.location.hash.substring(1);
540
+ if (!fragment) {
541
+ return null;
542
+ }
543
+ const params = new URLSearchParams(fragment);
544
+ const accessToken = params.get('access_token');
545
+ if (accessToken) {
546
+ this.logDebug('Tokens extracted from URL fragment');
547
+ return {
548
+ access_token: accessToken,
549
+ refresh_token: params.get('refresh_token') || undefined,
550
+ token_type: params.get('token_type') || 'Bearer',
551
+ expires_in: parseInt(params.get('expires_in') || '3600', 10),
552
+ scope: params.get('scope') || undefined,
553
+ id_token: params.get('id_token') || undefined
554
+ };
555
+ }
556
+ return null;
557
+ }
558
+ /**
559
+ * Exchange authorization code for tokens
560
+ */
561
+ async exchangeCodeForTokens(authCode) {
562
+ const codeVerifier = this.storageService.getItem(OAUTH2_STORAGE_KEYS.CODE_VERIFIER);
563
+ if (!codeVerifier) {
564
+ this.logError('Code verifier not found in storage');
565
+ throw new Error('Code verifier not found in storage');
566
+ }
567
+ const tokenRequest = {
568
+ grant_type: 'authorization_code',
569
+ redirect_uri: this.config.redirectUri,
570
+ client_id: this.config.clientId,
571
+ code: authCode,
572
+ code_verifier: codeVerifier
573
+ };
574
+ this.logInfo('Exchanging authorization code for tokens');
575
+ // Convert to URL-encoded form data as per OAuth 2.0 standard
576
+ const formData = new URLSearchParams();
577
+ Object.entries(tokenRequest).forEach(([key, value]) => {
578
+ if (value !== undefined) {
579
+ formData.append(key, value.toString());
580
+ }
581
+ });
582
+ try {
583
+ const tokenResponse = await this.http.post(this.config.tokenEndpoint, formData.toString(), {
584
+ headers: {
585
+ 'Content-Type': 'application/x-www-form-urlencoded'
586
+ }
587
+ }).toPromise();
588
+ if (tokenResponse) {
589
+ await this.handleTokenResponse(tokenResponse);
590
+ }
591
+ else {
592
+ throw new Error('No token response received');
593
+ }
594
+ }
595
+ catch (error) {
596
+ this.logError('Token exchange failed:', error);
597
+ throw new Error('Failed to exchange authorization code for tokens');
598
+ }
599
+ }
600
+ /**
601
+ * Handle token response and store tokens securely
602
+ */
603
+ async handleTokenResponse(tokenResponse) {
604
+ try {
605
+ // Validate state parameter for CSRF protection
606
+ await this.validateState();
607
+ // Create token info
608
+ const tokenInfo = {
609
+ accessToken: tokenResponse.access_token,
610
+ refreshToken: tokenResponse.refresh_token,
611
+ tokenType: tokenResponse.token_type || 'Bearer',
612
+ expiresAt: Date.now() + (tokenResponse.expires_in * 1000),
613
+ scope: tokenResponse.scope,
614
+ idToken: tokenResponse.id_token
615
+ };
616
+ // Store tokens securely
617
+ this.storeTokenInfo(tokenInfo);
618
+ // Update authentication state
619
+ this.updateAuthState({
620
+ isAuthenticated: true,
621
+ isLoading: false,
622
+ tokenInfo,
623
+ error: undefined
624
+ });
625
+ // Clean up temporary storage
626
+ this.storageService.clearTemporary();
627
+ this.logInfo('Tokens stored successfully, user authenticated');
628
+ }
629
+ catch (error) {
630
+ this.logError('Error handling token response:', error);
631
+ throw error;
632
+ }
633
+ }
634
+ /**
635
+ * Validate state parameter for CSRF protection
636
+ */
637
+ async validateState() {
638
+ const urlParams = new URLSearchParams(window.location.search);
639
+ const hashParams = new URLSearchParams(window.location.hash.substring(1));
640
+ const receivedState = urlParams.get('state') || hashParams.get('state');
641
+ const storedState = this.storageService.getItem(OAUTH2_STORAGE_KEYS.STATE);
642
+ if (!receivedState || !storedState || receivedState !== storedState) {
643
+ throw new Error('Invalid state parameter - possible CSRF attack');
644
+ }
645
+ this.logDebug('State parameter validated successfully');
646
+ }
647
+ /**
648
+ * Get current access token (only if valid/not expired)
649
+ */
650
+ getAccessToken() {
651
+ const tokenInfo = this.getStoredTokenInfo();
652
+ if (tokenInfo && this.isTokenValid(tokenInfo)) {
653
+ return tokenInfo.accessToken;
654
+ }
655
+ return null;
656
+ }
657
+ /**
658
+ * Get raw access token (even if expired) - used for refresh flow
659
+ */
660
+ getRawAccessToken() {
661
+ const tokenInfo = this.getStoredTokenInfo();
662
+ return tokenInfo?.accessToken || null;
663
+ }
664
+ /**
665
+ * Get current refresh token
666
+ */
667
+ getRefreshToken() {
668
+ const tokenInfo = this.getStoredTokenInfo();
669
+ return tokenInfo?.refreshToken || null;
670
+ }
671
+ /**
672
+ * Check if user is authenticated
673
+ */
674
+ isAuthenticated() {
675
+ const tokenInfo = this.getStoredTokenInfo();
676
+ return tokenInfo ? this.isTokenValid(tokenInfo) : false;
677
+ }
678
+ /**
679
+ * Check if authentication is available in current environment
680
+ */
681
+ isAuthenticationAvailable() {
682
+ return isPlatformBrowser(this.platformId);
683
+ }
684
+ /**
685
+ * Fetch user information from OIDC userinfo endpoint
686
+ */
687
+ async getUserInfo() {
688
+ if (!this.config.userInfoEndpoint) {
689
+ throw new Error('UserInfo endpoint not configured');
690
+ }
691
+ const accessToken = this.getAccessToken();
692
+ if (!accessToken) {
693
+ throw new Error('No access token available');
694
+ }
695
+ this.logInfo('Fetching user info from OIDC userinfo endpoint');
696
+ try {
697
+ const userInfo = await this.http.get(this.config.userInfoEndpoint, {
698
+ headers: {
699
+ 'Authorization': `Bearer ${accessToken}`
700
+ }
701
+ }).toPromise();
702
+ if (userInfo) {
703
+ this.logDebug('User info retrieved successfully:', userInfo);
704
+ return userInfo;
705
+ }
706
+ else {
707
+ throw new Error('No user info response received');
708
+ }
709
+ }
710
+ catch (error) {
711
+ this.logError('Failed to fetch user info:', error);
712
+ throw new Error('Failed to fetch user information');
713
+ }
714
+ }
715
+ /**
716
+ * Check if token is valid (not expired)
717
+ */
718
+ isTokenValid(tokenInfo) {
719
+ const threshold = (this.config.refreshThreshold || 300) * 1000; // Convert to milliseconds
720
+ return Date.now() < (tokenInfo.expiresAt - threshold);
721
+ }
722
+ /**
723
+ * Refresh access token using refresh token
724
+ */
725
+ async refreshAccessToken() {
726
+ const refreshToken = this.getRefreshToken();
727
+ if (!refreshToken) {
728
+ throw new Error('No refresh token available');
729
+ }
730
+ this.logInfo('Refreshing access token');
731
+ const tokenRequest = {
732
+ grant_type: 'refresh_token',
733
+ refresh_token: refreshToken,
734
+ client_id: this.config.clientId
735
+ };
736
+ // Convert to URL-encoded form data as per OAuth 2.0 standard
737
+ const formData = new URLSearchParams();
738
+ Object.entries(tokenRequest).forEach(([key, value]) => {
739
+ if (value !== undefined) {
740
+ formData.append(key, value.toString());
741
+ }
742
+ });
743
+ try {
744
+ const tokenResponse = await this.http.post(this.config.tokenEndpoint, formData.toString(), {
745
+ headers: {
746
+ 'Content-Type': 'application/x-www-form-urlencoded'
747
+ }
748
+ }).toPromise();
749
+ if (tokenResponse) {
750
+ const tokenInfo = {
751
+ accessToken: tokenResponse.access_token,
752
+ refreshToken: tokenResponse.refresh_token || refreshToken,
753
+ tokenType: tokenResponse.token_type || 'Bearer',
754
+ expiresAt: Date.now() + (tokenResponse.expires_in * 1000),
755
+ scope: tokenResponse.scope,
756
+ idToken: tokenResponse.id_token
757
+ };
758
+ this.storeTokenInfo(tokenInfo);
759
+ this.updateAuthState({
760
+ isAuthenticated: true,
761
+ isLoading: false,
762
+ tokenInfo
763
+ });
764
+ this.logInfo('Access token refreshed successfully');
765
+ return tokenResponse.access_token;
766
+ }
767
+ else {
768
+ throw new Error('No token response received');
769
+ }
770
+ }
771
+ catch (error) {
772
+ this.logError('Token refresh failed:', error);
773
+ // Only logout if it's a 400/401 error indicating invalid refresh token
774
+ if (error instanceof Error && 'status' in error) {
775
+ const httpError = error;
776
+ if (httpError.status === 400 || httpError.status === 401) {
777
+ this.logInfo('Refresh token is invalid, logging out');
778
+ this.logout();
779
+ }
780
+ }
781
+ else {
782
+ this.logInfo('Network or server error during token refresh, will retry later');
783
+ }
784
+ throw new Error('Failed to refresh access token');
785
+ }
786
+ }
787
+ /**
788
+ * Logout user and clean up all stored data
789
+ */
790
+ async logout() {
791
+ try {
792
+ this.updateAuthState({ isLoading: true });
793
+ // Revoke tokens if supported
794
+ await this.revokeTokens();
795
+ // Clear all stored authentication data
796
+ this.storageService.clearAll();
797
+ // Update authentication state
798
+ this.updateAuthState({
799
+ isAuthenticated: false,
800
+ isLoading: false,
801
+ tokenInfo: undefined,
802
+ error: undefined
803
+ });
804
+ this.logInfo('User logged out successfully');
805
+ }
806
+ catch (error) {
807
+ this.logError('Error during logout:', error);
808
+ // Still clear local data even if revocation fails
809
+ this.storageService.clearAll();
810
+ this.updateAuthState({
811
+ isAuthenticated: false,
812
+ isLoading: false,
813
+ tokenInfo: undefined
814
+ });
815
+ }
816
+ }
817
+ /**
818
+ * Revoke tokens at authorization server
819
+ */
820
+ async revokeTokens() {
821
+ if (!this.config.revokeEndpoint) {
822
+ this.logInfo('Token revocation endpoint not configured');
823
+ return;
824
+ }
825
+ const accessToken = this.getAccessToken();
826
+ const refreshToken = this.getRefreshToken();
827
+ const revokePromises = [];
828
+ if (accessToken) {
829
+ const revokeRequest = {
830
+ token: accessToken,
831
+ token_type_hint: 'access_token',
832
+ client_id: this.config.clientId
833
+ };
834
+ const formData = new URLSearchParams();
835
+ Object.entries(revokeRequest).forEach(([key, value]) => {
836
+ if (value !== undefined) {
837
+ formData.append(key, value.toString());
838
+ }
839
+ });
840
+ revokePromises.push(this.http.post(this.config.revokeEndpoint, formData.toString(), {
841
+ headers: {
842
+ 'Content-Type': 'application/x-www-form-urlencoded'
843
+ }
844
+ }).toPromise());
845
+ }
846
+ if (refreshToken) {
847
+ const revokeRequest = {
848
+ token: refreshToken,
849
+ token_type_hint: 'refresh_token',
850
+ client_id: this.config.clientId
851
+ };
852
+ const formData = new URLSearchParams();
853
+ Object.entries(revokeRequest).forEach(([key, value]) => {
854
+ if (value !== undefined) {
855
+ formData.append(key, value.toString());
856
+ }
857
+ });
858
+ revokePromises.push(this.http.post(this.config.revokeEndpoint, formData.toString(), {
859
+ headers: {
860
+ 'Content-Type': 'application/x-www-form-urlencoded'
861
+ }
862
+ }).toPromise());
863
+ }
864
+ if (revokePromises.length > 0) {
865
+ try {
866
+ await Promise.all(revokePromises);
867
+ this.logInfo('Tokens revoked successfully');
868
+ }
869
+ catch (error) {
870
+ this.logError('Token revocation failed:', error);
871
+ // Don't throw error, continue with logout
872
+ }
873
+ }
874
+ }
875
+ /**
876
+ * Store token information securely
877
+ */
878
+ storeTokenInfo(tokenInfo) {
879
+ try {
880
+ this.storageService.setItem(OAUTH2_STORAGE_KEYS.ACCESS_TOKEN, tokenInfo.accessToken);
881
+ this.storageService.setItem(OAUTH2_STORAGE_KEYS.TOKEN_EXPIRES_AT, tokenInfo.expiresAt.toString());
882
+ this.storageService.setItem(OAUTH2_STORAGE_KEYS.TOKEN_TYPE, tokenInfo.tokenType);
883
+ if (tokenInfo.refreshToken) {
884
+ this.storageService.setItem(OAUTH2_STORAGE_KEYS.REFRESH_TOKEN, tokenInfo.refreshToken);
885
+ }
886
+ if (tokenInfo.scope) {
887
+ this.storageService.setItem(OAUTH2_STORAGE_KEYS.SCOPE, tokenInfo.scope);
888
+ }
889
+ if (tokenInfo.idToken) {
890
+ this.storageService.setItem(OAUTH2_STORAGE_KEYS.ID_TOKEN, tokenInfo.idToken);
891
+ }
892
+ this.logDebug('Token information stored securely');
893
+ }
894
+ catch (error) {
895
+ this.logError('Error storing token information:', error);
896
+ throw new Error('Failed to store token information');
897
+ }
898
+ }
899
+ /**
900
+ * Retrieve stored token information
901
+ */
902
+ getStoredTokenInfo() {
903
+ if (!this.storageService.isAvailable()) {
904
+ return null;
905
+ }
906
+ try {
907
+ const accessToken = this.storageService.getItem(OAUTH2_STORAGE_KEYS.ACCESS_TOKEN);
908
+ const expiresAtStr = this.storageService.getItem(OAUTH2_STORAGE_KEYS.TOKEN_EXPIRES_AT);
909
+ if (!accessToken || !expiresAtStr) {
910
+ return null;
911
+ }
912
+ return {
913
+ accessToken,
914
+ refreshToken: this.storageService.getItem(OAUTH2_STORAGE_KEYS.REFRESH_TOKEN) || undefined,
915
+ tokenType: this.storageService.getItem(OAUTH2_STORAGE_KEYS.TOKEN_TYPE) || 'Bearer',
916
+ expiresAt: parseInt(expiresAtStr, 10),
917
+ scope: this.storageService.getItem(OAUTH2_STORAGE_KEYS.SCOPE) || undefined,
918
+ idToken: this.storageService.getItem(OAUTH2_STORAGE_KEYS.ID_TOKEN) || undefined
919
+ };
920
+ }
921
+ catch (error) {
922
+ this.logError('Error retrieving stored token information:', error);
923
+ return null;
924
+ }
925
+ }
926
+ /**
927
+ * Update authentication state
928
+ */
929
+ updateAuthState(newState) {
930
+ const currentState = this._authState();
931
+ const updatedState = { ...currentState, ...newState };
932
+ this._authState.set(updatedState);
933
+ this._authStateSubject.next(updatedState);
934
+ }
935
+ /**
936
+ * Debug logging
937
+ */
938
+ logDebug(message, ...args) {
939
+ if (this.logLevel === 'debug') {
940
+ console.log(`[OAuth2Service] ${message}`, ...args);
941
+ }
942
+ }
943
+ /**
944
+ * Info logging
945
+ */
946
+ logInfo(message, ...args) {
947
+ if (['debug', 'info'].includes(this.logLevel)) {
948
+ console.info(`[OAuth2Service] ${message}`, ...args);
949
+ }
950
+ }
951
+ /**
952
+ * Warning logging
953
+ */
954
+ logWarn(message, ...args) {
955
+ if (['debug', 'info', 'warn'].includes(this.logLevel)) {
956
+ console.warn(`[OAuth2Service] ${message}`, ...args);
957
+ }
958
+ }
959
+ /**
960
+ * Error logging
961
+ */
962
+ logError(message, error) {
963
+ if (this.logLevel !== 'none') {
964
+ console.error(`[OAuth2Service] ${message}`, error);
965
+ }
966
+ }
967
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: OAuth2Service, deps: [{ token: OAUTH2_CONFIG_TOKEN }, { token: PLATFORM_ID }, { token: i1.HttpClient }, { token: i2.Router }, { token: OAuth2StorageService }], target: i0.ɵɵFactoryTarget.Injectable });
968
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: OAuth2Service, providedIn: 'root' });
969
+ }
970
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: OAuth2Service, decorators: [{
971
+ type: Injectable,
972
+ args: [{
973
+ providedIn: 'root'
974
+ }]
975
+ }], ctorParameters: () => [{ type: undefined, decorators: [{
976
+ type: Inject,
977
+ args: [OAUTH2_CONFIG_TOKEN]
978
+ }] }, { type: Object, decorators: [{
979
+ type: Inject,
980
+ args: [PLATFORM_ID]
981
+ }] }, { type: i1.HttpClient }, { type: i2.Router }, { type: OAuth2StorageService }] });
982
+
983
+ // Global state for token refresh
984
+ let isRefreshing = false;
985
+ let refreshTokenSubject = new BehaviorSubject(null);
986
+ /**
987
+ * OAuth2 HTTP Interceptor Function
988
+ * Automatically adds Bearer tokens to requests and handles token refresh
989
+ */
990
+ const oauth2InterceptorFn = (request, next) => {
991
+ const platformId = inject(PLATFORM_ID);
992
+ const config = inject(OAUTH2_CONFIG_TOKEN);
993
+ const storageService = inject(OAuth2StorageService);
994
+ const logLevel = config.logLevel || 'warn';
995
+ // Only intercept requests that should have OAuth2 tokens
996
+ if (!shouldInterceptRequest(request, config)) {
997
+ return next(request);
998
+ }
999
+ // Get access token directly from storage to avoid circular dependency
1000
+ let accessToken = storageService.getItem(OAUTH2_STORAGE_KEYS.ACCESS_TOKEN);
1001
+ const hasValidToken = accessToken && isTokenValid(storageService);
1002
+ logDebug(logLevel, 'Access token retrieved:', accessToken ? (hasValidToken ? 'Valid' : 'Expired') : 'Not found');
1003
+ logDebug(logLevel, 'Request URL:', request.url);
1004
+ // Always add token if available, even if expired (server will reject and we'll refresh)
1005
+ if (accessToken) {
1006
+ request = addTokenToRequest(request, accessToken);
1007
+ logDebug(logLevel, 'Authorization header added to request');
1008
+ }
1009
+ else {
1010
+ logDebug(logLevel, 'No access token available, proceeding without Authorization header');
1011
+ }
1012
+ return next(request).pipe(catchError((error) => {
1013
+ // Handle 401 Unauthorized errors - attempt refresh if we have access token OR refresh token
1014
+ if (error.status === 401) {
1015
+ const refreshToken = storageService.getItem(OAUTH2_STORAGE_KEYS.REFRESH_TOKEN);
1016
+ if (accessToken || refreshToken) {
1017
+ logInfo(logLevel, '401 error detected, attempting token refresh');
1018
+ logDebug(logLevel, 'Has access token:', !!accessToken, 'Has refresh token:', !!refreshToken);
1019
+ return handle401Error(request, next, config, storageService, logLevel);
1020
+ }
1021
+ else {
1022
+ logInfo(logLevel, '401 error but no tokens available for refresh');
1023
+ }
1024
+ }
1025
+ return throwError(() => error);
1026
+ }));
1027
+ };
1028
+ /**
1029
+ * Check if token is valid (not expired)
1030
+ */
1031
+ function isTokenValid(storageService) {
1032
+ const expiresAtStr = storageService.getItem(OAUTH2_STORAGE_KEYS.TOKEN_EXPIRES_AT);
1033
+ if (!expiresAtStr) {
1034
+ return false;
1035
+ }
1036
+ const expiresAt = parseInt(expiresAtStr, 10);
1037
+ return Date.now() < expiresAt;
1038
+ }
1039
+ /**
1040
+ * Check if request should be intercepted
1041
+ */
1042
+ function shouldInterceptRequest(request, config) {
1043
+ // Exclude token refresh requests to avoid circular dependency
1044
+ if (request.url === config.tokenEndpoint) {
1045
+ return false;
1046
+ }
1047
+ // Exclude revoke requests
1048
+ if (config.revokeEndpoint && request.url === config.revokeEndpoint) {
1049
+ return false;
1050
+ }
1051
+ // You can customize this logic based on your needs
1052
+ // For example, only intercept requests to specific domains or paths
1053
+ return true;
1054
+ }
1055
+ /**
1056
+ * Add Bearer token to request headers
1057
+ */
1058
+ function addTokenToRequest(request, token) {
1059
+ return request.clone({
1060
+ setHeaders: {
1061
+ Authorization: `Bearer ${token}`
1062
+ }
1063
+ });
1064
+ }
1065
+ /**
1066
+ * Handle 401 Unauthorized errors by attempting token refresh
1067
+ */
1068
+ function handle401Error(request, next, config, storageService, logLevel) {
1069
+ if (!isRefreshing) {
1070
+ isRefreshing = true;
1071
+ refreshTokenSubject.next(null);
1072
+ const refreshToken = storageService.getItem(OAUTH2_STORAGE_KEYS.REFRESH_TOKEN);
1073
+ if (!refreshToken) {
1074
+ isRefreshing = false;
1075
+ logInfo(logLevel, 'No refresh token available');
1076
+ return throwError(() => new Error('No refresh token available'));
1077
+ }
1078
+ // Create token refresh request directly using HttpRequest
1079
+ const tokenRequestData = {
1080
+ grant_type: 'refresh_token',
1081
+ refresh_token: refreshToken,
1082
+ client_id: config.clientId
1083
+ };
1084
+ // Convert to URL-encoded form data as per OAuth 2.0 standard
1085
+ const formData = new URLSearchParams();
1086
+ Object.entries(tokenRequestData).forEach(([key, value]) => {
1087
+ if (value !== undefined) {
1088
+ formData.append(key, value.toString());
1089
+ }
1090
+ });
1091
+ const headers = new HttpHeaders({
1092
+ 'Content-Type': 'application/x-www-form-urlencoded'
1093
+ });
1094
+ const refreshRequest = new HttpRequest('POST', config.tokenEndpoint, formData.toString(), {
1095
+ headers: headers
1096
+ });
1097
+ return next(refreshRequest).pipe(filter((event) => event instanceof HttpResponse), switchMap((event) => {
1098
+ const tokenResponse = event.body;
1099
+ isRefreshing = false;
1100
+ if (tokenResponse?.access_token) {
1101
+ // Store new tokens
1102
+ storageService.setItem(OAUTH2_STORAGE_KEYS.ACCESS_TOKEN, tokenResponse.access_token);
1103
+ storageService.setItem(OAUTH2_STORAGE_KEYS.TOKEN_EXPIRES_AT, (Date.now() + (tokenResponse.expires_in * 1000)).toString());
1104
+ if (tokenResponse.refresh_token) {
1105
+ storageService.setItem(OAUTH2_STORAGE_KEYS.REFRESH_TOKEN, tokenResponse.refresh_token);
1106
+ }
1107
+ refreshTokenSubject.next(tokenResponse.access_token);
1108
+ logInfo(logLevel, 'Token refreshed successfully, retrying original request');
1109
+ // Retry the original request with new token
1110
+ return next(addTokenToRequest(request, tokenResponse.access_token));
1111
+ }
1112
+ else {
1113
+ throw new Error('No access token in refresh response');
1114
+ }
1115
+ }), catchError(error => {
1116
+ isRefreshing = false;
1117
+ refreshTokenSubject.next(null);
1118
+ logError(logLevel, 'Token refresh failed:', error);
1119
+ // Check if it's an authentication error (invalid refresh token)
1120
+ if (error?.status === 400 || error?.status === 401) {
1121
+ logInfo(logLevel, 'Refresh token is invalid, clearing tokens');
1122
+ // Clear all OAuth2 tokens from storage
1123
+ storageService.clearAll();
1124
+ // Optionally redirect to login or emit an event
1125
+ // This depends on your application's requirements
1126
+ }
1127
+ else {
1128
+ logInfo(logLevel, 'Network/server error, not clearing tokens');
1129
+ }
1130
+ return throwError(() => error);
1131
+ }));
1132
+ }
1133
+ else {
1134
+ // Wait for refresh to complete, then retry request
1135
+ return refreshTokenSubject.pipe(filter(token => token != null), take(1), switchMap(token => next(addTokenToRequest(request, token))));
1136
+ }
1137
+ }
1138
+ /**
1139
+ * Debug logging
1140
+ */
1141
+ function logDebug(logLevel, message, ...args) {
1142
+ if (logLevel === 'debug') {
1143
+ console.log(`[OAuth2Interceptor] ${message}`, ...args);
1144
+ }
1145
+ }
1146
+ /**
1147
+ * Info logging
1148
+ */
1149
+ function logInfo(logLevel, message, ...args) {
1150
+ if (['debug', 'info'].includes(logLevel)) {
1151
+ console.info(`[OAuth2Interceptor] ${message}`, ...args);
1152
+ }
1153
+ }
1154
+ /**
1155
+ * Error logging
1156
+ */
1157
+ function logError(logLevel, message, error) {
1158
+ if (logLevel !== 'none') {
1159
+ console.error(`[OAuth2Interceptor] ${message}`, error);
1160
+ }
1161
+ }
1162
+
1163
+ /**
1164
+ * OAuth2 Callback Component
1165
+ * Handles the OAuth2 authorization callback and processes the authorization code
1166
+ */
1167
+ class OAuth2CallbackComponent {
1168
+ oauth2Service;
1169
+ router;
1170
+ platformId;
1171
+ config;
1172
+ isLoading = true;
1173
+ error = null;
1174
+ success = false;
1175
+ constructor(oauth2Service, router, platformId, config) {
1176
+ this.oauth2Service = oauth2Service;
1177
+ this.router = router;
1178
+ this.platformId = platformId;
1179
+ this.config = config;
1180
+ }
1181
+ async ngOnInit() {
1182
+ // Only handle callback in browser environment
1183
+ if (!isPlatformBrowser(this.platformId)) {
1184
+ this.isLoading = false;
1185
+ this.error = 'Browser environment required for OAuth2 callback';
1186
+ return;
1187
+ }
1188
+ // Add a small delay to ensure the component is fully rendered on client side
1189
+ setTimeout(async () => {
1190
+ try {
1191
+ console.log('Starting OAuth2 callback processing...');
1192
+ console.log('Current URL:', window.location.href);
1193
+ console.log('LocalStorage available:', typeof (Storage) !== "undefined");
1194
+ // Handle the OAuth2 callback
1195
+ await this.oauth2Service.handleCallback();
1196
+ // Success
1197
+ this.isLoading = false;
1198
+ this.success = true;
1199
+ // Redirect after a short delay
1200
+ setTimeout(() => {
1201
+ // Use configurable redirect route from OAuth2Config, defaulting to '/'
1202
+ const redirectRoute = this.config.redirectRoute || '/';
1203
+ this.router.navigate([redirectRoute]);
1204
+ }, 2000);
1205
+ }
1206
+ catch (error) {
1207
+ console.error('OAuth2 callback error:', error);
1208
+ this.isLoading = false;
1209
+ this.error = error instanceof Error ? error.message : 'Authentication failed';
1210
+ }
1211
+ }, 100);
1212
+ }
1213
+ retryLogin() {
1214
+ if (!this.oauth2Service.isAuthenticationAvailable()) {
1215
+ this.error = 'Authentication not available in current environment';
1216
+ return;
1217
+ }
1218
+ this.isLoading = true;
1219
+ this.error = null;
1220
+ this.success = false;
1221
+ this.oauth2Service.startAuthorization().catch(error => {
1222
+ console.error('Retry login error:', error);
1223
+ this.isLoading = false;
1224
+ this.error = 'Failed to start authentication';
1225
+ });
1226
+ }
1227
+ goHome() {
1228
+ // Use configurable redirect route from OAuth2Config, defaulting to '/'
1229
+ const redirectRoute = this.config.redirectRoute || '/';
1230
+ this.router.navigate([redirectRoute]);
1231
+ }
1232
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: OAuth2CallbackComponent, deps: [{ token: OAuth2Service }, { token: i2.Router }, { token: PLATFORM_ID }, { token: OAUTH2_CONFIG_TOKEN }], target: i0.ɵɵFactoryTarget.Component });
1233
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "19.2.14", type: OAuth2CallbackComponent, isStandalone: true, selector: "lib-oauth2-callback", ngImport: i0, template: `
1234
+ <div class="oauth2-callback-container">
1235
+ <div class="oauth2-callback-content">
1236
+ <div *ngIf="isLoading" class="loading-section">
1237
+ <div class="spinner"></div>
1238
+ <h2>Processing Authentication...</h2>
1239
+ <p>Please wait while we complete your login.</p>
1240
+ </div>
1241
+
1242
+ <div *ngIf="success && !isLoading" class="success-section">
1243
+ <div class="success-icon">✓</div>
1244
+ <h2>Authentication Successful!</h2>
1245
+ <p>You will be redirected shortly...</p>
1246
+ </div>
1247
+
1248
+ <div *ngIf="error && !isLoading" class="error-section">
1249
+ <div class="error-icon">✗</div>
1250
+ <h2>Authentication Failed</h2>
1251
+ <p class="error-message">{{ error }}</p>
1252
+ <div class="error-actions">
1253
+ <button (click)="retryLogin()" class="retry-button">
1254
+ Try Again
1255
+ </button>
1256
+ <button (click)="goHome()" class="home-button">
1257
+ Go Home
1258
+ </button>
1259
+ </div>
1260
+ </div>
1261
+ </div>
1262
+ </div>
1263
+ `, isInline: true, styles: [".oauth2-callback-container{display:flex;justify-content:center;align-items:center;min-height:100vh;background-color:#f5f5f5;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif}.oauth2-callback-content{background:#fff;border-radius:8px;padding:2rem;box-shadow:0 4px 6px #0000001a;text-align:center;max-width:400px;width:100%;margin:1rem}.loading-section h2,.success-section h2,.error-section h2{margin:1rem 0 .5rem;color:#333}.loading-section p,.success-section p{color:#666;margin-bottom:0}.spinner{border:3px solid #f3f3f3;border-top:3px solid #007bff;border-radius:50%;width:40px;height:40px;animation:spin 1s linear infinite;margin:0 auto 1rem}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.success-icon{width:60px;height:60px;border-radius:50%;background-color:#28a745;color:#fff;display:flex;align-items:center;justify-content:center;font-size:2rem;font-weight:700;margin:0 auto 1rem}.error-icon{width:60px;height:60px;border-radius:50%;background-color:#dc3545;color:#fff;display:flex;align-items:center;justify-content:center;font-size:2rem;font-weight:700;margin:0 auto 1rem}.error-message{color:#dc3545;margin:1rem 0;padding:.5rem;background-color:#f8d7da;border:1px solid #f5c6cb;border-radius:4px;font-size:.9rem}.error-actions{display:flex;gap:1rem;justify-content:center;margin-top:1.5rem}.retry-button,.home-button{padding:.75rem 1.5rem;border:none;border-radius:4px;cursor:pointer;font-size:.9rem;font-weight:500;transition:background-color .2s}.retry-button{background-color:#007bff;color:#fff}.retry-button:hover{background-color:#0056b3}.home-button{background-color:#6c757d;color:#fff}.home-button:hover{background-color:#545b62}@media (max-width: 480px){.oauth2-callback-content{margin:.5rem;padding:1.5rem}.error-actions{flex-direction:column}.retry-button,.home-button{width:100%}}\n"], dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "directive", type: i3.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }] });
1264
+ }
1265
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: OAuth2CallbackComponent, decorators: [{
1266
+ type: Component,
1267
+ args: [{ selector: 'lib-oauth2-callback', standalone: true, imports: [CommonModule], template: `
1268
+ <div class="oauth2-callback-container">
1269
+ <div class="oauth2-callback-content">
1270
+ <div *ngIf="isLoading" class="loading-section">
1271
+ <div class="spinner"></div>
1272
+ <h2>Processing Authentication...</h2>
1273
+ <p>Please wait while we complete your login.</p>
1274
+ </div>
1275
+
1276
+ <div *ngIf="success && !isLoading" class="success-section">
1277
+ <div class="success-icon">✓</div>
1278
+ <h2>Authentication Successful!</h2>
1279
+ <p>You will be redirected shortly...</p>
1280
+ </div>
1281
+
1282
+ <div *ngIf="error && !isLoading" class="error-section">
1283
+ <div class="error-icon">✗</div>
1284
+ <h2>Authentication Failed</h2>
1285
+ <p class="error-message">{{ error }}</p>
1286
+ <div class="error-actions">
1287
+ <button (click)="retryLogin()" class="retry-button">
1288
+ Try Again
1289
+ </button>
1290
+ <button (click)="goHome()" class="home-button">
1291
+ Go Home
1292
+ </button>
1293
+ </div>
1294
+ </div>
1295
+ </div>
1296
+ </div>
1297
+ `, styles: [".oauth2-callback-container{display:flex;justify-content:center;align-items:center;min-height:100vh;background-color:#f5f5f5;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif}.oauth2-callback-content{background:#fff;border-radius:8px;padding:2rem;box-shadow:0 4px 6px #0000001a;text-align:center;max-width:400px;width:100%;margin:1rem}.loading-section h2,.success-section h2,.error-section h2{margin:1rem 0 .5rem;color:#333}.loading-section p,.success-section p{color:#666;margin-bottom:0}.spinner{border:3px solid #f3f3f3;border-top:3px solid #007bff;border-radius:50%;width:40px;height:40px;animation:spin 1s linear infinite;margin:0 auto 1rem}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.success-icon{width:60px;height:60px;border-radius:50%;background-color:#28a745;color:#fff;display:flex;align-items:center;justify-content:center;font-size:2rem;font-weight:700;margin:0 auto 1rem}.error-icon{width:60px;height:60px;border-radius:50%;background-color:#dc3545;color:#fff;display:flex;align-items:center;justify-content:center;font-size:2rem;font-weight:700;margin:0 auto 1rem}.error-message{color:#dc3545;margin:1rem 0;padding:.5rem;background-color:#f8d7da;border:1px solid #f5c6cb;border-radius:4px;font-size:.9rem}.error-actions{display:flex;gap:1rem;justify-content:center;margin-top:1.5rem}.retry-button,.home-button{padding:.75rem 1.5rem;border:none;border-radius:4px;cursor:pointer;font-size:.9rem;font-weight:500;transition:background-color .2s}.retry-button{background-color:#007bff;color:#fff}.retry-button:hover{background-color:#0056b3}.home-button{background-color:#6c757d;color:#fff}.home-button:hover{background-color:#545b62}@media (max-width: 480px){.oauth2-callback-content{margin:.5rem;padding:1.5rem}.error-actions{flex-direction:column}.retry-button,.home-button{width:100%}}\n"] }]
1298
+ }], ctorParameters: () => [{ type: OAuth2Service }, { type: i2.Router }, { type: Object, decorators: [{
1299
+ type: Inject,
1300
+ args: [PLATFORM_ID]
1301
+ }] }, { type: undefined, decorators: [{
1302
+ type: Inject,
1303
+ args: [OAUTH2_CONFIG_TOKEN]
1304
+ }] }] });
1305
+
1306
+ /**
1307
+ * OAuth2 Authentication Guard Function
1308
+ * Protects routes by checking if user is authenticated
1309
+ */
1310
+ const oauth2AuthGuard = (route, state) => {
1311
+ const oauth2Service = inject(OAuth2Service);
1312
+ const router = inject(Router);
1313
+ // Check if authentication is available in current environment
1314
+ if (!oauth2Service.isAuthenticationAvailable()) {
1315
+ console.warn('[OAuth2AuthGuard] Authentication not available in current environment');
1316
+ return false;
1317
+ }
1318
+ // Check current authentication state
1319
+ return oauth2Service.authState$.pipe(take(1), map(authState => {
1320
+ if (authState.isAuthenticated) {
1321
+ return true;
1322
+ }
1323
+ // Check if we have stored tokens that might be valid
1324
+ if (oauth2Service.isAuthenticated()) {
1325
+ return true;
1326
+ }
1327
+ // User is not authenticated, redirect to login or start OAuth flow
1328
+ console.log('[OAuth2AuthGuard] User not authenticated, starting OAuth2 flow');
1329
+ // You can customize this behavior:
1330
+ // Option 1: Start OAuth2 flow immediately
1331
+ oauth2Service.startAuthorization().catch(error => {
1332
+ console.error('[OAuth2AuthGuard] Failed to start OAuth2 flow:', error);
1333
+ });
1334
+ // Option 2: Redirect to a login page
1335
+ // router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
1336
+ return false;
1337
+ }));
1338
+ };
1339
+ /**
1340
+ * OAuth2 Authentication Guard Class (for backward compatibility)
1341
+ * @deprecated Use oauth2AuthGuard function instead
1342
+ */
1343
+ class OAuth2AuthGuard {
1344
+ oauth2Service;
1345
+ router;
1346
+ constructor(oauth2Service, router) {
1347
+ this.oauth2Service = oauth2Service;
1348
+ this.router = router;
1349
+ }
1350
+ canActivate(route, state) {
1351
+ // Check if authentication is available in current environment
1352
+ if (!this.oauth2Service.isAuthenticationAvailable()) {
1353
+ console.warn('[OAuth2AuthGuard] Authentication not available in current environment');
1354
+ return false;
1355
+ }
1356
+ // Check current authentication state
1357
+ return this.oauth2Service.authState$.pipe(take(1), map(authState => {
1358
+ if (authState.isAuthenticated) {
1359
+ return true;
1360
+ }
1361
+ // Check if we have stored tokens that might be valid
1362
+ if (this.oauth2Service.isAuthenticated()) {
1363
+ return true;
1364
+ }
1365
+ // User is not authenticated, redirect to login or start OAuth flow
1366
+ console.log('[OAuth2AuthGuard] User not authenticated, starting OAuth2 flow');
1367
+ this.oauth2Service.startAuthorization().catch(error => {
1368
+ console.error('[OAuth2AuthGuard] Failed to start OAuth2 flow:', error);
1369
+ });
1370
+ return false;
1371
+ }));
1372
+ }
1373
+ }
1374
+ /**
1375
+ * OAuth2 Unauthenticated Guard Function
1376
+ * Protects routes that should only be accessible to unauthenticated users
1377
+ * (e.g., login page, registration page)
1378
+ */
1379
+ const oauth2UnauthGuard = (route, state) => {
1380
+ const oauth2Service = inject(OAuth2Service);
1381
+ const router = inject(Router);
1382
+ // Check if authentication is available in current environment
1383
+ if (!oauth2Service.isAuthenticationAvailable()) {
1384
+ return true; // Allow access if auth is not available
1385
+ }
1386
+ // Check current authentication state
1387
+ return oauth2Service.authState$.pipe(take(1), map(authState => {
1388
+ if (!authState.isAuthenticated && !oauth2Service.isAuthenticated()) {
1389
+ return true; // User is not authenticated, allow access
1390
+ }
1391
+ // User is authenticated, redirect to protected area
1392
+ console.log('[OAuth2UnauthGuard] User already authenticated, redirecting');
1393
+ router.navigate(['/']); // Redirect to home or dashboard
1394
+ return false;
1395
+ }));
1396
+ };
1397
+ function oauth2RoleGuard(config) {
1398
+ return (route, state) => {
1399
+ const oauth2Service = inject(OAuth2Service);
1400
+ const router = inject(Router);
1401
+ // First check if user is authenticated
1402
+ if (!oauth2Service.isAuthenticated()) {
1403
+ console.log('[OAuth2RoleGuard] User not authenticated');
1404
+ oauth2Service.startAuthorization().catch(error => {
1405
+ console.error('[OAuth2RoleGuard] Failed to start OAuth2 flow:', error);
1406
+ });
1407
+ return false;
1408
+ }
1409
+ // If no roles or permissions specified, just check authentication
1410
+ if (!config.roles?.length && !config.permissions?.length) {
1411
+ return true;
1412
+ }
1413
+ // Get user info to check roles/permissions
1414
+ return oauth2Service.getUserInfo().then(userInfo => {
1415
+ const userRoles = userInfo.roles || [];
1416
+ const userPermissions = userInfo.permissions || [];
1417
+ let hasRequiredRoles = true;
1418
+ let hasRequiredPermissions = true;
1419
+ // Check roles
1420
+ if (config.roles?.length) {
1421
+ if (config.requireAll) {
1422
+ hasRequiredRoles = config.roles.every(role => userRoles.includes(role));
1423
+ }
1424
+ else {
1425
+ hasRequiredRoles = config.roles.some(role => userRoles.includes(role));
1426
+ }
1427
+ }
1428
+ // Check permissions
1429
+ if (config.permissions?.length) {
1430
+ if (config.requireAll) {
1431
+ hasRequiredPermissions = config.permissions.every(permission => userPermissions.includes(permission));
1432
+ }
1433
+ else {
1434
+ hasRequiredPermissions = config.permissions.some(permission => userPermissions.includes(permission));
1435
+ }
1436
+ }
1437
+ const hasAccess = hasRequiredRoles && hasRequiredPermissions;
1438
+ if (!hasAccess) {
1439
+ console.warn('[OAuth2RoleGuard] User does not have required roles/permissions');
1440
+ router.navigate(['/unauthorized']); // Redirect to unauthorized page
1441
+ }
1442
+ return hasAccess;
1443
+ }).catch(error => {
1444
+ console.error('[OAuth2RoleGuard] Failed to get user info:', error);
1445
+ return false;
1446
+ });
1447
+ };
1448
+ }
1449
+
1450
+ /**
1451
+ * Provide OAuth2 configuration and services
1452
+ * Use this function in your app.config.ts or main.ts
1453
+ */
1454
+ function provideOAuth2(config) {
1455
+ return makeEnvironmentProviders([
1456
+ // Provide the OAuth2 configuration
1457
+ { provide: OAUTH2_CONFIG_TOKEN, useValue: config },
1458
+ // Provide the OAuth2 services
1459
+ OAuth2Service,
1460
+ OAuth2StorageService,
1461
+ // Provide HTTP client with OAuth2 interceptor
1462
+ provideHttpClient(withInterceptors([oauth2InterceptorFn]))
1463
+ ]);
1464
+ }
1465
+ /**
1466
+ * Provide OAuth2 configuration and services without HTTP interceptor
1467
+ * Use this if you want to manually configure the HTTP interceptor
1468
+ */
1469
+ function provideOAuth2WithoutInterceptor(config) {
1470
+ return makeEnvironmentProviders([
1471
+ // Provide the OAuth2 configuration
1472
+ { provide: OAUTH2_CONFIG_TOKEN, useValue: config },
1473
+ // Provide the OAuth2 services
1474
+ OAuth2Service,
1475
+ OAuth2StorageService
1476
+ ]);
1477
+ }
1478
+ class NgOAuth2PkceModule {
1479
+ static forRoot(config) {
1480
+ return {
1481
+ ngModule: NgOAuth2PkceModule,
1482
+ providers: [
1483
+ { provide: OAUTH2_CONFIG_TOKEN, useValue: config },
1484
+ OAuth2Service,
1485
+ OAuth2StorageService
1486
+ ]
1487
+ };
1488
+ }
1489
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: NgOAuth2PkceModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
1490
+ static ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "19.2.14", ngImport: i0, type: NgOAuth2PkceModule, imports: [CommonModule] });
1491
+ static ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: NgOAuth2PkceModule, imports: [CommonModule] });
1492
+ }
1493
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: NgOAuth2PkceModule, decorators: [{
1494
+ type: NgModule,
1495
+ args: [{
1496
+ imports: [CommonModule],
1497
+ exports: []
1498
+ }]
1499
+ }] });
1500
+
1501
+ /*
1502
+ * Public API Surface of ng-oauth2-pkce
1503
+ */
1504
+ // Export models
1505
+
1506
+ /**
1507
+ * Generated bundle index. Do not edit.
1508
+ */
1509
+
1510
+ export { NgOAuth2PkceModule, OAUTH2_CONFIG_TOKEN, OAUTH2_STORAGE_KEYS, OAuth2AuthGuard, OAuth2CallbackComponent, OAuth2Service, OAuth2StorageService, oauth2AuthGuard, oauth2InterceptorFn, oauth2RoleGuard, oauth2UnauthGuard, provideOAuth2, provideOAuth2WithoutInterceptor };
1511
+ //# sourceMappingURL=witspry-auth-ng-client.mjs.map