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