@dontdrinkandroot/ngx-extensions 0.3.2 → 0.5.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.
Files changed (61) hide show
  1. package/esm2022/src/cookie/cookie.service.mjs +135 -0
  2. package/esm2022/src/ddr-extensions.module.mjs +67 -0
  3. package/esm2022/src/http/redirect-to-login-interceptor.service.mjs +35 -0
  4. package/{esm2020 → esm2022}/src/http/with-credentials-interceptor.service.mjs +4 -4
  5. package/esm2022/src/image/lazy-image.directive.mjs +132 -0
  6. package/esm2022/src/jwt/jwt-interceptor.service.mjs +26 -0
  7. package/esm2022/src/jwt/jwt-refresh-token-interceptor.service.mjs +50 -0
  8. package/{esm2020 → esm2022}/src/jwt/jwt.service.mjs +5 -5
  9. package/esm2022/src/logger/console-logger.service.mjs +43 -0
  10. package/esm2022/src/methoddecorator/limit.mjs +16 -0
  11. package/esm2022/src/oauth/oauth2-access-token-interceptor.service.mjs +26 -0
  12. package/esm2022/src/oauth/oauth2-error.mjs +8 -0
  13. package/esm2022/src/oauth/oauth2-refresh-token-interceptor.service.mjs +24 -0
  14. package/{esm2020 → esm2022}/src/oauth/oauth2.module.mjs +5 -5
  15. package/esm2022/src/oauth/oauth2.service.mjs +125 -0
  16. package/esm2022/src/oauth/redirect-to-oauth2-login-interceptor.service.mjs +41 -0
  17. package/esm2022/src/scroll/bottom-hit.directive.mjs +60 -0
  18. package/esm2022/src/scroll/scroll.service.mjs +38 -0
  19. package/esm2022/src/storage/local-storage.service.mjs +53 -0
  20. package/esm2022/src/util/collection-utils.mjs +27 -0
  21. package/{esm2020 → esm2022}/src/util/number-utils.mjs +1 -1
  22. package/esm2022/src/util/string-utils.mjs +35 -0
  23. package/esm2022/src/util/type-utils.mjs +9 -0
  24. package/{esm2020 → esm2022}/src/visibility/visibility.service.mjs +5 -5
  25. package/{fesm2020 → fesm2022}/dontdrinkandroot-ngx-extensions.mjs +102 -100
  26. package/{fesm2020 → fesm2022}/dontdrinkandroot-ngx-extensions.mjs.map +1 -1
  27. package/package.json +9 -15
  28. package/src/image/lazy-image.directive.d.ts +1 -1
  29. package/esm2020/src/cookie/cookie.service.mjs +0 -135
  30. package/esm2020/src/ddr-extensions.module.mjs +0 -67
  31. package/esm2020/src/http/redirect-to-login-interceptor.service.mjs +0 -35
  32. package/esm2020/src/image/lazy-image.directive.mjs +0 -132
  33. package/esm2020/src/jwt/jwt-interceptor.service.mjs +0 -26
  34. package/esm2020/src/jwt/jwt-refresh-token-interceptor.service.mjs +0 -50
  35. package/esm2020/src/logger/console-logger.service.mjs +0 -43
  36. package/esm2020/src/methoddecorator/limit.mjs +0 -16
  37. package/esm2020/src/oauth/oauth2-access-token-interceptor.service.mjs +0 -26
  38. package/esm2020/src/oauth/oauth2-error.mjs +0 -8
  39. package/esm2020/src/oauth/oauth2-refresh-token-interceptor.service.mjs +0 -24
  40. package/esm2020/src/oauth/oauth2.service.mjs +0 -125
  41. package/esm2020/src/oauth/redirect-to-oauth2-login-interceptor.service.mjs +0 -41
  42. package/esm2020/src/scroll/bottom-hit.directive.mjs +0 -60
  43. package/esm2020/src/scroll/scroll.service.mjs +0 -38
  44. package/esm2020/src/storage/local-storage.service.mjs +0 -53
  45. package/esm2020/src/util/collection-utils.mjs +0 -27
  46. package/esm2020/src/util/string-utils.mjs +0 -35
  47. package/esm2020/src/util/type-utils.mjs +0 -9
  48. package/fesm2015/dontdrinkandroot-ngx-extensions.mjs +0 -1132
  49. package/fesm2015/dontdrinkandroot-ngx-extensions.mjs.map +0 -1
  50. /package/{esm2020 → esm2022}/dontdrinkandroot-ngx-extensions.mjs +0 -0
  51. /package/{esm2020 → esm2022}/public-api.mjs +0 -0
  52. /package/{esm2020 → esm2022}/src/http/url-info.mjs +0 -0
  53. /package/{esm2020 → esm2022}/src/jwt/jwt-token-response.mjs +0 -0
  54. /package/{esm2020 → esm2022}/src/logger/logger.service.mjs +0 -0
  55. /package/{esm2020 → esm2022}/src/methoddecorator/debounce.mjs +0 -0
  56. /package/{esm2020 → esm2022}/src/oauth/json-web-token.mjs +0 -0
  57. /package/{esm2020 → esm2022}/src/oauth/oauth2-config.mjs +0 -0
  58. /package/{esm2020 → esm2022}/src/oauth/token-response.mjs +0 -0
  59. /package/{esm2020 → esm2022}/src/storage/storage.service.mjs +0 -0
  60. /package/{esm2020 → esm2022}/src/typeguard/is-non-null.mjs +0 -0
  61. /package/{esm2020 → esm2022}/src/util/object-utils.mjs +0 -0
@@ -1,1132 +0,0 @@
1
- import * as i0 from '@angular/core';
2
- import { Directive, Input, HostBinding, HostListener, EventEmitter, Output, Injectable, InjectionToken, Inject, NgModule } from '@angular/core';
3
- import { __decorate } from 'tslib';
4
- import * as i2 from '@angular/common';
5
- import { DOCUMENT } from '@angular/common';
6
- import * as i1 from '@angular/router';
7
- import { NavigationStart } from '@angular/router';
8
- import { merge, fromEvent, throwError } from 'rxjs';
9
- import { debounceTime, startWith, map, distinctUntilChanged, shareReplay, catchError, switchMap } from 'rxjs/operators';
10
- import * as i2$1 from '@angular/common/http';
11
- import { HttpErrorResponse, HttpParams, HTTP_INTERCEPTORS } from '@angular/common/http';
12
-
13
- class NumberUtils {
14
- static getNextPowerOfTwo(value) {
15
- let target = 2;
16
- while (target < value) {
17
- target *= 2;
18
- }
19
- return target;
20
- }
21
- }
22
-
23
- class StringUtils {
24
- static capitalizeFirstLetter(text) {
25
- return text.charAt(0).toUpperCase() + text.slice(1);
26
- }
27
- static stripTrailingSlash(text) {
28
- const lastChar = text.charAt(text.length - 1);
29
- if ('/' === lastChar) {
30
- return text.slice(0, text.length - 1);
31
- }
32
- return text;
33
- }
34
- static updateUrlParameter(uri, key, value) {
35
- // remove the hash part before operating on the uri
36
- const i = uri.indexOf('#');
37
- const hash = i === -1 ? '' : uri.substr(i);
38
- uri = i === -1 ? uri : uri.substr(0, i);
39
- const re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i');
40
- const separator = uri.indexOf('?') !== -1 ? '&' : '?';
41
- if (uri.match(re)) {
42
- uri = uri.replace(re, '$1' + key + '=' + value + '$2');
43
- }
44
- else {
45
- uri = uri + separator + key + '=' + value;
46
- }
47
- return uri + hash; // finally append the hash as well
48
- }
49
- static createRandomString(lengthOfCode, possible) {
50
- let text = '';
51
- for (let i = 0; i < lengthOfCode; i++) {
52
- text += possible.charAt(Math.floor(Math.random() * possible.length));
53
- }
54
- return text;
55
- }
56
- }
57
-
58
- function Debounce(delay = 250) {
59
- let timeoutReference = null;
60
- return (target, propertyKey, descriptor) => {
61
- const original = descriptor.value;
62
- descriptor.value = function (...args) {
63
- if (null != timeoutReference)
64
- clearTimeout(timeoutReference);
65
- timeoutReference = setTimeout(() => original.apply(this, args), delay);
66
- };
67
- return descriptor;
68
- };
69
- }
70
-
71
- function Limit(rate = 250) {
72
- let timeoutReference = null;
73
- return (target, propertyKey, descriptor) => {
74
- const original = descriptor.value;
75
- descriptor.value = function (...args) {
76
- if (null == timeoutReference) {
77
- timeoutReference = setTimeout(() => {
78
- original.apply(this, args);
79
- timeoutReference = undefined;
80
- }, rate);
81
- }
82
- };
83
- return descriptor;
84
- };
85
- }
86
-
87
- class LazyImageDirective {
88
- constructor(element, changeDetectorRef) {
89
- this.element = element;
90
- this.changeDetectorRef = changeDetectorRef;
91
- this.objectFit = 'contain';
92
- this.offset = 1000;
93
- this.hostSrc = 'assets/placeholder.gif';
94
- this.hostStyleObjectFit = 'contain';
95
- this.displayed = false;
96
- this.maxLoadedDimension = null;
97
- }
98
- windowResized($event) {
99
- this.displayed = false;
100
- this.check();
101
- }
102
- windowScroll($event) {
103
- this.check();
104
- }
105
- /**
106
- * @override
107
- */
108
- ngOnChanges(changes) {
109
- this.displayed = false;
110
- this.maxLoadedDimension = null;
111
- this.check();
112
- }
113
- check() {
114
- if (this.element.nativeElement.parentElement.offsetWidth > 0) {
115
- this.doCheck();
116
- }
117
- else {
118
- setTimeout(() => this.doCheck(), 1);
119
- }
120
- }
121
- doCheck() {
122
- if (this.displayed || this.isHidden(this.element.nativeElement)) {
123
- return;
124
- }
125
- if (this.isInsideViewport(this.element.nativeElement, this.offset)) {
126
- this.displayed = true;
127
- const dimension = this.getDimension();
128
- this.hostStyleWidthPx = dimension.width;
129
- this.hostStyleHeightPx = dimension.height;
130
- if (this.maxLoadedDimension != null
131
- && this.maxLoadedDimension.width >= dimension.width
132
- && this.maxLoadedDimension.height >= dimension.height) {
133
- // console.log('has smaller dimension');
134
- return;
135
- }
136
- this.maxLoadedDimension = dimension;
137
- let wantedSize;
138
- if (this.objectFit === 'cover') {
139
- wantedSize = NumberUtils.getNextPowerOfTwo(Math.max(dimension.width, dimension.height));
140
- this.hostStyleObjectFit = 'cover';
141
- }
142
- else {
143
- wantedSize = NumberUtils.getNextPowerOfTwo(Math.min(dimension.width, dimension.height));
144
- this.hostStyleObjectFit = 'contain';
145
- }
146
- this.hostSrc = StringUtils.updateUrlParameter(this.src, 'size', String(wantedSize));
147
- this.changeDetectorRef.markForCheck();
148
- }
149
- }
150
- isInsideViewport(element, threshold) {
151
- const ownerDocument = element.ownerDocument;
152
- const documentTop = window.pageYOffset || ownerDocument.body.scrollTop;
153
- const documentLeft = window.pageXOffset || ownerDocument.body.scrollLeft;
154
- const documentWidth = window.innerWidth || (ownerDocument.documentElement.clientWidth || document.body.clientWidth);
155
- const documentHeight = window.innerHeight || (ownerDocument.documentElement.clientHeight || document.body.clientHeight);
156
- const topOffset = element.getBoundingClientRect().top + documentTop - ownerDocument.documentElement.clientTop;
157
- const leftOffset = element.getBoundingClientRect().left + documentLeft - ownerDocument.documentElement.clientLeft;
158
- const isBelowViewport = documentHeight + documentTop <= topOffset - threshold;
159
- const isAtRightOfViewport = documentWidth + window.pageXOffset <= leftOffset - threshold;
160
- const isAboveViewport = documentTop >= topOffset + threshold + element.offsetHeight;
161
- const isAtLeftOfViewport = documentLeft >= leftOffset + threshold + element.offsetWidth;
162
- return !isBelowViewport && !isAboveViewport && !isAtRightOfViewport && !isAtLeftOfViewport;
163
- }
164
- getDimension() {
165
- return {
166
- width: this.element.nativeElement.parentElement.offsetWidth,
167
- height: this.element.nativeElement.parentElement.offsetHeight,
168
- };
169
- }
170
- isHidden(element) {
171
- return window.getComputedStyle(element).display === 'none';
172
- }
173
- }
174
- LazyImageDirective.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: LazyImageDirective, deps: [{ token: i0.ElementRef }, { token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Directive });
175
- LazyImageDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "15.2.4", type: LazyImageDirective, selector: "[ddrLazyImage]", inputs: { src: ["ddrLazyImage", "src"], objectFit: "objectFit", offset: "offset" }, host: { listeners: { "window:resize": "windowResized($event)", "window:scroll": "windowScroll($event)" }, properties: { "src": "this.hostSrc", "style.width.px": "this.hostStyleWidthPx", "style.height.px": "this.hostStyleHeightPx", "style.object-fit": "this.hostStyleObjectFit" } }, usesOnChanges: true, ngImport: i0 });
176
- __decorate([
177
- Debounce()
178
- ], LazyImageDirective.prototype, "windowResized", null);
179
- __decorate([
180
- Limit()
181
- ], LazyImageDirective.prototype, "windowScroll", null);
182
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: LazyImageDirective, decorators: [{
183
- type: Directive,
184
- args: [{ selector: '[ddrLazyImage]' }]
185
- }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: i0.ChangeDetectorRef }]; }, propDecorators: { src: [{
186
- type: Input,
187
- args: ['ddrLazyImage']
188
- }], objectFit: [{
189
- type: Input
190
- }], offset: [{
191
- type: Input
192
- }], hostSrc: [{
193
- type: HostBinding,
194
- args: ['src']
195
- }], hostStyleWidthPx: [{
196
- type: HostBinding,
197
- args: ['style.width.px']
198
- }], hostStyleHeightPx: [{
199
- type: HostBinding,
200
- args: ['style.height.px']
201
- }], hostStyleObjectFit: [{
202
- type: HostBinding,
203
- args: ['style.object-fit']
204
- }], windowResized: [{
205
- type: HostListener,
206
- args: ['window:resize', ['$event']]
207
- }], windowScroll: [{
208
- type: HostListener,
209
- args: ['window:scroll', ['$event']]
210
- }] } });
211
-
212
- class BottomHitDirective {
213
- constructor() {
214
- this.offset = 1000;
215
- this.onWindowBottomHit = new EventEmitter();
216
- this.onElementBottomHit = new EventEmitter();
217
- }
218
- scrolled($event) {
219
- this.elementScrollEvent($event);
220
- }
221
- windowScrolled($event) {
222
- this.windowScrollEvent($event);
223
- }
224
- windowScrollEvent($event) {
225
- const pageHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.body.clientHeight, document.documentElement.clientHeight);
226
- const viewportHeight = document.documentElement.clientHeight;
227
- const scrollPosition = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
228
- const distanceToBottom = pageHeight - (scrollPosition + viewportHeight);
229
- if (distanceToBottom < this.offset) {
230
- this.onWindowBottomHit.emit();
231
- }
232
- }
233
- elementScrollEvent($event) {
234
- const target = $event.target;
235
- const scrollPosition = target.scrollHeight - target.scrollTop;
236
- const offsetHeight = target.offsetHeight;
237
- const isReachingBottom = (scrollPosition - offsetHeight) < this.offset;
238
- if (isReachingBottom) {
239
- this.onElementBottomHit.emit();
240
- }
241
- }
242
- }
243
- BottomHitDirective.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: BottomHitDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });
244
- BottomHitDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "15.2.4", type: BottomHitDirective, selector: "[ddrBottomHit]", outputs: { onWindowBottomHit: "onWindowBottomHit", onElementBottomHit: "onElementBottomHit" }, host: { listeners: { "scroll": "scrolled($event)", "window:scroll": "windowScrolled($event)" } }, ngImport: i0 });
245
- __decorate([
246
- Limit()
247
- ], BottomHitDirective.prototype, "scrolled", null);
248
- __decorate([
249
- Limit()
250
- ], BottomHitDirective.prototype, "windowScrolled", null);
251
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: BottomHitDirective, decorators: [{
252
- type: Directive,
253
- args: [{
254
- selector: '[ddrBottomHit]'
255
- }]
256
- }], ctorParameters: function () { return []; }, propDecorators: { onWindowBottomHit: [{
257
- type: Output
258
- }], onElementBottomHit: [{
259
- type: Output
260
- }], scrolled: [{
261
- type: HostListener,
262
- args: ['scroll', ['$event']]
263
- }], windowScrolled: [{
264
- type: HostListener,
265
- args: ['window:scroll', ['$event']]
266
- }] } });
267
-
268
- class Logger {
269
- constructor() {
270
- this.debugEnabled = false;
271
- this.infoEnabled = true;
272
- this.warnEnabled = true;
273
- this.errorEnabled = true;
274
- }
275
- }
276
-
277
- class ConsoleLogger extends Logger {
278
- /**
279
- * @override
280
- */
281
- debug(...data) {
282
- if (this.debugEnabled) {
283
- console.debug(...data);
284
- }
285
- }
286
- /**
287
- * @override
288
- */
289
- info(...data) {
290
- if (this.infoEnabled) {
291
- console.info(...data);
292
- }
293
- }
294
- /**
295
- * @override
296
- */
297
- warn(...data) {
298
- if (this.warnEnabled) {
299
- console.warn(...data);
300
- }
301
- }
302
- /**
303
- * @override
304
- */
305
- error(...data) {
306
- if (this.errorEnabled) {
307
- console.error(...data);
308
- }
309
- }
310
- }
311
- ConsoleLogger.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: ConsoleLogger, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
312
- ConsoleLogger.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: ConsoleLogger });
313
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: ConsoleLogger, decorators: [{
314
- type: Injectable
315
- }] });
316
-
317
- const DDR_STORAGE_PREFIX = new InjectionToken('storage-prefix');
318
- class StorageService {
319
- }
320
-
321
- class LocalStorageService extends StorageService {
322
- constructor(storagePrefix, logger) {
323
- super();
324
- this.storagePrefix = storagePrefix;
325
- this.logger = logger;
326
- }
327
- /**
328
- * @override
329
- */
330
- retrieve(key, defaultValue = null) {
331
- let fullKey = this.getFullKey(key);
332
- let valueJson = localStorage.getItem(fullKey);
333
- if (null == valueJson) {
334
- return defaultValue;
335
- }
336
- try {
337
- return JSON.parse(valueJson);
338
- }
339
- catch (e) {
340
- this.logger.warn('Could not parse json value', valueJson, e);
341
- localStorage.removeItem(fullKey);
342
- return null;
343
- }
344
- }
345
- /**
346
- * @override
347
- */
348
- store(key, value) {
349
- localStorage.setItem(this.getFullKey(key), JSON.stringify(value));
350
- }
351
- /**
352
- * @override
353
- */
354
- remove(key) {
355
- localStorage.removeItem(this.getFullKey(key));
356
- }
357
- getFullKey(key) {
358
- return this.storagePrefix + '.' + key;
359
- }
360
- }
361
- LocalStorageService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: LocalStorageService, deps: [{ token: DDR_STORAGE_PREFIX }, { token: Logger }], target: i0.ɵɵFactoryTarget.Injectable });
362
- LocalStorageService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: LocalStorageService });
363
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: LocalStorageService, decorators: [{
364
- type: Injectable
365
- }], ctorParameters: function () {
366
- return [{ type: undefined, decorators: [{
367
- type: Inject,
368
- args: [DDR_STORAGE_PREFIX]
369
- }] }, { type: Logger }];
370
- } });
371
-
372
- const DDR_JWT_REFRESH_TOKEN_URL = new InjectionToken('DDR_JWT_REFRESH_TOKEN_URL');
373
- const DDR_LOGIN_PATH = new InjectionToken('DDR_LOGIN_PATH');
374
- class DdrExtensionsModule {
375
- }
376
- DdrExtensionsModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: DdrExtensionsModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
377
- DdrExtensionsModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.2.4", ngImport: i0, type: DdrExtensionsModule, declarations: [LazyImageDirective,
378
- BottomHitDirective], exports: [LazyImageDirective,
379
- BottomHitDirective] });
380
- DdrExtensionsModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: DdrExtensionsModule, providers: [
381
- {
382
- provide: DDR_LOGIN_PATH,
383
- useValue: '/login'
384
- },
385
- {
386
- provide: Logger,
387
- useClass: ConsoleLogger
388
- },
389
- {
390
- provide: DDR_STORAGE_PREFIX,
391
- useValue: 'ddr'
392
- },
393
- {
394
- provide: StorageService,
395
- useClass: LocalStorageService
396
- },
397
- ] });
398
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: DdrExtensionsModule, decorators: [{
399
- type: NgModule,
400
- args: [{
401
- declarations: [
402
- LazyImageDirective,
403
- BottomHitDirective
404
- ],
405
- imports: [],
406
- providers: [
407
- {
408
- provide: DDR_LOGIN_PATH,
409
- useValue: '/login'
410
- },
411
- {
412
- provide: Logger,
413
- useClass: ConsoleLogger
414
- },
415
- {
416
- provide: DDR_STORAGE_PREFIX,
417
- useValue: 'ddr'
418
- },
419
- {
420
- provide: StorageService,
421
- useClass: LocalStorageService
422
- },
423
- ],
424
- exports: [
425
- LazyImageDirective,
426
- BottomHitDirective
427
- ]
428
- }]
429
- }] });
430
-
431
- // This service is based on the `ng2-cookies` package which sadly is not a service and does
432
- class CookieService {
433
- constructor(document) {
434
- this.document = document;
435
- // To avoid issues with server side prerendering, check if `document` is defined.
436
- this.documentIsAccessible = document !== undefined;
437
- }
438
- /**
439
- * @param name Cookie name
440
- */
441
- check(name) {
442
- if (!this.documentIsAccessible) {
443
- return false;
444
- }
445
- name = encodeURIComponent(name);
446
- const regExp = this.getCookieRegExp(name);
447
- return regExp.test(this.document.cookie);
448
- }
449
- /**
450
- * @param name Cookie name
451
- */
452
- get(name) {
453
- if (this.documentIsAccessible && this.check(name)) {
454
- name = encodeURIComponent(name);
455
- const regExp = this.getCookieRegExp(name);
456
- const result = regExp.exec(this.document.cookie);
457
- if (null == result)
458
- return '';
459
- return decodeURIComponent(result[1]);
460
- }
461
- else {
462
- return '';
463
- }
464
- }
465
- getAll() {
466
- if (!this.documentIsAccessible) {
467
- return {};
468
- }
469
- const cookies = {};
470
- const document = this.document;
471
- if (document.cookie && document.cookie !== '') {
472
- const split = document.cookie.split(';');
473
- for (let i = 0; i < split.length; i += 1) {
474
- const currentCookie = split[i].split('=');
475
- currentCookie[0] = currentCookie[0].replace(/^ /, '');
476
- // @ts-ignore
477
- cookies[decodeURIComponent(currentCookie[0])] = decodeURIComponent(currentCookie[1]);
478
- }
479
- }
480
- return cookies;
481
- }
482
- /**
483
- * @param name Cookie name
484
- * @param value Cookie value
485
- * @param expires Number of days until the cookies expires or an actual `Date`
486
- * @param path Cookie path
487
- * @param domain Cookie domain
488
- * @param secure Secure flag
489
- */
490
- set(name, value, expires, path, domain, secure) {
491
- if (!this.documentIsAccessible) {
492
- return;
493
- }
494
- let cookieString = encodeURIComponent(name) + '=' + encodeURIComponent(value) + ';';
495
- if (expires) {
496
- if (typeof expires === 'number') {
497
- const dateExpires = new Date(new Date().getTime() + expires * 1000 * 60 * 60 * 24);
498
- cookieString += 'expires=' + dateExpires.toUTCString() + ';';
499
- }
500
- else {
501
- cookieString += 'expires=' + expires.toUTCString() + ';';
502
- }
503
- }
504
- if (path) {
505
- cookieString += 'path=' + path + ';';
506
- }
507
- if (domain) {
508
- cookieString += 'domain=' + domain + ';';
509
- }
510
- if (secure) {
511
- cookieString += 'secure;';
512
- }
513
- this.document.cookie = cookieString;
514
- }
515
- /**
516
- * @param name Cookie name
517
- * @param path Cookie path
518
- * @param domain Cookie domain
519
- */
520
- delete(name, path, domain) {
521
- if (!this.documentIsAccessible) {
522
- return;
523
- }
524
- this.set(name, '', -1, path, domain);
525
- }
526
- /**
527
- * @param path Cookie path
528
- * @param domain Cookie domain
529
- */
530
- deleteAll(path, domain) {
531
- if (!this.documentIsAccessible) {
532
- return;
533
- }
534
- const cookies = this.getAll();
535
- for (const cookieName in cookies) {
536
- if (cookies.hasOwnProperty(cookieName)) {
537
- this.delete(cookieName, path, domain);
538
- }
539
- }
540
- }
541
- /**
542
- * @param name Cookie name
543
- */
544
- getCookieRegExp(name) {
545
- const escapedName = name.replace(/([\[\]{}()|=;+?,.*^$])/ig, '\\$1');
546
- return new RegExp('(?:^' + escapedName + '|;\\s*' + escapedName + ')=(.*?)(?:;|$)', 'g');
547
- }
548
- }
549
- CookieService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: CookieService, deps: [{ token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Injectable });
550
- CookieService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: CookieService, providedIn: 'root' });
551
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: CookieService, decorators: [{
552
- type: Injectable,
553
- args: [{
554
- providedIn: 'root'
555
- }]
556
- }], ctorParameters: function () {
557
- return [{ type: Document, decorators: [{
558
- type: Inject,
559
- args: [DOCUMENT]
560
- }] }];
561
- } });
562
-
563
- class ObjectUtils {
564
- static deepCopy(value) {
565
- return JSON.parse(JSON.stringify(value));
566
- }
567
- static getProperty(o, propertyName) {
568
- return o[propertyName];
569
- }
570
- }
571
-
572
- class CollectionUtils {
573
- /**
574
- * Maps an array into a Map by a specific property which should be unique.
575
- */
576
- static mapByProperty(entries, property) {
577
- const map = new Map();
578
- for (const entry of entries) {
579
- map.set(ObjectUtils.getProperty(entry, property), entry);
580
- }
581
- return map;
582
- }
583
- /**
584
- * Maps an array into a Map by a specified property and aggregates them into an array.
585
- */
586
- static mapArrayByProperty(entries, property) {
587
- var _a;
588
- const map = new Map();
589
- for (const entry of entries) {
590
- const value = ObjectUtils.getProperty(entry, property);
591
- const existingEntries = (_a = map.get(value)) !== null && _a !== void 0 ? _a : [];
592
- existingEntries.push(entry);
593
- map.set(value, existingEntries);
594
- }
595
- return map;
596
- }
597
- }
598
-
599
- class TypeUtils {
600
- static notNull(value, message = 'Value must not be null') {
601
- if (null == value) {
602
- throw new Error(message);
603
- }
604
- return value;
605
- }
606
- }
607
-
608
- class ScrollService {
609
- constructor(router, viewportScroller) {
610
- this.router = router;
611
- this.viewportScroller = viewportScroller;
612
- this.scrollPositionMap = new Map();
613
- this.router.events
614
- .subscribe(e => {
615
- if (e instanceof NavigationStart) {
616
- this.scrollPositionMap.set(this.router.url, this.viewportScroller.getScrollPosition());
617
- }
618
- });
619
- }
620
- restore() {
621
- const url = this.router.url;
622
- if (this.scrollPositionMap.has(url)) {
623
- /* Restore after timeout so rendering was completed */
624
- setTimeout(() => {
625
- let scrollPosition = this.scrollPositionMap.get(url);
626
- if (null != scrollPosition)
627
- this.viewportScroller.scrollToPosition(scrollPosition);
628
- }, 1);
629
- }
630
- }
631
- }
632
- ScrollService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: ScrollService, deps: [{ token: i1.Router }, { token: i2.ViewportScroller }], target: i0.ɵɵFactoryTarget.Injectable });
633
- ScrollService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: ScrollService, providedIn: 'root' });
634
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: ScrollService, decorators: [{
635
- type: Injectable,
636
- args: [{
637
- providedIn: 'root'
638
- }]
639
- }], ctorParameters: function () { return [{ type: i1.Router }, { type: i2.ViewportScroller }]; } });
640
-
641
- class VisibilityService {
642
- constructor() {
643
- this.visibility$ = merge(fromEvent(document, 'visibilitychange'), fromEvent(window, 'focus'), fromEvent(window, 'blur')).pipe(debounceTime(50), startWith(true), map(() => document.hasFocus()), distinctUntilChanged(), shareReplay(1));
644
- }
645
- getVisibilityObservable() {
646
- return this.visibility$;
647
- }
648
- }
649
- VisibilityService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: VisibilityService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
650
- VisibilityService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: VisibilityService, providedIn: 'root' });
651
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: VisibilityService, decorators: [{
652
- type: Injectable,
653
- args: [{ providedIn: 'root' }]
654
- }], ctorParameters: function () { return []; } });
655
-
656
- class WithCredentialsInterceptor {
657
- /**
658
- * @override
659
- */
660
- intercept(req, next) {
661
- const cloned = req.clone({
662
- withCredentials: true
663
- });
664
- return next.handle(cloned);
665
- }
666
- }
667
- WithCredentialsInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: WithCredentialsInterceptor, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
668
- WithCredentialsInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: WithCredentialsInterceptor });
669
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: WithCredentialsInterceptor, decorators: [{
670
- type: Injectable
671
- }] });
672
-
673
- class UrlInfo {
674
- constructor(protocol, host, hostname, port, pathname, hash, search) {
675
- this.protocol = protocol;
676
- this.host = host;
677
- this.hostname = hostname;
678
- this.port = port;
679
- this.pathname = pathname;
680
- this.hash = hash;
681
- this.search = search;
682
- }
683
- static parse(urlString) {
684
- const parser = document.createElement('a');
685
- parser.href = urlString;
686
- return new UrlInfo(parser.protocol, parser.host, parser.hostname, parser.port === '' ? 80 : +parser.port, parser.pathname, parser.hash, parser.search);
687
- }
688
- getRoot() {
689
- let root = this.protocol + '//' + this.hostname;
690
- if (this.port !== 80)
691
- root += ':' + this.port;
692
- return root;
693
- }
694
- getUrl() {
695
- return this.getRoot() + this.pathname;
696
- }
697
- }
698
-
699
- class RedirectToLoginInterceptor {
700
- constructor(router, loginPath) {
701
- this.router = router;
702
- this.loginPath = loginPath;
703
- }
704
- /**
705
- * @override
706
- */
707
- intercept(req, next) {
708
- return next.handle(req).pipe(catchError((err) => {
709
- if (err instanceof HttpErrorResponse) {
710
- if (err.status === 401) {
711
- this.router.navigate([this.loginPath]);
712
- }
713
- }
714
- return throwError(err);
715
- }));
716
- }
717
- }
718
- RedirectToLoginInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: RedirectToLoginInterceptor, deps: [{ token: i1.Router }, { token: DDR_LOGIN_PATH }], target: i0.ɵɵFactoryTarget.Injectable });
719
- RedirectToLoginInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: RedirectToLoginInterceptor });
720
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: RedirectToLoginInterceptor, decorators: [{
721
- type: Injectable
722
- }], ctorParameters: function () {
723
- return [{ type: i1.Router }, { type: undefined, decorators: [{
724
- type: Inject,
725
- args: [DDR_LOGIN_PATH]
726
- }] }];
727
- } });
728
-
729
- const DDR_OAUTH2_CONFIG = new InjectionToken('DDR_OAUTH2_CONFIG');
730
- class OAuth2Config {
731
- constructor(clientId, redirectUri, authorizeUri, tokenUri) {
732
- this.clientId = clientId;
733
- this.redirectUri = redirectUri;
734
- this.authorizeUri = authorizeUri;
735
- this.tokenUri = tokenUri;
736
- }
737
- }
738
-
739
- class OAuth2Error extends Error {
740
- constructor(error) {
741
- super(error);
742
- }
743
- }
744
- OAuth2Error.CODE_NOT_FOUND = 'code_not_found';
745
- OAuth2Error.ACCESS_DENIED = 'access_denied';
746
-
747
- class OAuth2Service {
748
- constructor(route, httpClient, loggerService, config) {
749
- this.route = route;
750
- this.httpClient = httpClient;
751
- this.loggerService = loggerService;
752
- this.config = config;
753
- this.accessTokenString = null;
754
- this.accessToken = null;
755
- this.REFRESH_MARGIN_SECONDS = 60 * 10;
756
- this.refreshTokenRequest$ = null;
757
- }
758
- redirectToLogin() {
759
- const challenge = this.createChallenge();
760
- localStorage.setItem(OAuth2Service.STORAGE_KEY_CHALLENGE, challenge);
761
- const params = new HttpParams()
762
- .set('client_id', this.config.clientId)
763
- .set('response_type', 'code')
764
- .set('redirect_uri', this.config.redirectUri)
765
- .set('code_challenge', challenge)
766
- .set('code_challenge_method', 'plain');
767
- window.location.href = this.config.authorizeUri + '?' + params.toString();
768
- }
769
- handleCode() {
770
- if (this.route.snapshot.queryParamMap.has('error')) {
771
- const error = this.route.snapshot.queryParamMap.get('error');
772
- return throwError(() => new OAuth2Error(error !== null && error !== void 0 ? error : 'Unknown error'));
773
- }
774
- if (!this.route.snapshot.queryParamMap.has('code')) {
775
- return throwError(() => new OAuth2Error(OAuth2Error.CODE_NOT_FOUND));
776
- }
777
- const code = TypeUtils.notNull(this.route.snapshot.queryParamMap.get('code'));
778
- const params = new HttpParams()
779
- .set('grant_type', 'authorization_code')
780
- .set('code', code)
781
- .set('redirect_uri', this.config.redirectUri)
782
- .set('code_verifier', TypeUtils.notNull(localStorage.getItem(OAuth2Service.STORAGE_KEY_CHALLENGE)))
783
- .set('client_id', this.config.clientId);
784
- return this.httpClient.post(this.config.tokenUri, params).pipe(map(tokenResponse => this.processTokenResponse(tokenResponse)));
785
- }
786
- createChallenge() {
787
- return StringUtils.createRandomString(64, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-._~');
788
- }
789
- getRefreshToken() {
790
- return localStorage.getItem(OAuth2Service.STORAGE_KEY_REFRESH_TOKEN);
791
- }
792
- getAccessTokenString() {
793
- return this.accessTokenString;
794
- }
795
- isAccessTokenExpired() {
796
- return (null == this.accessToken
797
- || this.accessToken.exp * 1000 < Date.now());
798
- }
799
- isRefreshPossibleAndRequired(req = null) {
800
- return ((null == req || !req.url.endsWith(this.config.tokenUri))
801
- && null != this.getRefreshToken()
802
- && (null == this.accessToken
803
- || (this.accessToken.exp - this.REFRESH_MARGIN_SECONDS) * 1000 < Date.now()));
804
- }
805
- performRefresh() {
806
- if (null == this.refreshTokenRequest$) {
807
- this.loggerService.info('Performing token refesh');
808
- const params = new HttpParams()
809
- .set('grant_type', 'refresh_token')
810
- .set('refresh_token', TypeUtils.notNull(this.getRefreshToken()))
811
- .set('client_id', this.config.clientId);
812
- this.refreshTokenRequest$ = this.httpClient.post(this.config.tokenUri, params).pipe(map(tokenResponse => {
813
- const token = this.processTokenResponse(tokenResponse);
814
- this.refreshTokenRequest$ = null;
815
- return token;
816
- }), catchError(error => {
817
- this.accessTokenString = null;
818
- this.accessToken = null;
819
- localStorage.removeItem(OAuth2Service.STORAGE_KEY_REFRESH_TOKEN);
820
- this.refreshTokenRequest$ = null;
821
- return throwError(error);
822
- }), shareReplay(1));
823
- }
824
- return this.refreshTokenRequest$;
825
- }
826
- processTokenResponse(tokenResponse) {
827
- localStorage.removeItem(OAuth2Service.STORAGE_KEY_CHALLENGE);
828
- this.accessTokenString = tokenResponse.access_token;
829
- this.accessToken = JSON.parse(atob(tokenResponse.access_token.split('.')[1]));
830
- this.loggerService.info('Access Token Expiry', new Date(this.accessToken.exp * 1000));
831
- localStorage.setItem(OAuth2Service.STORAGE_KEY_REFRESH_TOKEN, tokenResponse.refresh_token);
832
- return this.accessToken;
833
- }
834
- clear() {
835
- this.accessToken = null;
836
- this.accessTokenString = null;
837
- localStorage.removeItem(OAuth2Service.STORAGE_KEY_REFRESH_TOKEN);
838
- localStorage.removeItem(OAuth2Service.STORAGE_KEY_RETURN_URL);
839
- }
840
- setReturnUrl(url) {
841
- localStorage.setItem(OAuth2Service.STORAGE_KEY_RETURN_URL, url);
842
- }
843
- getReturnUrl() {
844
- return localStorage.getItem(OAuth2Service.STORAGE_KEY_RETURN_URL);
845
- }
846
- }
847
- OAuth2Service.STORAGE_KEY_CHALLENGE = 'ddr_oauth2_challenge';
848
- OAuth2Service.STORAGE_KEY_REFRESH_TOKEN = 'ddr_oauth2_refresh_token';
849
- OAuth2Service.STORAGE_KEY_RETURN_URL = 'ddr_oauth2_return_url';
850
- OAuth2Service.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: OAuth2Service, deps: [{ token: i1.ActivatedRoute }, { token: i2$1.HttpClient }, { token: Logger }, { token: DDR_OAUTH2_CONFIG }], target: i0.ɵɵFactoryTarget.Injectable });
851
- OAuth2Service.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: OAuth2Service });
852
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: OAuth2Service, decorators: [{
853
- type: Injectable
854
- }], ctorParameters: function () {
855
- return [{ type: i1.ActivatedRoute }, { type: i2$1.HttpClient }, { type: Logger }, { type: OAuth2Config, decorators: [{
856
- type: Inject,
857
- args: [DDR_OAUTH2_CONFIG]
858
- }] }];
859
- } });
860
-
861
- class OAuth2RefreshTokenInterceptor {
862
- constructor(oAuth2Service) {
863
- this.oAuth2Service = oAuth2Service;
864
- }
865
- /**
866
- * @override
867
- */
868
- intercept(req, next) {
869
- if (this.oAuth2Service.isRefreshPossibleAndRequired(req)) {
870
- return this.oAuth2Service.performRefresh().pipe(switchMap(() => next.handle(req)));
871
- }
872
- return next.handle(req);
873
- }
874
- }
875
- OAuth2RefreshTokenInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: OAuth2RefreshTokenInterceptor, deps: [{ token: OAuth2Service }], target: i0.ɵɵFactoryTarget.Injectable });
876
- OAuth2RefreshTokenInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: OAuth2RefreshTokenInterceptor });
877
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: OAuth2RefreshTokenInterceptor, decorators: [{
878
- type: Injectable
879
- }], ctorParameters: function () { return [{ type: OAuth2Service }]; } });
880
-
881
- class RedirectToOAuth2LoginInterceptor {
882
- constructor(oAuth2Service, router, oAuth2Config) {
883
- this.oAuth2Service = oAuth2Service;
884
- this.router = router;
885
- this.oAuth2Config = oAuth2Config;
886
- }
887
- /**
888
- * @override
889
- */
890
- intercept(req, next) {
891
- return next.handle(req).pipe(catchError((err) => {
892
- if (err instanceof HttpErrorResponse) {
893
- if (err.status === 401) {
894
- if (!window.location.href.startsWith(this.oAuth2Config.redirectUri)) {
895
- this.oAuth2Service.setReturnUrl(this.router.routerState.snapshot.url);
896
- this.oAuth2Service.redirectToLogin();
897
- }
898
- }
899
- }
900
- return throwError(err);
901
- }));
902
- }
903
- }
904
- RedirectToOAuth2LoginInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: RedirectToOAuth2LoginInterceptor, deps: [{ token: OAuth2Service }, { token: i1.Router }, { token: DDR_OAUTH2_CONFIG }], target: i0.ɵɵFactoryTarget.Injectable });
905
- RedirectToOAuth2LoginInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: RedirectToOAuth2LoginInterceptor });
906
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: RedirectToOAuth2LoginInterceptor, decorators: [{
907
- type: Injectable
908
- }], ctorParameters: function () {
909
- return [{ type: OAuth2Service }, { type: i1.Router }, { type: OAuth2Config, decorators: [{
910
- type: Inject,
911
- args: [DDR_OAUTH2_CONFIG]
912
- }] }];
913
- } });
914
-
915
- class OAuth2AccessTokenInterceptor {
916
- constructor(oAuth2Service) {
917
- this.oAuth2Service = oAuth2Service;
918
- }
919
- /**
920
- * @override
921
- */
922
- intercept(req, next) {
923
- const accessTokenString = this.oAuth2Service.getAccessTokenString();
924
- if (null !== accessTokenString && !this.oAuth2Service.isAccessTokenExpired()) {
925
- req = req.clone({
926
- headers: req.headers.set('Authorization', 'Bearer ' + accessTokenString)
927
- });
928
- }
929
- return next.handle(req);
930
- }
931
- }
932
- OAuth2AccessTokenInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: OAuth2AccessTokenInterceptor, deps: [{ token: OAuth2Service }], target: i0.ɵɵFactoryTarget.Injectable });
933
- OAuth2AccessTokenInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: OAuth2AccessTokenInterceptor });
934
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: OAuth2AccessTokenInterceptor, decorators: [{
935
- type: Injectable
936
- }], ctorParameters: function () { return [{ type: OAuth2Service }]; } });
937
-
938
- class OAuth2Module {
939
- static forRoot(config) {
940
- return {
941
- ngModule: OAuth2Module,
942
- providers: [
943
- OAuth2Service,
944
- {
945
- provide: DDR_OAUTH2_CONFIG,
946
- useValue: config
947
- },
948
- {
949
- provide: HTTP_INTERCEPTORS,
950
- useClass: OAuth2RefreshTokenInterceptor,
951
- multi: true
952
- },
953
- {
954
- provide: HTTP_INTERCEPTORS,
955
- useClass: RedirectToOAuth2LoginInterceptor,
956
- multi: true
957
- },
958
- {
959
- provide: HTTP_INTERCEPTORS,
960
- useClass: OAuth2AccessTokenInterceptor,
961
- multi: true
962
- }
963
- ],
964
- };
965
- }
966
- }
967
- OAuth2Module.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: OAuth2Module, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
968
- OAuth2Module.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.2.4", ngImport: i0, type: OAuth2Module });
969
- OAuth2Module.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: OAuth2Module });
970
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: OAuth2Module, decorators: [{
971
- type: NgModule
972
- }] });
973
-
974
- function isNonNull(value) {
975
- return value != null;
976
- }
977
-
978
- class JwtService {
979
- constructor(storageService, loggerService) {
980
- this.storageService = storageService;
981
- this.loggerService = loggerService;
982
- /**
983
- * The current token.
984
- */
985
- this.token = null;
986
- /**
987
- * The expiry of the current token.
988
- */
989
- this.tokenExpiry = null;
990
- }
991
- /**
992
- * Sets the current token and a refresh token.
993
- */
994
- setTokens(token, refreshToken) {
995
- this.setToken(token);
996
- this.storageService.store(this.getRefreshTokenStorageKey(), refreshToken);
997
- }
998
- /**
999
- * Sets the current token.
1000
- */
1001
- setToken(token) {
1002
- this.token = token;
1003
- const decodedToken = JSON.parse(atob(token.split('.')[1]));
1004
- this.tokenExpiry = decodedToken.exp * 1000;
1005
- this.loggerService.info('New refresh token, expiry', new Date(this.tokenExpiry));
1006
- }
1007
- /**
1008
- * Gets the current token.
1009
- */
1010
- getToken() {
1011
- return this.token;
1012
- }
1013
- /**
1014
- * Gets the refresh token.
1015
- */
1016
- getRefreshToken() {
1017
- return this.storageService.retrieve(this.getRefreshTokenStorageKey());
1018
- }
1019
- /**
1020
- * Checks if the current token expired.
1021
- */
1022
- isExpired() {
1023
- const now = new Date().getTime();
1024
- return null == this.tokenExpiry || this.tokenExpiry < now;
1025
- }
1026
- /**
1027
- * Checks if the current token is about to expire.
1028
- * @param expiryMs
1029
- */
1030
- isAboutToExpire(expiryMs = 60000) {
1031
- const now = new Date().getTime();
1032
- return null == this.tokenExpiry || this.tokenExpiry - expiryMs < now;
1033
- }
1034
- /**
1035
- * Clears all token information.
1036
- */
1037
- clear() {
1038
- this.token = null;
1039
- this.tokenExpiry = null;
1040
- this.storageService.remove(this.getRefreshTokenStorageKey());
1041
- }
1042
- getRefreshTokenStorageKey() {
1043
- return 'jwt.refresh_token';
1044
- }
1045
- }
1046
- JwtService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: JwtService, deps: [{ token: StorageService }, { token: Logger }], target: i0.ɵɵFactoryTarget.Injectable });
1047
- JwtService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: JwtService, providedIn: 'root' });
1048
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: JwtService, decorators: [{
1049
- type: Injectable,
1050
- args: [{
1051
- providedIn: 'root'
1052
- }]
1053
- }], ctorParameters: function () { return [{ type: StorageService }, { type: Logger }]; } });
1054
-
1055
- class JwtInterceptor {
1056
- constructor(jwtService) {
1057
- this.jwtService = jwtService;
1058
- }
1059
- /**
1060
- * @override
1061
- */
1062
- intercept(req, next) {
1063
- const token = this.jwtService.getToken();
1064
- if (null !== token && !this.jwtService.isExpired()) {
1065
- req = req.clone({
1066
- headers: req.headers.set('Authorization', 'Bearer ' + token)
1067
- });
1068
- }
1069
- return next.handle(req);
1070
- }
1071
- }
1072
- JwtInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: JwtInterceptor, deps: [{ token: JwtService }], target: i0.ɵɵFactoryTarget.Injectable });
1073
- JwtInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: JwtInterceptor });
1074
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: JwtInterceptor, decorators: [{
1075
- type: Injectable
1076
- }], ctorParameters: function () { return [{ type: JwtService }]; } });
1077
-
1078
- class JwtRefreshTokenInterceptor {
1079
- constructor(jwtService, httpClient, jwtRefreshTokenUrl) {
1080
- this.jwtService = jwtService;
1081
- this.httpClient = httpClient;
1082
- this.jwtRefreshTokenUrl = jwtRefreshTokenUrl;
1083
- this.refreshTokenRequest$ = null;
1084
- }
1085
- /**
1086
- * @override
1087
- */
1088
- intercept(req, next) {
1089
- if (this.jwtService.isAboutToExpire() && !(req.url === this.jwtRefreshTokenUrl)) {
1090
- const refreshToken = this.jwtService.getRefreshToken();
1091
- if (null != refreshToken) {
1092
- return this.getRefreshTokenRequest(refreshToken).pipe(switchMap(() => next.handle(req)));
1093
- }
1094
- }
1095
- return next.handle(req);
1096
- }
1097
- getRefreshTokenRequest(refreshToken) {
1098
- if (null == this.refreshTokenRequest$) {
1099
- this.refreshTokenRequest$ = this.httpClient.post(this.jwtRefreshTokenUrl, { refresh_token: refreshToken }).pipe(map(response => {
1100
- this.jwtService.setTokens(response.token, response.refresh_token);
1101
- this.refreshTokenRequest$ = null;
1102
- return response;
1103
- }), catchError(error => {
1104
- this.jwtService.clear();
1105
- this.refreshTokenRequest$ = null;
1106
- return throwError(error);
1107
- }), shareReplay(1));
1108
- }
1109
- return this.refreshTokenRequest$;
1110
- }
1111
- }
1112
- JwtRefreshTokenInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: JwtRefreshTokenInterceptor, deps: [{ token: JwtService }, { token: i2$1.HttpClient }, { token: DDR_JWT_REFRESH_TOKEN_URL }], target: i0.ɵɵFactoryTarget.Injectable });
1113
- JwtRefreshTokenInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: JwtRefreshTokenInterceptor });
1114
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.4", ngImport: i0, type: JwtRefreshTokenInterceptor, decorators: [{
1115
- type: Injectable
1116
- }], ctorParameters: function () {
1117
- return [{ type: JwtService }, { type: i2$1.HttpClient }, { type: undefined, decorators: [{
1118
- type: Inject,
1119
- args: [DDR_JWT_REFRESH_TOKEN_URL]
1120
- }] }];
1121
- } });
1122
-
1123
- /*
1124
- * Public API Surface of ngx-extensions
1125
- */
1126
-
1127
- /**
1128
- * Generated bundle index. Do not edit.
1129
- */
1130
-
1131
- export { BottomHitDirective, CollectionUtils, CookieService, DDR_JWT_REFRESH_TOKEN_URL, DDR_LOGIN_PATH, DDR_STORAGE_PREFIX, DdrExtensionsModule, Debounce, JwtInterceptor, JwtRefreshTokenInterceptor, JwtService, LazyImageDirective, Limit, NumberUtils, OAuth2Error, OAuth2Module, OAuth2Service, ObjectUtils, RedirectToLoginInterceptor, ScrollService, StorageService, StringUtils, TypeUtils, UrlInfo, VisibilityService, WithCredentialsInterceptor, isNonNull };
1132
- //# sourceMappingURL=dontdrinkandroot-ngx-extensions.mjs.map