@igo2/auth 21.0.0-next.8 → 21.0.0

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