@igo2/auth 21.0.0-next.43 → 21.0.0-next.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,35 +1,50 @@
1
- import { HttpClient, HttpHeaders, HTTP_INTERCEPTORS } from '@angular/common/http';
1
+ import { HttpClient, HttpHeaders, HttpErrorResponse, ɵHTTP_ROOT_INTERCEPTOR_FNS as _HTTP_ROOT_INTERCEPTOR_FNS } from '@angular/common/http';
2
2
  import * as i0 from '@angular/core';
3
- import { inject, Injector, Injectable, InjectionToken, signal, makeEnvironmentProviders } from '@angular/core';
3
+ import { InjectionToken, inject, Injectable, signal, Injector, makeEnvironmentProviders } from '@angular/core';
4
4
  import { XHR_INTERCEPTOR } from '@igo2/core/auth';
5
+ import { ConfigService } from '@igo2/core/config';
5
6
  import { BaseStorage, StorageScope, StorageService } from '@igo2/core/storage';
6
7
  import { Router } from '@angular/router';
7
- import { ConfigService } from '@igo2/core/config';
8
8
  import { LanguageService } from '@igo2/core/language';
9
9
  import { MessageService } from '@igo2/core/message';
10
+ import { RouteService } from '@igo2/core/route';
10
11
  import { Base64 } from '@igo2/utils';
11
- import { BehaviorSubject, tap, of, Observable, Subject, EMPTY } from 'rxjs';
12
- import { finalize, tap as tap$1, catchError, switchMap, takeUntil, debounceTime, map } from 'rxjs/operators';
12
+ import { BehaviorSubject, tap, ReplaySubject, of, throwError, Subject, EMPTY, firstValueFrom, Observable } from 'rxjs';
13
+ import { finalize, tap as tap$1, catchError, switchMap, takeUntil, debounceTime, take, map, shareReplay } from 'rxjs/operators';
13
14
  import { globalCacheBusterNotifier } from 'ts-cacheable';
14
15
  import { jwtDecode } from 'jwt-decode';
16
+ import { DOCUMENT, Location } from '@angular/common';
15
17
  import { Md5 } from 'ts-md5';
16
18
 
19
+ var AuthFeatureKind;
20
+ (function (AuthFeatureKind) {
21
+ AuthFeatureKind[AuthFeatureKind["Microsoft"] = 0] = "Microsoft";
22
+ AuthFeatureKind[AuthFeatureKind["User"] = 1] = "User";
23
+ AuthFeatureKind[AuthFeatureKind["Options"] = 2] = "Options";
24
+ })(AuthFeatureKind || (AuthFeatureKind = {}));
25
+ const AUTH_OPTIONS = new InjectionToken('AUTH_OPTIONS', {
26
+ providedIn: 'root',
27
+ factory: () => ({})
28
+ });
29
+
17
30
  class TokenService {
18
- injector = inject(Injector);
19
- options;
20
- tokenKey;
21
- constructor() {
22
- const config = this.injector.get(ConfigService);
23
- this.options = config.getConfig('auth');
24
- this.tokenKey = this.options?.tokenKey ?? '';
25
- }
31
+ tokenKey = inject(AUTH_OPTIONS).tokenKey;
26
32
  set(token) {
33
+ if (!this.tokenKey) {
34
+ return;
35
+ }
27
36
  localStorage.setItem(this.tokenKey, token);
28
37
  }
29
38
  remove() {
39
+ if (!this.tokenKey) {
40
+ return;
41
+ }
30
42
  localStorage.removeItem(this.tokenKey);
31
43
  }
32
44
  get() {
45
+ if (!this.tokenKey) {
46
+ return;
47
+ }
33
48
  return localStorage.getItem(this.tokenKey) ?? undefined;
34
49
  }
35
50
  decode() {
@@ -39,23 +54,30 @@ class TokenService {
39
54
  }
40
55
  return jwtDecode(token);
41
56
  }
42
- isExpired() {
57
+ getStatus(nearExpirySeconds = 1800) {
43
58
  const jwt = this.decode();
44
- const currentTime = new Date().getTime() / 1000;
45
- if (jwt?.exp && currentTime < jwt.exp) {
46
- return false;
59
+ if (!jwt) {
60
+ return 'missing';
47
61
  }
48
- return true;
62
+ const currentTime = Date.now() / 1000;
63
+ if (jwt.exp === undefined || currentTime >= jwt.exp) {
64
+ return 'expired';
65
+ }
66
+ return currentTime > jwt.exp - nearExpirySeconds ? 'near-expiry' : 'valid';
67
+ }
68
+ isExpired() {
69
+ const status = this.getStatus();
70
+ return status === 'missing' || status === 'expired';
49
71
  }
50
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: TokenService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
51
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: TokenService, providedIn: 'root' });
72
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: TokenService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
73
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: TokenService, providedIn: 'root' });
52
74
  }
53
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: TokenService, decorators: [{
75
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: TokenService, decorators: [{
54
76
  type: Injectable,
55
77
  args: [{
56
78
  providedIn: 'root'
57
79
  }]
58
- }], ctorParameters: () => [] });
80
+ }] });
59
81
 
60
82
  const USER_AUTH_OPTIONS = new InjectionToken('USER_AUTH_OPTIONS');
61
83
  class UserService {
@@ -80,10 +102,10 @@ class UserService {
80
102
  updatePreference(preference) {
81
103
  return this.http.patch(this.baseUrl, { preference });
82
104
  }
83
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: UserService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
84
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: UserService });
105
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: UserService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
106
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: UserService });
85
107
  }
86
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: UserService, decorators: [{
108
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: UserService, decorators: [{
87
109
  type: Injectable
88
110
  }], ctorParameters: () => [] });
89
111
 
@@ -93,32 +115,48 @@ class AuthService {
93
115
  userService = inject(UserService, {
94
116
  optional: true
95
117
  });
96
- config = inject(ConfigService);
97
- languageService = inject(LanguageService);
118
+ languageService = inject(LanguageService, { optional: true });
98
119
  messageService = inject(MessageService);
99
- router = inject(Router, { optional: true });
120
+ router = inject(Router);
121
+ routeService = inject(RouteService);
100
122
  authenticate$ = new BehaviorSubject(false);
101
123
  logged$ = new BehaviorSubject(false);
124
+ initialized$ = new ReplaySubject(1);
102
125
  redirectUrl;
103
126
  languageForce = false;
104
127
  authOptions;
105
128
  anonymous = false;
106
129
  isLogging = signal(false, ...(ngDevMode ? [{ debugName: "isLogging" }] : /* istanbul ignore next */ []));
107
- get hasAuthService() {
108
- return this.authOptions?.url !== undefined;
109
- }
110
- get user() {
111
- const decodedToken = this.decodeToken();
112
- return decodedToken?.user ? decodedToken.user : null;
113
- }
114
130
  constructor() {
115
- this.authOptions = this.config.getConfig('auth');
131
+ this.authOptions = inject(AUTH_OPTIONS);
116
132
  this.initializeAuthentication(this.authenticated).subscribe();
117
133
  this.authenticate$.subscribe((authenticated) => {
118
134
  this.logged$.next(authenticated);
119
135
  globalCacheBusterNotifier.next();
120
136
  });
121
137
  }
138
+ get hasAuthService() {
139
+ return Boolean(this.authOptions.url);
140
+ }
141
+ get user() {
142
+ if (!this.isAuthenticated()) {
143
+ return null;
144
+ }
145
+ const decodedToken = this.tokenService.decode();
146
+ return decodedToken?.user ? decodedToken.user : null;
147
+ }
148
+ get logged() {
149
+ return this.authenticated || this.isAnonymous;
150
+ }
151
+ get isAnonymous() {
152
+ return this.anonymous;
153
+ }
154
+ get authenticated() {
155
+ return this.isAuthenticated();
156
+ }
157
+ get isAdmin() {
158
+ return this.user?.isAdmin ?? false;
159
+ }
122
160
  login(username, password) {
123
161
  this.isLogging.set(true);
124
162
  const myHeader = new HttpHeaders({ 'Content-Type': 'application/json' });
@@ -144,125 +182,139 @@ class AuthService {
144
182
  return of(true);
145
183
  }
146
184
  refresh() {
147
- return this.http.post(`${this.authOptions?.url}/refresh`, {}).pipe(tap$1((data) => {
185
+ const url = this.getAuthenticationUrl('refresh');
186
+ if (!url) {
187
+ return this.authenticationNotConfigured();
188
+ }
189
+ return this.http.post(url, {}).pipe(tap$1((data) => {
148
190
  this.tokenService.set(data.token);
149
191
  }), catchError((err) => {
150
- err.error.caught = true;
192
+ if (err.error && typeof err.error === 'object') {
193
+ err.error.caught = true;
194
+ }
195
+ this.expireSession();
151
196
  throw err;
152
197
  }));
153
198
  }
154
199
  logout() {
155
200
  this.logoutInternal();
156
- if (this.authOptions.logoutRedirectRoute) {
201
+ if (this.authOptions?.logoutRedirectRoute) {
157
202
  this.router?.navigate([this.authOptions.logoutRedirectRoute]);
158
203
  }
159
204
  }
160
- logoutInternal() {
161
- this.anonymous = false;
162
- this.tokenService.remove();
163
- this.authenticate$.next(false);
205
+ expireSession(redirectUrl = this.router.url) {
206
+ this.redirectUrl = redirectUrl;
207
+ this.logoutInternal();
208
+ this.navigateToLogin();
164
209
  }
165
210
  isAuthenticated() {
166
211
  return !this.tokenService.isExpired();
167
212
  }
168
- getToken() {
169
- return this.tokenService.get();
170
- }
171
- decodeToken() {
172
- if (this.isAuthenticated()) {
173
- return this.tokenService.decode();
174
- }
175
- return;
176
- }
177
213
  goToRedirectUrl() {
178
214
  if (!this.router) {
179
215
  return;
180
216
  }
181
- const redirectUrl = this.redirectUrl ?? this.authOptions.homeRoute ?? '/';
217
+ const redirectUrl = this.redirectUrl ?? this.authOptions?.homeRoute ?? '/';
182
218
  this.router.navigateByUrl(redirectUrl);
183
219
  }
184
220
  getUserInfo() {
185
- const url = this.authOptions?.url + '/info';
221
+ const url = this.getAuthenticationUrl('info');
222
+ if (!url) {
223
+ return this.authenticationNotConfigured();
224
+ }
186
225
  return this.http.get(url);
187
226
  }
188
227
  getProfils() {
189
- return this.http.get(`${this.authOptions?.url}/profils`);
228
+ const url = this.getAuthenticationUrl('profils');
229
+ if (!url) {
230
+ return this.authenticationNotConfigured();
231
+ }
232
+ return this.http.get(url);
190
233
  }
191
234
  updateUser(user) {
192
- return this.http.patch(this.authOptions?.url, user);
193
- }
194
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
195
- translateError(prefix, error) {
196
- return new Observable((observer) => {
197
- try {
198
- this.languageService.translate
199
- .get(prefix + error.error.message)
200
- .subscribe((errorMsg) => {
201
- observer.next(errorMsg);
202
- observer.complete();
203
- });
235
+ const url = this.getAuthenticationUrl();
236
+ if (!url) {
237
+ return this.authenticationNotConfigured();
238
+ }
239
+ return this.http.patch(url, user);
240
+ }
241
+ redirectToLogin(route, state) {
242
+ this.redirectUrl = state.url;
243
+ const langKey = this.routeService.options.languageKey ?? 'lang';
244
+ const langValue = route.queryParams[langKey];
245
+ this.navigateToLogin(langValue ? { [langKey]: langValue } : {});
246
+ }
247
+ loginCall(body, headers) {
248
+ const url = this.getAuthenticationUrl('login');
249
+ if (!url) {
250
+ return this.authenticationNotConfigured();
251
+ }
252
+ return this.http.post(url, body, { headers }).pipe(tap$1((data) => {
253
+ this.tokenService.set(data.token);
254
+ const user = this.user;
255
+ if (!user) {
256
+ return;
204
257
  }
205
- catch {
206
- if (error.error)
207
- observer.next(error.error.message);
208
- observer.complete();
258
+ if (user.locale && !this.languageForce) {
259
+ this.languageService?.setLanguage(user.locale);
209
260
  }
210
- });
211
- }
212
- encodePassword(password) {
213
- return Base64.encode(password);
261
+ if (user.isExpired) {
262
+ this.messageService.alert('igo.auth.error.intern.Password expired');
263
+ }
264
+ }), switchMap(() => this.initializeAuthentication(true)));
214
265
  }
215
- // authenticated or anonymous
216
- get logged() {
217
- return this.authenticated || this.isAnonymous;
266
+ getAuthenticationUrl(path) {
267
+ const url = this.authOptions.url;
268
+ if (!url) {
269
+ return;
270
+ }
271
+ return path ? `${url}/${path}` : url;
218
272
  }
219
- get isAnonymous() {
220
- return this.anonymous;
273
+ authenticationNotConfigured() {
274
+ return throwError(() => new Error('Authentication is not configured.'));
221
275
  }
222
- get authenticated() {
223
- return this.isAuthenticated();
276
+ logoutInternal() {
277
+ this.anonymous = false;
278
+ this.tokenService.remove();
279
+ this.authenticate$.next(false);
280
+ this.initialized$.next(false);
224
281
  }
225
- get isAdmin() {
226
- const token = this.decodeToken();
227
- if (token?.user?.isAdmin) {
228
- return true;
282
+ navigateToLogin(queryParams = {}) {
283
+ if (!this.authOptions?.loginRoute) {
284
+ return;
229
285
  }
230
- return false;
286
+ this.router.navigate([this.authOptions.loginRoute], { queryParams });
231
287
  }
232
- loginCall(body, headers) {
233
- return this.http
234
- .post(`${this.authOptions?.url}/login`, body, { headers })
235
- .pipe(tap$1((data) => {
236
- this.tokenService.set(data.token);
237
- const tokenDecoded = this.decodeToken();
238
- if (tokenDecoded?.user) {
239
- if (tokenDecoded.user.locale && !this.languageForce) {
240
- this.languageService.setLanguage(tokenDecoded.user.locale);
241
- }
242
- if (tokenDecoded.user.isExpired) {
243
- this.messageService.alert('igo.auth.error.intern.Password expired');
244
- }
245
- }
246
- }), switchMap(() => this.initializeAuthentication(true)));
288
+ encodePassword(password) {
289
+ return Base64.encode(password);
247
290
  }
248
291
  initializeAuthentication(isAuthenticated) {
249
292
  if (!isAuthenticated) {
250
293
  this.authenticate$.next(false);
294
+ this.initialized$.next(false);
251
295
  return of(null);
252
296
  }
253
297
  if (this.userService) {
254
- const obs$ = this.authOptions.user?.withSync
298
+ const obs$ = this.authOptions?.user?.withSync
255
299
  ? this.userService.sync()
256
300
  : this.userService.getUser();
257
- return obs$.pipe(tap$1(() => this.authenticate$.next(true)));
301
+ return obs$.pipe(tap$1(() => {
302
+ this.authenticate$.next(true);
303
+ this.initialized$.next(true);
304
+ }), catchError(() => {
305
+ this.authenticate$.next(false);
306
+ this.initialized$.next(false);
307
+ return of(null);
308
+ }));
258
309
  }
259
310
  this.authenticate$.next(true);
311
+ this.initialized$.next(true);
260
312
  return of(null);
261
313
  }
262
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: AuthService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
263
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: AuthService, providedIn: 'root' });
314
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: AuthService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
315
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: AuthService, providedIn: 'root' });
264
316
  }
265
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: AuthService, decorators: [{
317
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: AuthService, decorators: [{
266
318
  type: Injectable,
267
319
  args: [{
268
320
  providedIn: 'root'
@@ -284,10 +336,10 @@ class AdminGuard {
284
336
  }
285
337
  return false;
286
338
  }
287
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: AdminGuard, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
288
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: AdminGuard, providedIn: 'root' });
339
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: AdminGuard, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
340
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: AdminGuard, providedIn: 'root' });
289
341
  }
290
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: AdminGuard, decorators: [{
342
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: AdminGuard, decorators: [{
291
343
  type: Injectable,
292
344
  args: [{
293
345
  providedIn: 'root'
@@ -385,10 +437,10 @@ class AuthStorageService extends BaseStorage {
385
437
  });
386
438
  }
387
439
  }
388
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: AuthStorageService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
389
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: AuthStorageService, providedIn: 'root' });
440
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: AuthStorageService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
441
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: AuthStorageService, providedIn: 'root' });
390
442
  }
391
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: AuthStorageService, decorators: [{
443
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: AuthStorageService, decorators: [{
392
444
  type: Injectable,
393
445
  args: [{
394
446
  providedIn: 'root'
@@ -397,23 +449,19 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.24", ngImpo
397
449
 
398
450
  class AuthGuard {
399
451
  authService = inject(AuthService);
400
- config = inject(ConfigService);
401
- router = inject(Router);
402
452
  canActivate(route, state) {
403
- if (this.authService.authenticated) {
404
- return true;
405
- }
406
- this.authService.redirectUrl = state.url;
407
- const authConfig = this.config.getConfig('auth');
408
- if (authConfig?.loginRoute) {
409
- this.router.navigateByUrl(authConfig.loginRoute);
410
- }
411
- return false;
453
+ return this.authService.initialized$.pipe(take(1), map((authenticated) => {
454
+ if (authenticated) {
455
+ return true;
456
+ }
457
+ this.authService.redirectToLogin(route, state);
458
+ return false;
459
+ }));
412
460
  }
413
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: AuthGuard, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
414
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: AuthGuard, providedIn: 'root' });
461
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: AuthGuard, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
462
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: AuthGuard, providedIn: 'root' });
415
463
  }
416
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: AuthGuard, decorators: [{
464
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: AuthGuard, decorators: [{
417
465
  type: Injectable,
418
466
  args: [{
419
467
  providedIn: 'root'
@@ -421,20 +469,23 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.24", ngImpo
421
469
  }] });
422
470
 
423
471
  class AuthInterceptor {
424
- config = inject(ConfigService);
425
472
  tokenService = inject(TokenService);
426
- http = inject(HttpClient);
427
- authOptions;
428
- refreshInProgress = false;
473
+ injector = inject(Injector);
474
+ document = inject(DOCUMENT);
475
+ location = inject(Location);
476
+ authOptions = inject(AUTH_OPTIONS);
477
+ refreshRequest$;
429
478
  trustHosts;
430
479
  hostsWithCredentials;
431
480
  hostsWithAuthByKey;
432
481
  constructor() {
433
- this.authOptions = this.config.getConfig('auth');
434
- this.trustHosts = this.authOptions?.trustHosts || [];
435
- this.trustHosts.push(window.location.hostname);
436
- this.hostsWithCredentials = this.authOptions?.hostsWithCredentials || [];
437
- this.hostsWithAuthByKey = this.authOptions?.hostsByKey || [];
482
+ this.trustHosts = [...(this.authOptions.trustHosts ?? [])];
483
+ const applicationUrl = new URL(this.location.prepareExternalUrl('/'), this.document.baseURI);
484
+ if (!this.trustHosts.includes(applicationUrl.hostname)) {
485
+ this.trustHosts.push(applicationUrl.hostname);
486
+ }
487
+ this.hostsWithCredentials = this.authOptions.hostsWithCredentials ?? [];
488
+ this.hostsWithAuthByKey = this.authOptions.hostsByKey ?? [];
438
489
  }
439
490
  intercept(originalReq, next) {
440
491
  const withCredentials = this.handleHostsWithCredentials(originalReq.url);
@@ -449,13 +500,23 @@ class AuthInterceptor {
449
500
  req = originalReq.clone({
450
501
  withCredentials
451
502
  });
452
- return next.handle(req);
503
+ return next.handle(req).pipe(this.catchUnauthorized(req));
504
+ }
505
+ const isAuthenticationRequest = this.isAuthenticationRequest(req.url);
506
+ if (isAuthenticationRequest) {
507
+ return next.handle(req).pipe(this.catchUnauthorized(req));
453
508
  }
454
- this.refreshToken();
509
+ const refresh$ = this.isTrustedHost(req.url)
510
+ ? this.refreshToken()
511
+ : undefined;
512
+ if (refresh$) {
513
+ return refresh$.pipe(switchMap(() => this.forwardRequest(req, next)));
514
+ }
515
+ return this.forwardRequest(req, next);
516
+ }
517
+ forwardRequest(req, next) {
455
518
  const token = this.tokenService.get();
456
- const element = document.createElement('a');
457
- element.href = req.url;
458
- if (!token || this.trustHosts.indexOf(element.hostname) === -1) {
519
+ if (!token || !this.isTrustedHost(req.url)) {
459
520
  return next.handle(req);
460
521
  }
461
522
  const authHeader = `Bearer ${token}`;
@@ -474,7 +535,33 @@ class AuthInterceptor {
474
535
  params: authReq.params.delete('_i')
475
536
  });
476
537
  }
477
- return next.handle(authReq);
538
+ return next.handle(authReq).pipe(this.catchUnauthorized(authReq));
539
+ }
540
+ async prepareXhr(url) {
541
+ if (this.handleHostsWithCredentials(url) ||
542
+ this.isAuthenticationRequest(url) ||
543
+ !this.isTrustedHost(url)) {
544
+ return true;
545
+ }
546
+ const status = this.tokenService.getStatus();
547
+ if (status === 'expired') {
548
+ this.expireSession();
549
+ return false;
550
+ }
551
+ if (status !== 'near-expiry') {
552
+ return true;
553
+ }
554
+ const refresh$ = this.refreshToken();
555
+ if (!refresh$) {
556
+ return true;
557
+ }
558
+ try {
559
+ await firstValueFrom(refresh$);
560
+ return true;
561
+ }
562
+ catch {
563
+ return false;
564
+ }
478
565
  }
479
566
  interceptXhr(xhr, url) {
480
567
  const withCredentials = this.handleHostsWithCredentials(url);
@@ -482,11 +569,11 @@ class AuthInterceptor {
482
569
  xhr.withCredentials = withCredentials;
483
570
  return true;
484
571
  }
485
- this.refreshToken();
486
- const element = document.createElement('a');
487
- element.href = url;
572
+ if (!this.isAuthenticationRequest(url)) {
573
+ this.refreshToken()?.subscribe({ error: () => undefined });
574
+ }
488
575
  const token = this.tokenService.get();
489
- if (!token || this.trustHosts.indexOf(element.hostname) === -1) {
576
+ if (!token || !this.isTrustedHost(url)) {
490
577
  return false;
491
578
  }
492
579
  xhr.setRequestHeader('Authorization', 'Bearer ' + token);
@@ -545,41 +632,88 @@ class AuthInterceptor {
545
632
  }
546
633
  return hostWithKey;
547
634
  }
635
+ catchUnauthorized(req) {
636
+ return catchError((error) => {
637
+ if (error instanceof HttpErrorResponse &&
638
+ error.status === 401 &&
639
+ !this.isAuthenticationRequest(req.url) &&
640
+ this.tokenService.isExpired()) {
641
+ this.expireSession();
642
+ }
643
+ return throwError(() => error);
644
+ });
645
+ }
646
+ isAuthenticationRequest(url) {
647
+ const authUrl = this.authOptions?.url;
648
+ if (!authUrl) {
649
+ return false;
650
+ }
651
+ const requestUrl = new URL(url, this.document.baseURI);
652
+ const loginUrl = this.createAuthenticationUrl(authUrl, 'login');
653
+ const refreshUrl = this.createAuthenticationUrl(authUrl, 'refresh');
654
+ return [loginUrl, refreshUrl].some((authenticationUrl) => requestUrl.origin === authenticationUrl.origin &&
655
+ requestUrl.pathname === authenticationUrl.pathname);
656
+ }
657
+ createAuthenticationUrl(authUrl, path) {
658
+ const normalizedAuthUrl = authUrl.replace(/\/+$/, '');
659
+ return new URL(`${normalizedAuthUrl}/${path}`, this.document.baseURI);
660
+ }
661
+ isTrustedHost(url) {
662
+ const parsedUrl = new URL(url, this.document.baseURI);
663
+ return this.trustHosts.includes(parsedUrl.hostname);
664
+ }
665
+ expireSession() {
666
+ this.injector.get(AuthService).expireSession();
667
+ }
548
668
  refreshToken() {
549
- const jwt = this.tokenService.decode();
550
- const currentTime = new Date().getTime() / 1000;
551
- if (!this.refreshInProgress &&
552
- jwt?.exp &&
553
- currentTime < jwt.exp &&
554
- currentTime > jwt.exp - 1800) {
555
- this.refreshInProgress = true;
556
- const url = this.authOptions?.url;
557
- return this.http.post(`${url}/refresh`, {}).subscribe(
558
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
559
- (data) => {
560
- this.tokenService.set(data.token);
561
- this.refreshInProgress = false;
562
- }, (err) => {
563
- err.error.caught = true;
564
- return err;
565
- });
669
+ const status = this.tokenService.getStatus();
670
+ if (status === 'missing' || status === 'valid') {
671
+ return;
672
+ }
673
+ if (status === 'expired') {
674
+ this.expireSession();
675
+ return EMPTY;
566
676
  }
677
+ if (!this.refreshRequest$) {
678
+ const authService = this.injector.get(AuthService);
679
+ this.refreshRequest$ = authService.refresh().pipe(finalize(() => (this.refreshRequest$ = undefined)), shareReplay({ bufferSize: 1, refCount: false }));
680
+ }
681
+ return this.refreshRequest$;
567
682
  }
568
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: AuthInterceptor, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
569
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: AuthInterceptor, providedIn: 'root' });
683
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: AuthInterceptor, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
684
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: AuthInterceptor, providedIn: 'root' });
570
685
  }
571
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: AuthInterceptor, decorators: [{
686
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: AuthInterceptor, decorators: [{
572
687
  type: Injectable,
573
688
  args: [{
574
689
  providedIn: 'root'
575
690
  }]
576
691
  }], ctorParameters: () => [] });
692
+ const authInterceptorFn = (req, next) => {
693
+ const interceptor = inject(AuthInterceptor);
694
+ const handler = { handle: next };
695
+ return interceptor.intercept(req, handler);
696
+ };
577
697
 
578
- var AuthFeatureKind;
579
- (function (AuthFeatureKind) {
580
- AuthFeatureKind[AuthFeatureKind["Microsoft"] = 0] = "Microsoft";
581
- AuthFeatureKind[AuthFeatureKind["User"] = 1] = "User";
582
- })(AuthFeatureKind || (AuthFeatureKind = {}));
698
+ function translateError(prefix,
699
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
700
+ error, languageService) {
701
+ return new Observable((observer) => {
702
+ try {
703
+ languageService.translate
704
+ .get(prefix + error.error.message)
705
+ .subscribe((errorMsg) => {
706
+ observer.next(errorMsg);
707
+ observer.complete();
708
+ });
709
+ }
710
+ catch {
711
+ if (error.error)
712
+ observer.next(error.error.message);
713
+ observer.complete();
714
+ }
715
+ });
716
+ }
583
717
 
584
718
  class LoggedGuard {
585
719
  authService = inject(AuthService);
@@ -596,10 +730,10 @@ class LoggedGuard {
596
730
  }
597
731
  return false;
598
732
  }
599
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: LoggedGuard, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
600
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: LoggedGuard, providedIn: 'root' });
733
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: LoggedGuard, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
734
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: LoggedGuard, providedIn: 'root' });
601
735
  }
602
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: LoggedGuard, decorators: [{
736
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: LoggedGuard, decorators: [{
603
737
  type: Injectable,
604
738
  args: [{
605
739
  providedIn: 'root'
@@ -608,27 +742,26 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.24", ngImpo
608
742
 
609
743
  class ProfilsGuard {
610
744
  authService = inject(AuthService);
611
- config = inject(ConfigService);
612
- router = inject(Router);
613
- canActivate(_route, state) {
745
+ authOptions = inject(AUTH_OPTIONS);
746
+ canActivate(route, state) {
747
+ if (!this.authService.hasAuthService ||
748
+ !this.authOptions.profilsGuard?.length) {
749
+ this.authService.redirectToLogin(route, state);
750
+ return of(false);
751
+ }
614
752
  return this.authService.getProfils().pipe(map((profils) => {
615
- const authConfig = this.config.getConfig('auth');
616
- if (profils &&
617
- profils.profils &&
618
- profils.profils.some((v) => authConfig.profilsGuard?.indexOf(v) !== -1)) {
753
+ if (profils.profils.some((profil) => this.authOptions.profilsGuard?.includes(profil))) {
619
754
  return true;
620
755
  }
621
756
  this.authService.redirectUrl = state.url;
622
- if (authConfig?.loginRoute) {
623
- this.router.navigateByUrl(authConfig.loginRoute);
624
- }
757
+ this.authService.redirectToLogin(route, state);
625
758
  return false;
626
759
  }));
627
760
  }
628
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: ProfilsGuard, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
629
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: ProfilsGuard, providedIn: 'root' });
761
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: ProfilsGuard, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
762
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: ProfilsGuard, providedIn: 'root' });
630
763
  }
631
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.24", ngImport: i0, type: ProfilsGuard, decorators: [{
764
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: ProfilsGuard, decorators: [{
632
765
  type: Injectable,
633
766
  args: [{
634
767
  providedIn: 'root'
@@ -641,8 +774,8 @@ function withUserIgo() {
641
774
  providers: [
642
775
  {
643
776
  provide: USER_AUTH_OPTIONS,
644
- useFactory: (config) => config.getConfig('auth.user'),
645
- deps: [ConfigService]
777
+ useFactory: (authOptions) => authOptions.user,
778
+ deps: [AUTH_OPTIONS]
646
779
  },
647
780
  {
648
781
  provide: UserService,
@@ -658,11 +791,15 @@ function withUserIgo() {
658
791
  };
659
792
  }
660
793
 
661
- function provideAuthentification(...features) {
794
+ function provideAuthentification(options, ...features) {
662
795
  const providers = [
663
796
  {
664
- provide: HTTP_INTERCEPTORS,
665
- useClass: AuthInterceptor,
797
+ provide: AUTH_OPTIONS,
798
+ useFactory: () => resolveAuthOptions(options)
799
+ },
800
+ {
801
+ provide: _HTTP_ROOT_INTERCEPTOR_FNS,
802
+ useValue: authInterceptorFn,
666
803
  multi: true
667
804
  },
668
805
  {
@@ -679,6 +816,16 @@ function provideAuthentification(...features) {
679
816
  }
680
817
  return makeEnvironmentProviders(providers);
681
818
  }
819
+ /**
820
+ * Merges options passed explicitly via `withOptions` with the `auth`
821
+ * config entry, when a `ConfigService` is available. Explicit options take
822
+ * precedence over config values.
823
+ */
824
+ function resolveAuthOptions(explicitOptions) {
825
+ const config = inject(ConfigService, { optional: true });
826
+ const configOptions = config?.getConfig('auth');
827
+ return { ...configOptions, ...explicitOptions };
828
+ }
682
829
 
683
830
  /*
684
831
  * Public API Surface of auth
@@ -688,5 +835,5 @@ function provideAuthentification(...features) {
688
835
  * Generated bundle index. Do not edit.
689
836
  */
690
837
 
691
- export { AdminGuard, AuthFeatureKind, AuthGuard, AuthInterceptor, AuthService, AuthStorageService, LoggedGuard, ProfilsGuard, TokenService, USER_AUTH_OPTIONS, UserService, provideAuthentification, withUserIgo };
838
+ export { AUTH_OPTIONS, AdminGuard, AuthFeatureKind, AuthGuard, AuthInterceptor, AuthService, AuthStorageService, LoggedGuard, ProfilsGuard, TokenService, USER_AUTH_OPTIONS, UserService, authInterceptorFn, provideAuthentification, translateError, withUserIgo };
692
839
  //# sourceMappingURL=igo2-auth.mjs.map