@dontdrinkandroot/ngx-extensions 0.3.1 → 0.4.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 (56) hide show
  1. package/{esm2020 → esm2022}/src/cookie/cookie.service.mjs +4 -4
  2. package/esm2022/src/ddr-extensions.module.mjs +67 -0
  3. package/{esm2020 → esm2022}/src/http/redirect-to-login-interceptor.service.mjs +4 -4
  4. package/{esm2020 → esm2022}/src/http/with-credentials-interceptor.service.mjs +4 -4
  5. package/{esm2020 → esm2022}/src/image/lazy-image.directive.mjs +4 -4
  6. package/{esm2020 → esm2022}/src/jwt/jwt-interceptor.service.mjs +4 -4
  7. package/{esm2020 → esm2022}/src/jwt/jwt-refresh-token-interceptor.service.mjs +4 -4
  8. package/esm2022/src/jwt/jwt.service.mjs +81 -0
  9. package/esm2022/src/logger/console-logger.service.mjs +43 -0
  10. package/esm2022/src/logger/logger.service.mjs +9 -0
  11. package/{esm2020 → esm2022}/src/oauth/oauth2-access-token-interceptor.service.mjs +4 -4
  12. package/esm2022/src/oauth/oauth2-error.mjs +8 -0
  13. package/{esm2020 → esm2022}/src/oauth/oauth2-refresh-token-interceptor.service.mjs +4 -4
  14. package/{esm2020 → esm2022}/src/oauth/oauth2.module.mjs +5 -5
  15. package/esm2022/src/oauth/oauth2.service.mjs +125 -0
  16. package/{esm2020 → esm2022}/src/oauth/redirect-to-oauth2-login-interceptor.service.mjs +4 -4
  17. package/{esm2020 → esm2022}/src/scroll/bottom-hit.directive.mjs +4 -4
  18. package/{esm2020 → esm2022}/src/scroll/scroll.service.mjs +4 -4
  19. package/esm2022/src/storage/local-storage.service.mjs +53 -0
  20. package/{esm2020 → esm2022}/src/visibility/visibility.service.mjs +4 -4
  21. package/{fesm2020 → fesm2022}/dontdrinkandroot-ngx-extensions.mjs +109 -101
  22. package/fesm2022/dontdrinkandroot-ngx-extensions.mjs.map +1 -0
  23. package/package.json +9 -15
  24. package/src/image/lazy-image.directive.d.ts +1 -1
  25. package/src/jwt/jwt.service.d.ts +3 -1
  26. package/src/logger/console-logger.service.d.ts +8 -8
  27. package/src/logger/logger.service.d.ts +5 -5
  28. package/src/oauth/oauth2.service.d.ts +3 -1
  29. package/src/storage/local-storage.service.d.ts +4 -4
  30. package/src/visibility/visibility.service.d.ts +1 -1
  31. package/esm2020/src/ddr-extensions.module.mjs +0 -67
  32. package/esm2020/src/jwt/jwt.service.mjs +0 -79
  33. package/esm2020/src/logger/console-logger.service.mjs +0 -43
  34. package/esm2020/src/logger/logger.service.mjs +0 -9
  35. package/esm2020/src/oauth/oauth2-error.mjs +0 -8
  36. package/esm2020/src/oauth/oauth2.service.mjs +0 -119
  37. package/esm2020/src/storage/local-storage.service.mjs +0 -53
  38. package/fesm2015/dontdrinkandroot-ngx-extensions.mjs +0 -1126
  39. package/fesm2015/dontdrinkandroot-ngx-extensions.mjs.map +0 -1
  40. package/fesm2020/dontdrinkandroot-ngx-extensions.mjs.map +0 -1
  41. /package/{esm2020 → esm2022}/dontdrinkandroot-ngx-extensions.mjs +0 -0
  42. /package/{esm2020 → esm2022}/public-api.mjs +0 -0
  43. /package/{esm2020 → esm2022}/src/http/url-info.mjs +0 -0
  44. /package/{esm2020 → esm2022}/src/jwt/jwt-token-response.mjs +0 -0
  45. /package/{esm2020 → esm2022}/src/methoddecorator/debounce.mjs +0 -0
  46. /package/{esm2020 → esm2022}/src/methoddecorator/limit.mjs +0 -0
  47. /package/{esm2020 → esm2022}/src/oauth/json-web-token.mjs +0 -0
  48. /package/{esm2020 → esm2022}/src/oauth/oauth2-config.mjs +0 -0
  49. /package/{esm2020 → esm2022}/src/oauth/token-response.mjs +0 -0
  50. /package/{esm2020 → esm2022}/src/storage/storage.service.mjs +0 -0
  51. /package/{esm2020 → esm2022}/src/typeguard/is-non-null.mjs +0 -0
  52. /package/{esm2020 → esm2022}/src/util/collection-utils.mjs +0 -0
  53. /package/{esm2020 → esm2022}/src/util/number-utils.mjs +0 -0
  54. /package/{esm2020 → esm2022}/src/util/object-utils.mjs +0 -0
  55. /package/{esm2020 → esm2022}/src/util/string-utils.mjs +0 -0
  56. /package/{esm2020 → esm2022}/src/util/type-utils.mjs +0 -0
@@ -1,1126 +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.3", 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.3", 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.3", 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.3", ngImport: i0, type: BottomHitDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });
244
- BottomHitDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "15.2.3", 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.3", 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 LoggerService {
269
- constructor() {
270
- this.debugEnabled = false;
271
- this.infoEnabled = true;
272
- this.warnEnabled = true;
273
- this.errorEnabled = true;
274
- }
275
- }
276
-
277
- class ConsoleLoggerService extends LoggerService {
278
- /**
279
- * @override
280
- */
281
- debug(message, ...optionalParams) {
282
- if (this.debugEnabled) {
283
- console.debug(message, optionalParams);
284
- }
285
- }
286
- /**
287
- * @override
288
- */
289
- info(message, ...optionalParams) {
290
- if (this.infoEnabled) {
291
- console.info(message, optionalParams);
292
- }
293
- }
294
- /**
295
- * @override
296
- */
297
- warn(message, ...optionalParams) {
298
- if (this.warnEnabled) {
299
- console.warn(message, optionalParams);
300
- }
301
- }
302
- /**
303
- * @override
304
- */
305
- error(message, ...optionalParams) {
306
- if (this.errorEnabled) {
307
- console.error(message, optionalParams);
308
- }
309
- }
310
- }
311
- ConsoleLoggerService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: ConsoleLoggerService, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
312
- ConsoleLoggerService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: ConsoleLoggerService });
313
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: ConsoleLoggerService, 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.3", ngImport: i0, type: LocalStorageService, deps: [{ token: DDR_STORAGE_PREFIX }, { token: LoggerService }], target: i0.ɵɵFactoryTarget.Injectable });
362
- LocalStorageService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: LocalStorageService });
363
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.3", 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: LoggerService }];
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.3", ngImport: i0, type: DdrExtensionsModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
377
- DdrExtensionsModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.2.3", ngImport: i0, type: DdrExtensionsModule, declarations: [LazyImageDirective,
378
- BottomHitDirective], exports: [LazyImageDirective,
379
- BottomHitDirective] });
380
- DdrExtensionsModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: DdrExtensionsModule, providers: [
381
- {
382
- provide: DDR_LOGIN_PATH,
383
- useValue: '/login'
384
- },
385
- {
386
- provide: LoggerService,
387
- useClass: ConsoleLoggerService
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.3", 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: LoggerService,
413
- useClass: ConsoleLoggerService
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.3", ngImport: i0, type: CookieService, deps: [{ token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Injectable });
550
- CookieService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: CookieService, providedIn: 'root' });
551
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.3", 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.3", 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.3", ngImport: i0, type: ScrollService, providedIn: 'root' });
634
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.3", 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.3", ngImport: i0, type: VisibilityService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
650
- VisibilityService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: VisibilityService, providedIn: 'root' });
651
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.3", 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.3", ngImport: i0, type: WithCredentialsInterceptor, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
668
- WithCredentialsInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: WithCredentialsInterceptor });
669
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.3", 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.3", 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.3", ngImport: i0, type: RedirectToLoginInterceptor });
720
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.3", 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, config) {
749
- this.route = route;
750
- this.httpClient = httpClient;
751
- this.config = config;
752
- this.accessTokenString = null;
753
- this.accessToken = null;
754
- this.REFRESH_MARGIN_SECONDS = 60 * 10;
755
- this.refreshTokenRequest$ = null;
756
- }
757
- redirectToLogin() {
758
- const challenge = this.createChallenge();
759
- localStorage.setItem(OAuth2Service.STORAGE_KEY_CHALLENGE, challenge);
760
- const params = new HttpParams()
761
- .set('client_id', this.config.clientId)
762
- .set('response_type', 'code')
763
- .set('redirect_uri', this.config.redirectUri)
764
- .set('code_challenge', challenge)
765
- .set('code_challenge_method', 'plain');
766
- window.location.href = this.config.authorizeUri + '?' + params.toString();
767
- }
768
- handleCode() {
769
- if (this.route.snapshot.queryParamMap.has('error')) {
770
- const error = this.route.snapshot.queryParamMap.get('error');
771
- return throwError(() => new OAuth2Error(error !== null && error !== void 0 ? error : 'Unknown error'));
772
- }
773
- if (!this.route.snapshot.queryParamMap.has('code')) {
774
- return throwError(() => new OAuth2Error(OAuth2Error.CODE_NOT_FOUND));
775
- }
776
- const code = TypeUtils.notNull(this.route.snapshot.queryParamMap.get('code'));
777
- const params = new HttpParams()
778
- .set('grant_type', 'authorization_code')
779
- .set('code', code)
780
- .set('redirect_uri', this.config.redirectUri)
781
- .set('code_verifier', TypeUtils.notNull(localStorage.getItem(OAuth2Service.STORAGE_KEY_CHALLENGE)))
782
- .set('client_id', this.config.clientId);
783
- return this.httpClient.post(this.config.tokenUri, params).pipe(map(tokenResponse => this.processTokenResponse(tokenResponse)));
784
- }
785
- createChallenge() {
786
- return StringUtils.createRandomString(64, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-._~');
787
- }
788
- getRefreshToken() {
789
- return localStorage.getItem(OAuth2Service.STORAGE_KEY_REFRESH_TOKEN);
790
- }
791
- getAccessTokenString() {
792
- return this.accessTokenString;
793
- }
794
- isAccessTokenExpired() {
795
- return (null == this.accessToken
796
- || this.accessToken.exp * 1000 < Date.now());
797
- }
798
- isRefreshPossibleAndRequired(req = null) {
799
- return ((null == req || !req.url.endsWith(this.config.tokenUri))
800
- && null != this.getRefreshToken()
801
- && (null == this.accessToken
802
- || (this.accessToken.exp - this.REFRESH_MARGIN_SECONDS) * 1000 < Date.now()));
803
- }
804
- performRefresh() {
805
- if (null == this.refreshTokenRequest$) {
806
- console.log('Performing token refesh');
807
- const params = new HttpParams()
808
- .set('grant_type', 'refresh_token')
809
- .set('refresh_token', TypeUtils.notNull(this.getRefreshToken()))
810
- .set('client_id', this.config.clientId);
811
- this.refreshTokenRequest$ = this.httpClient.post(this.config.tokenUri, params).pipe(map(tokenResponse => this.processTokenResponse(tokenResponse)), catchError(error => {
812
- this.accessTokenString = null;
813
- this.accessToken = null;
814
- localStorage.removeItem(OAuth2Service.STORAGE_KEY_REFRESH_TOKEN);
815
- this.refreshTokenRequest$ = null;
816
- return throwError(error);
817
- }), shareReplay(1));
818
- }
819
- return this.refreshTokenRequest$;
820
- }
821
- processTokenResponse(tokenResponse) {
822
- localStorage.removeItem(OAuth2Service.STORAGE_KEY_CHALLENGE);
823
- this.accessTokenString = tokenResponse.access_token;
824
- this.accessToken = JSON.parse(atob(tokenResponse.access_token.split('.')[1]));
825
- console.log('Access Token Expiry', new Date(this.accessToken.exp * 1000));
826
- localStorage.setItem(OAuth2Service.STORAGE_KEY_REFRESH_TOKEN, tokenResponse.refresh_token);
827
- return this.accessToken;
828
- }
829
- clear() {
830
- this.accessToken = null;
831
- this.accessTokenString = null;
832
- localStorage.removeItem(OAuth2Service.STORAGE_KEY_REFRESH_TOKEN);
833
- localStorage.removeItem(OAuth2Service.STORAGE_KEY_RETURN_URL);
834
- }
835
- setReturnUrl(url) {
836
- localStorage.setItem(OAuth2Service.STORAGE_KEY_RETURN_URL, url);
837
- }
838
- getReturnUrl() {
839
- return localStorage.getItem(OAuth2Service.STORAGE_KEY_RETURN_URL);
840
- }
841
- }
842
- OAuth2Service.STORAGE_KEY_CHALLENGE = 'ddr_oauth2_challenge';
843
- OAuth2Service.STORAGE_KEY_REFRESH_TOKEN = 'ddr_oauth2_refresh_token';
844
- OAuth2Service.STORAGE_KEY_RETURN_URL = 'ddr_oauth2_return_url';
845
- OAuth2Service.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: OAuth2Service, deps: [{ token: i1.ActivatedRoute }, { token: i2$1.HttpClient }, { token: DDR_OAUTH2_CONFIG }], target: i0.ɵɵFactoryTarget.Injectable });
846
- OAuth2Service.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: OAuth2Service });
847
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: OAuth2Service, decorators: [{
848
- type: Injectable
849
- }], ctorParameters: function () {
850
- return [{ type: i1.ActivatedRoute }, { type: i2$1.HttpClient }, { type: OAuth2Config, decorators: [{
851
- type: Inject,
852
- args: [DDR_OAUTH2_CONFIG]
853
- }] }];
854
- } });
855
-
856
- class OAuth2RefreshTokenInterceptor {
857
- constructor(oAuth2Service) {
858
- this.oAuth2Service = oAuth2Service;
859
- }
860
- /**
861
- * @override
862
- */
863
- intercept(req, next) {
864
- if (this.oAuth2Service.isRefreshPossibleAndRequired(req)) {
865
- return this.oAuth2Service.performRefresh().pipe(switchMap(() => next.handle(req)));
866
- }
867
- return next.handle(req);
868
- }
869
- }
870
- OAuth2RefreshTokenInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: OAuth2RefreshTokenInterceptor, deps: [{ token: OAuth2Service }], target: i0.ɵɵFactoryTarget.Injectable });
871
- OAuth2RefreshTokenInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: OAuth2RefreshTokenInterceptor });
872
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: OAuth2RefreshTokenInterceptor, decorators: [{
873
- type: Injectable
874
- }], ctorParameters: function () { return [{ type: OAuth2Service }]; } });
875
-
876
- class RedirectToOAuth2LoginInterceptor {
877
- constructor(oAuth2Service, router, oAuth2Config) {
878
- this.oAuth2Service = oAuth2Service;
879
- this.router = router;
880
- this.oAuth2Config = oAuth2Config;
881
- }
882
- /**
883
- * @override
884
- */
885
- intercept(req, next) {
886
- return next.handle(req).pipe(catchError((err) => {
887
- if (err instanceof HttpErrorResponse) {
888
- if (err.status === 401) {
889
- if (!window.location.href.startsWith(this.oAuth2Config.redirectUri)) {
890
- this.oAuth2Service.setReturnUrl(this.router.routerState.snapshot.url);
891
- this.oAuth2Service.redirectToLogin();
892
- }
893
- }
894
- }
895
- return throwError(err);
896
- }));
897
- }
898
- }
899
- RedirectToOAuth2LoginInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: RedirectToOAuth2LoginInterceptor, deps: [{ token: OAuth2Service }, { token: i1.Router }, { token: DDR_OAUTH2_CONFIG }], target: i0.ɵɵFactoryTarget.Injectable });
900
- RedirectToOAuth2LoginInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: RedirectToOAuth2LoginInterceptor });
901
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: RedirectToOAuth2LoginInterceptor, decorators: [{
902
- type: Injectable
903
- }], ctorParameters: function () {
904
- return [{ type: OAuth2Service }, { type: i1.Router }, { type: OAuth2Config, decorators: [{
905
- type: Inject,
906
- args: [DDR_OAUTH2_CONFIG]
907
- }] }];
908
- } });
909
-
910
- class OAuth2AccessTokenInterceptor {
911
- constructor(oAuth2Service) {
912
- this.oAuth2Service = oAuth2Service;
913
- }
914
- /**
915
- * @override
916
- */
917
- intercept(req, next) {
918
- const accessTokenString = this.oAuth2Service.getAccessTokenString();
919
- if (null !== accessTokenString && !this.oAuth2Service.isAccessTokenExpired()) {
920
- req = req.clone({
921
- headers: req.headers.set('Authorization', 'Bearer ' + accessTokenString)
922
- });
923
- }
924
- return next.handle(req);
925
- }
926
- }
927
- OAuth2AccessTokenInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: OAuth2AccessTokenInterceptor, deps: [{ token: OAuth2Service }], target: i0.ɵɵFactoryTarget.Injectable });
928
- OAuth2AccessTokenInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: OAuth2AccessTokenInterceptor });
929
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: OAuth2AccessTokenInterceptor, decorators: [{
930
- type: Injectable
931
- }], ctorParameters: function () { return [{ type: OAuth2Service }]; } });
932
-
933
- class OAuth2Module {
934
- static forRoot(config) {
935
- return {
936
- ngModule: OAuth2Module,
937
- providers: [
938
- OAuth2Service,
939
- {
940
- provide: DDR_OAUTH2_CONFIG,
941
- useValue: config
942
- },
943
- {
944
- provide: HTTP_INTERCEPTORS,
945
- useClass: OAuth2RefreshTokenInterceptor,
946
- multi: true
947
- },
948
- {
949
- provide: HTTP_INTERCEPTORS,
950
- useClass: RedirectToOAuth2LoginInterceptor,
951
- multi: true
952
- },
953
- {
954
- provide: HTTP_INTERCEPTORS,
955
- useClass: OAuth2AccessTokenInterceptor,
956
- multi: true
957
- }
958
- ],
959
- };
960
- }
961
- }
962
- OAuth2Module.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: OAuth2Module, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
963
- OAuth2Module.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.2.3", ngImport: i0, type: OAuth2Module });
964
- OAuth2Module.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: OAuth2Module });
965
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: OAuth2Module, decorators: [{
966
- type: NgModule
967
- }] });
968
-
969
- function isNonNull(value) {
970
- return value != null;
971
- }
972
-
973
- class JwtService {
974
- constructor(storageService) {
975
- this.storageService = storageService;
976
- /**
977
- * The current token.
978
- */
979
- this.token = null;
980
- /**
981
- * The expiry of the current token.
982
- */
983
- this.tokenExpiry = null;
984
- }
985
- /**
986
- * Sets the current token and a refresh token.
987
- */
988
- setTokens(token, refreshToken) {
989
- this.setToken(token);
990
- this.storageService.store(this.getRefreshTokenStorageKey(), refreshToken);
991
- }
992
- /**
993
- * Sets the current token.
994
- */
995
- setToken(token) {
996
- this.token = token;
997
- const decodedToken = JSON.parse(atob(token.split('.')[1]));
998
- this.tokenExpiry = decodedToken.exp * 1000;
999
- console.log('New refresh token, expiry', new Date(this.tokenExpiry));
1000
- }
1001
- /**
1002
- * Gets the current token.
1003
- */
1004
- getToken() {
1005
- return this.token;
1006
- }
1007
- /**
1008
- * Gets the refresh token.
1009
- */
1010
- getRefreshToken() {
1011
- return this.storageService.retrieve(this.getRefreshTokenStorageKey());
1012
- }
1013
- /**
1014
- * Checks if the current token expired.
1015
- */
1016
- isExpired() {
1017
- const now = new Date().getTime();
1018
- return null == this.tokenExpiry || this.tokenExpiry < now;
1019
- }
1020
- /**
1021
- * Checks if the current token is about to expire.
1022
- * @param expiryMs
1023
- */
1024
- isAboutToExpire(expiryMs = 60000) {
1025
- const now = new Date().getTime();
1026
- return null == this.tokenExpiry || this.tokenExpiry - expiryMs < now;
1027
- }
1028
- /**
1029
- * Clears all token information.
1030
- */
1031
- clear() {
1032
- this.token = null;
1033
- this.tokenExpiry = null;
1034
- this.storageService.remove(this.getRefreshTokenStorageKey());
1035
- }
1036
- getRefreshTokenStorageKey() {
1037
- return 'jwt.refresh_token';
1038
- }
1039
- }
1040
- JwtService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: JwtService, deps: [{ token: StorageService }], target: i0.ɵɵFactoryTarget.Injectable });
1041
- JwtService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: JwtService, providedIn: 'root' });
1042
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: JwtService, decorators: [{
1043
- type: Injectable,
1044
- args: [{
1045
- providedIn: 'root'
1046
- }]
1047
- }], ctorParameters: function () { return [{ type: StorageService }]; } });
1048
-
1049
- class JwtInterceptor {
1050
- constructor(jwtService) {
1051
- this.jwtService = jwtService;
1052
- }
1053
- /**
1054
- * @override
1055
- */
1056
- intercept(req, next) {
1057
- const token = this.jwtService.getToken();
1058
- if (null !== token && !this.jwtService.isExpired()) {
1059
- req = req.clone({
1060
- headers: req.headers.set('Authorization', 'Bearer ' + token)
1061
- });
1062
- }
1063
- return next.handle(req);
1064
- }
1065
- }
1066
- JwtInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: JwtInterceptor, deps: [{ token: JwtService }], target: i0.ɵɵFactoryTarget.Injectable });
1067
- JwtInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: JwtInterceptor });
1068
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: JwtInterceptor, decorators: [{
1069
- type: Injectable
1070
- }], ctorParameters: function () { return [{ type: JwtService }]; } });
1071
-
1072
- class JwtRefreshTokenInterceptor {
1073
- constructor(jwtService, httpClient, jwtRefreshTokenUrl) {
1074
- this.jwtService = jwtService;
1075
- this.httpClient = httpClient;
1076
- this.jwtRefreshTokenUrl = jwtRefreshTokenUrl;
1077
- this.refreshTokenRequest$ = null;
1078
- }
1079
- /**
1080
- * @override
1081
- */
1082
- intercept(req, next) {
1083
- if (this.jwtService.isAboutToExpire() && !(req.url === this.jwtRefreshTokenUrl)) {
1084
- const refreshToken = this.jwtService.getRefreshToken();
1085
- if (null != refreshToken) {
1086
- return this.getRefreshTokenRequest(refreshToken).pipe(switchMap(() => next.handle(req)));
1087
- }
1088
- }
1089
- return next.handle(req);
1090
- }
1091
- getRefreshTokenRequest(refreshToken) {
1092
- if (null == this.refreshTokenRequest$) {
1093
- this.refreshTokenRequest$ = this.httpClient.post(this.jwtRefreshTokenUrl, { refresh_token: refreshToken }).pipe(map(response => {
1094
- this.jwtService.setTokens(response.token, response.refresh_token);
1095
- this.refreshTokenRequest$ = null;
1096
- return response;
1097
- }), catchError(error => {
1098
- this.jwtService.clear();
1099
- this.refreshTokenRequest$ = null;
1100
- return throwError(error);
1101
- }), shareReplay(1));
1102
- }
1103
- return this.refreshTokenRequest$;
1104
- }
1105
- }
1106
- JwtRefreshTokenInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: JwtRefreshTokenInterceptor, deps: [{ token: JwtService }, { token: i2$1.HttpClient }, { token: DDR_JWT_REFRESH_TOKEN_URL }], target: i0.ɵɵFactoryTarget.Injectable });
1107
- JwtRefreshTokenInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: JwtRefreshTokenInterceptor });
1108
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.3", ngImport: i0, type: JwtRefreshTokenInterceptor, decorators: [{
1109
- type: Injectable
1110
- }], ctorParameters: function () {
1111
- return [{ type: JwtService }, { type: i2$1.HttpClient }, { type: undefined, decorators: [{
1112
- type: Inject,
1113
- args: [DDR_JWT_REFRESH_TOKEN_URL]
1114
- }] }];
1115
- } });
1116
-
1117
- /*
1118
- * Public API Surface of ngx-extensions
1119
- */
1120
-
1121
- /**
1122
- * Generated bundle index. Do not edit.
1123
- */
1124
-
1125
- 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 };
1126
- //# sourceMappingURL=dontdrinkandroot-ngx-extensions.mjs.map