@delon/auth 12.4.2 → 13.1.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 (49) hide show
  1. package/auth.d.ts +1 -0
  2. package/{esm2015/auth.js → esm2020/auth.mjs} +0 -0
  3. package/{esm2015/index.js → esm2020/index.mjs} +0 -0
  4. package/{esm2015/src/auth.config.js → esm2020/src/auth.config.mjs} +0 -0
  5. package/esm2020/src/auth.module.mjs +12 -0
  6. package/esm2020/src/social/social.service.mjs +105 -0
  7. package/{esm2015/src/store/cookie-storage.service.js → esm2020/src/store/cookie-storage.service.mjs} +0 -0
  8. package/{esm2015/src/store/interface.js → esm2020/src/store/interface.mjs} +0 -0
  9. package/{esm2015/src/store/local-storage.service.js → esm2020/src/store/local-storage.service.mjs} +0 -0
  10. package/{esm2015/src/store/memory.service.js → esm2020/src/store/memory.service.mjs} +0 -0
  11. package/{esm2015/src/store/session-storage.service.js → esm2020/src/store/session-storage.service.mjs} +0 -0
  12. package/esm2020/src/token/base.interceptor.mjs +86 -0
  13. package/esm2020/src/token/helper.mjs +32 -0
  14. package/{esm2015/src/token/interface.js → esm2020/src/token/interface.mjs} +0 -0
  15. package/esm2020/src/token/jwt/jwt.guard.mjs +63 -0
  16. package/{esm2015/src/token/jwt/jwt.helper.js → esm2020/src/token/jwt/jwt.helper.mjs} +0 -0
  17. package/esm2020/src/token/jwt/jwt.interceptor.mjs +33 -0
  18. package/{esm2015/src/token/jwt/jwt.model.js → esm2020/src/token/jwt/jwt.model.mjs} +0 -0
  19. package/esm2020/src/token/simple/simple.guard.mjs +62 -0
  20. package/esm2020/src/token/simple/simple.interceptor.mjs +51 -0
  21. package/{esm2015/src/token/simple/simple.model.js → esm2020/src/token/simple/simple.model.mjs} +1 -1
  22. package/esm2020/src/token/token.service.mjs +92 -0
  23. package/fesm2015/{auth.js → auth.mjs} +80 -50
  24. package/fesm2015/auth.mjs.map +1 -0
  25. package/fesm2020/auth.mjs +717 -0
  26. package/fesm2020/auth.mjs.map +1 -0
  27. package/package.json +21 -9
  28. package/src/auth.module.d.ts +4 -0
  29. package/src/social/social.service.d.ts +3 -0
  30. package/src/token/base.interceptor.d.ts +3 -0
  31. package/src/token/jwt/jwt.guard.d.ts +3 -0
  32. package/src/token/jwt/jwt.interceptor.d.ts +3 -0
  33. package/src/token/simple/simple.guard.d.ts +3 -0
  34. package/src/token/simple/simple.interceptor.d.ts +3 -0
  35. package/src/token/simple/simple.model.d.ts +1 -1
  36. package/src/token/token.service.d.ts +5 -1
  37. package/auth.metadata.json +0 -1
  38. package/bundles/auth.umd.js +0 -1140
  39. package/bundles/auth.umd.js.map +0 -1
  40. package/esm2015/src/auth.module.js +0 -7
  41. package/esm2015/src/social/social.service.js +0 -96
  42. package/esm2015/src/token/base.interceptor.js +0 -84
  43. package/esm2015/src/token/helper.js +0 -30
  44. package/esm2015/src/token/jwt/jwt.guard.js +0 -63
  45. package/esm2015/src/token/jwt/jwt.interceptor.js +0 -30
  46. package/esm2015/src/token/simple/simple.guard.js +0 -62
  47. package/esm2015/src/token/simple/simple.interceptor.js +0 -48
  48. package/esm2015/src/token/token.service.js +0 -89
  49. package/fesm2015/auth.js.map +0 -1
@@ -0,0 +1,717 @@
1
+ import { DOCUMENT } from '@angular/common';
2
+ import * as i0 from '@angular/core';
3
+ import { InjectionToken, inject, Injectable, Inject, Optional, NgModule } from '@angular/core';
4
+ import { Subject, BehaviorSubject, interval, Observable } from 'rxjs';
5
+ import { share, map, filter } from 'rxjs/operators';
6
+ import * as i1 from '@delon/util/config';
7
+ import { AlainConfigService } from '@delon/util/config';
8
+ import * as i1$1 from '@angular/router';
9
+ import { Router } from '@angular/router';
10
+ import { HttpParams, HttpErrorResponse, HTTP_INTERCEPTORS } from '@angular/common/http';
11
+
12
+ const AUTH_DEFAULT_CONFIG = {
13
+ store_key: `_token`,
14
+ token_invalid_redirect: true,
15
+ token_exp_offset: 10,
16
+ token_send_key: `token`,
17
+ token_send_template: '${token}',
18
+ token_send_place: 'header',
19
+ login_url: '/login',
20
+ ignores: [/\/login/, /assets\//, /passport\//],
21
+ allow_anonymous_key: `_allow_anonymous`,
22
+ executeOtherInterceptors: true,
23
+ refreshTime: 3000,
24
+ refreshOffset: 6000
25
+ };
26
+ function mergeConfig(srv) {
27
+ return srv.merge('auth', AUTH_DEFAULT_CONFIG);
28
+ }
29
+
30
+ function DA_STORE_TOKEN_LOCAL_FACTORY() {
31
+ return new LocalStorageStore();
32
+ }
33
+ /**
34
+ * `localStorage` storage, **not lost after closing the browser**.
35
+ *
36
+ * ```ts
37
+ * // global-config.module.ts
38
+ * { provide: DA_STORE_TOKEN, useClass: LocalStorageStore }
39
+ * ```
40
+ */
41
+ class LocalStorageStore {
42
+ get(key) {
43
+ return JSON.parse(localStorage.getItem(key) || '{}') || {};
44
+ }
45
+ set(key, value) {
46
+ localStorage.setItem(key, JSON.stringify(value));
47
+ return true;
48
+ }
49
+ remove(key) {
50
+ localStorage.removeItem(key);
51
+ }
52
+ }
53
+
54
+ const DA_STORE_TOKEN = new InjectionToken('AUTH_STORE_TOKEN', {
55
+ providedIn: 'root',
56
+ factory: DA_STORE_TOKEN_LOCAL_FACTORY
57
+ });
58
+
59
+ function DA_SERVICE_TOKEN_FACTORY() {
60
+ return new TokenService(inject(AlainConfigService), inject(DA_STORE_TOKEN));
61
+ }
62
+ /**
63
+ * 维护Token信息服务,[在线文档](https://ng-alain.com/auth)
64
+ */
65
+ class TokenService {
66
+ constructor(configSrv, store) {
67
+ this.store = store;
68
+ this.refresh$ = new Subject();
69
+ this.change$ = new BehaviorSubject(null);
70
+ this._referrer = {};
71
+ this._options = mergeConfig(configSrv);
72
+ }
73
+ get refresh() {
74
+ this.builderRefresh();
75
+ return this.refresh$.pipe(share());
76
+ }
77
+ get login_url() {
78
+ return this._options.login_url;
79
+ }
80
+ get referrer() {
81
+ return this._referrer;
82
+ }
83
+ get options() {
84
+ return this._options;
85
+ }
86
+ set(data) {
87
+ const res = this.store.set(this._options.store_key, data);
88
+ this.change$.next(data);
89
+ return res;
90
+ }
91
+ get(type) {
92
+ const data = this.store.get(this._options.store_key);
93
+ return type ? Object.assign(new type(), data) : data;
94
+ }
95
+ clear(options = { onlyToken: false }) {
96
+ let data = null;
97
+ if (options.onlyToken === true) {
98
+ data = this.get();
99
+ data.token = ``;
100
+ this.set(data);
101
+ }
102
+ else {
103
+ this.store.remove(this._options.store_key);
104
+ }
105
+ this.change$.next(data);
106
+ }
107
+ change() {
108
+ return this.change$.pipe(share());
109
+ }
110
+ builderRefresh() {
111
+ const { refreshTime, refreshOffset } = this._options;
112
+ this.cleanRefresh();
113
+ this.interval$ = interval(refreshTime)
114
+ .pipe(map(() => {
115
+ const item = this.get();
116
+ const expired = item.expired || item.exp || 0;
117
+ if (expired <= 0) {
118
+ return null;
119
+ }
120
+ const curTime = new Date().valueOf() + refreshOffset;
121
+ return expired <= curTime ? item : null;
122
+ }), filter(v => v != null))
123
+ .subscribe(res => this.refresh$.next(res));
124
+ }
125
+ cleanRefresh() {
126
+ if (this.interval$ && !this.interval$.closed) {
127
+ this.interval$.unsubscribe();
128
+ }
129
+ }
130
+ ngOnDestroy() {
131
+ this.cleanRefresh();
132
+ }
133
+ }
134
+ TokenService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: TokenService, deps: [{ token: i1.AlainConfigService }, { token: DA_STORE_TOKEN }], target: i0.ɵɵFactoryTarget.Injectable });
135
+ TokenService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: TokenService });
136
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: TokenService, decorators: [{
137
+ type: Injectable
138
+ }], ctorParameters: function () { return [{ type: i1.AlainConfigService }, { type: undefined, decorators: [{
139
+ type: Inject,
140
+ args: [DA_STORE_TOKEN]
141
+ }] }]; } });
142
+
143
+ const DA_SERVICE_TOKEN = new InjectionToken('DA_SERVICE_TOKEN', {
144
+ providedIn: 'root',
145
+ factory: DA_SERVICE_TOKEN_FACTORY
146
+ });
147
+
148
+ const OPENTYPE = '_delonAuthSocialType';
149
+ const HREFCALLBACK = '_delonAuthSocialCallbackByHref';
150
+ class SocialService {
151
+ constructor(tokenService, doc, router) {
152
+ this.tokenService = tokenService;
153
+ this.doc = doc;
154
+ this.router = router;
155
+ this._win = null;
156
+ }
157
+ /**
158
+ * 跳转至登录页,若为 `type=window` 时,返回值是 `Observable<ITokenModel>`
159
+ *
160
+ * @param url 获取授权地址
161
+ * @param callback 当 `type=href` 成功时的回调路由地址
162
+ * @param options.type 打开方式,默认 `window`
163
+ * @param options.windowFeatures 等同 `window.open` 的 `features` 参数值
164
+ */
165
+ login(url, callback = '/', options = {}) {
166
+ options = {
167
+ type: 'window',
168
+ windowFeatures: 'location=yes,height=570,width=520,scrollbars=yes,status=yes',
169
+ ...options
170
+ };
171
+ localStorage.setItem(OPENTYPE, options.type);
172
+ localStorage.setItem(HREFCALLBACK, callback);
173
+ if (options.type === 'href') {
174
+ this.doc.location.href = url;
175
+ return;
176
+ }
177
+ this._win = window.open(url, '_blank', options.windowFeatures);
178
+ this._winTime = setInterval(() => {
179
+ if (this._win && this._win.closed) {
180
+ this.ngOnDestroy();
181
+ let model = this.tokenService.get();
182
+ if (model && !model.token)
183
+ model = null;
184
+ // 触发变更通知
185
+ if (model) {
186
+ this.tokenService.set(model);
187
+ }
188
+ this.observer.next(model);
189
+ this.observer.complete();
190
+ }
191
+ }, 100);
192
+ return new Observable((observer) => {
193
+ this.observer = observer;
194
+ });
195
+ }
196
+ /**
197
+ * 授权成功后的回调处理
198
+ *
199
+ * @param rawData 指定回调认证信息,为空时从根据当前URL解析
200
+ */
201
+ callback(rawData) {
202
+ // from uri
203
+ if (!rawData && this.router.url.indexOf('?') === -1) {
204
+ throw new Error(`url muse contain a ?`);
205
+ }
206
+ // parse
207
+ let data = { token: `` };
208
+ if (typeof rawData === 'string') {
209
+ const rightUrl = rawData.split('?')[1].split('#')[0];
210
+ data = this.router.parseUrl(`./?${rightUrl}`).queryParams;
211
+ }
212
+ else {
213
+ data = rawData;
214
+ }
215
+ if (!data || !data.token)
216
+ throw new Error(`invalide token data`);
217
+ this.tokenService.set(data);
218
+ const url = localStorage.getItem(HREFCALLBACK) || '/';
219
+ localStorage.removeItem(HREFCALLBACK);
220
+ const type = localStorage.getItem(OPENTYPE);
221
+ localStorage.removeItem(OPENTYPE);
222
+ if (type === 'window') {
223
+ window.close();
224
+ }
225
+ else {
226
+ this.router.navigateByUrl(url);
227
+ }
228
+ return data;
229
+ }
230
+ ngOnDestroy() {
231
+ clearInterval(this._winTime);
232
+ this._winTime = null;
233
+ }
234
+ }
235
+ SocialService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: SocialService, deps: [{ token: DA_SERVICE_TOKEN }, { token: DOCUMENT }, { token: i1$1.Router }], target: i0.ɵɵFactoryTarget.Injectable });
236
+ SocialService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: SocialService });
237
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: SocialService, decorators: [{
238
+ type: Injectable
239
+ }], ctorParameters: function () { return [{ type: undefined, decorators: [{
240
+ type: Inject,
241
+ args: [DA_SERVICE_TOKEN]
242
+ }] }, { type: undefined, decorators: [{
243
+ type: Inject,
244
+ args: [DOCUMENT]
245
+ }] }, { type: i1$1.Router }]; } });
246
+
247
+ /**
248
+ * 内存存储,关掉浏览器标签后**丢失**。
249
+ *
250
+ * ```ts
251
+ * // global-config.module.ts
252
+ * { provide: DA_STORE_TOKEN, useClass: MemoryStore }
253
+ * ```
254
+ */
255
+ class MemoryStore {
256
+ constructor() {
257
+ this.cache = {};
258
+ }
259
+ get(key) {
260
+ return this.cache[key] || {};
261
+ }
262
+ set(key, value) {
263
+ this.cache[key] = value;
264
+ return true;
265
+ }
266
+ remove(key) {
267
+ this.cache[key] = null;
268
+ }
269
+ }
270
+
271
+ /**
272
+ * `sessionStorage` storage, **lost after closing the browser**.
273
+ *
274
+ * ```ts
275
+ * // global-config.module.ts
276
+ * { provide: DA_STORE_TOKEN, useClass: SessionStorageStore }
277
+ * ```
278
+ */
279
+ class SessionStorageStore {
280
+ get(key) {
281
+ return JSON.parse(sessionStorage.getItem(key) || '{}') || {};
282
+ }
283
+ set(key, value) {
284
+ sessionStorage.setItem(key, JSON.stringify(value));
285
+ return true;
286
+ }
287
+ remove(key) {
288
+ sessionStorage.removeItem(key);
289
+ }
290
+ }
291
+
292
+ /**
293
+ * `cookie` storage
294
+ *
295
+ * ```ts
296
+ * // global-config.module.ts
297
+ * { provide: DA_STORE_TOKEN, useClass: CookieStorageStore, deps: [CookieService] }
298
+ * ```
299
+ */
300
+ class CookieStorageStore {
301
+ constructor(srv) {
302
+ this.srv = srv;
303
+ }
304
+ get(key) {
305
+ return JSON.parse(this.srv.get(key) || '{}') || {};
306
+ }
307
+ set(key, value) {
308
+ this.srv.put(key, value != null ? JSON.stringify(value) : '{}');
309
+ return true;
310
+ }
311
+ remove(key) {
312
+ this.srv.remove(key);
313
+ }
314
+ }
315
+
316
+ function CheckSimple(model) {
317
+ return model != null && typeof model.token === 'string' && model.token.length > 0;
318
+ }
319
+ function CheckJwt(model, offset) {
320
+ try {
321
+ return model != null && !!model.token && !model.isExpired(offset);
322
+ }
323
+ catch (err) {
324
+ if (typeof ngDevMode === 'undefined' || ngDevMode) {
325
+ console.warn(`${err.message}, jump to login_url`);
326
+ }
327
+ return false;
328
+ }
329
+ }
330
+ function ToLogin(options, injector, url) {
331
+ const router = injector.get(Router);
332
+ injector.get(DA_SERVICE_TOKEN).referrer.url = url || router.url;
333
+ if (options.token_invalid_redirect === true) {
334
+ setTimeout(() => {
335
+ if (/^https?:\/\//g.test(options.login_url)) {
336
+ injector.get(DOCUMENT).location.href = options.login_url;
337
+ }
338
+ else {
339
+ router.navigate([options.login_url]);
340
+ }
341
+ });
342
+ }
343
+ }
344
+
345
+ class HttpAuthInterceptorHandler {
346
+ constructor(next, interceptor) {
347
+ this.next = next;
348
+ this.interceptor = interceptor;
349
+ }
350
+ handle(req) {
351
+ return this.interceptor.intercept(req, this.next);
352
+ }
353
+ }
354
+ class BaseInterceptor {
355
+ constructor(injector) {
356
+ this.injector = injector;
357
+ }
358
+ intercept(req, next) {
359
+ const options = mergeConfig(this.injector.get(AlainConfigService));
360
+ if (Array.isArray(options.ignores)) {
361
+ for (const item of options.ignores) {
362
+ if (item.test(req.url))
363
+ return next.handle(req);
364
+ }
365
+ }
366
+ const ingoreKey = options.allow_anonymous_key;
367
+ let ingored = false;
368
+ let params = req.params;
369
+ let url = req.url;
370
+ if (req.params.has(ingoreKey)) {
371
+ params = req.params.delete(ingoreKey);
372
+ ingored = true;
373
+ }
374
+ const urlArr = req.url.split('?');
375
+ if (urlArr.length > 1) {
376
+ const queryStringParams = new HttpParams({ fromString: urlArr[1] });
377
+ if (queryStringParams.has(ingoreKey)) {
378
+ const queryString = queryStringParams.delete(ingoreKey).toString();
379
+ url = queryString.length > 0 ? `${urlArr[0]}?${queryString}` : urlArr[0];
380
+ ingored = true;
381
+ }
382
+ }
383
+ if (ingored) {
384
+ return next.handle(req.clone({ params, url }));
385
+ }
386
+ if (this.isAuth(options)) {
387
+ req = this.setReq(req, options);
388
+ }
389
+ else {
390
+ ToLogin(options, this.injector);
391
+ // Interrupt Http request, so need to generate a new Observable
392
+ const err$ = new Observable((observer) => {
393
+ const res = new HttpErrorResponse({
394
+ url: req.url,
395
+ headers: req.headers,
396
+ status: 401,
397
+ statusText: `来自 @delon/auth 的拦截,所请求URL未授权,若是登录API可加入 [url?_allow_anonymous=true] 来表示忽略校验,更多方法请参考: https://ng-alain.com/auth/getting-started#AlainAuthConfig\nThe interception from @delon/auth, the requested URL is not authorized. If the login API can add [url?_allow_anonymous=true] to ignore the check, please refer to: https://ng-alain.com/auth/getting-started#AlainAuthConfig`
398
+ });
399
+ observer.error(res);
400
+ });
401
+ if (options.executeOtherInterceptors) {
402
+ const interceptors = this.injector.get(HTTP_INTERCEPTORS, []);
403
+ const lastInterceptors = interceptors.slice(interceptors.indexOf(this) + 1);
404
+ if (lastInterceptors.length > 0) {
405
+ const chain = lastInterceptors.reduceRight((_next, _interceptor) => new HttpAuthInterceptorHandler(_next, _interceptor), {
406
+ handle: (_) => err$
407
+ });
408
+ return chain.handle(req);
409
+ }
410
+ }
411
+ return err$;
412
+ }
413
+ return next.handle(req);
414
+ }
415
+ }
416
+ BaseInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: BaseInterceptor, deps: [{ token: i0.Injector, optional: true }], target: i0.ɵɵFactoryTarget.Injectable });
417
+ BaseInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: BaseInterceptor });
418
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: BaseInterceptor, decorators: [{
419
+ type: Injectable
420
+ }], ctorParameters: function () { return [{ type: i0.Injector, decorators: [{
421
+ type: Optional
422
+ }] }]; } });
423
+
424
+ function urlBase64Decode(str) {
425
+ let output = str.replace(/-/g, '+').replace(/_/g, '/');
426
+ switch (output.length % 4) {
427
+ case 0: {
428
+ break;
429
+ }
430
+ case 2: {
431
+ output += '==';
432
+ break;
433
+ }
434
+ case 3: {
435
+ output += '=';
436
+ break;
437
+ }
438
+ default: {
439
+ throw new Error(`'atob' failed: The string to be decoded is not correctly encoded.`);
440
+ }
441
+ }
442
+ return b64DecodeUnicode(output);
443
+ }
444
+ function b64decode(str) {
445
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
446
+ let output = '';
447
+ str = String(str).replace(/=+$/, '');
448
+ for (
449
+ // initialize result and counters
450
+ let bc = 0, bs, buffer, idx = 0;
451
+ // get next character
452
+ (buffer = str.charAt(idx++));
453
+ // character found in table? initialize bit storage and add its ascii value;
454
+ ~buffer &&
455
+ ((bs = bc % 4 ? bs * 64 + buffer : buffer),
456
+ // and if not first of each 4 characters,
457
+ // convert the first 8 bits to one ascii character
458
+ bc++ % 4)
459
+ ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))
460
+ : 0) {
461
+ // try to find character in table (0-63, not found => -1)
462
+ buffer = chars.indexOf(buffer);
463
+ }
464
+ return output;
465
+ }
466
+ // https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem
467
+ function b64DecodeUnicode(str) {
468
+ return decodeURIComponent(Array.prototype.map
469
+ .call(b64decode(str), (c) => {
470
+ return `%${`00${c.charCodeAt(0).toString(16)}`.slice(-2)}`;
471
+ })
472
+ .join(''));
473
+ }
474
+
475
+ class JWTTokenModel {
476
+ /**
477
+ * 获取载荷信息
478
+ */
479
+ get payload() {
480
+ const parts = (this.token || '').split('.');
481
+ if (parts.length !== 3)
482
+ throw new Error('JWT must have 3 parts');
483
+ const decoded = urlBase64Decode(parts[1]);
484
+ return JSON.parse(decoded);
485
+ }
486
+ /**
487
+ * 获取过期时间戳(单位:ms)
488
+ */
489
+ get exp() {
490
+ const decoded = this.payload;
491
+ if (!decoded.hasOwnProperty('exp'))
492
+ return null;
493
+ const date = new Date(0);
494
+ date.setUTCSeconds(decoded.exp);
495
+ return date.valueOf();
496
+ }
497
+ /**
498
+ * 检查Token是否过期,当`payload` 包含 `exp` 字段时有效,若无 `exp` 字段直接返回 `null`
499
+ *
500
+ * @param offsetSeconds 偏移量
501
+ */
502
+ isExpired(offsetSeconds = 0) {
503
+ const exp = this.exp;
504
+ if (exp == null)
505
+ return null;
506
+ return !(exp > new Date().valueOf() + offsetSeconds * 1000);
507
+ }
508
+ }
509
+
510
+ /**
511
+ * JWT 拦截器
512
+ *
513
+ * ```
514
+ * // app.module.ts
515
+ * { provide: HTTP_INTERCEPTORS, useClass: JWTInterceptor, multi: true}
516
+ * ```
517
+ */
518
+ class JWTInterceptor extends BaseInterceptor {
519
+ isAuth(options) {
520
+ this.model = this.injector.get(DA_SERVICE_TOKEN).get(JWTTokenModel);
521
+ return CheckJwt(this.model, options.token_exp_offset);
522
+ }
523
+ setReq(req, _options) {
524
+ return req.clone({
525
+ setHeaders: {
526
+ Authorization: `Bearer ${this.model.token}`
527
+ }
528
+ });
529
+ }
530
+ }
531
+ JWTInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: JWTInterceptor, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
532
+ JWTInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: JWTInterceptor });
533
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: JWTInterceptor, decorators: [{
534
+ type: Injectable
535
+ }] });
536
+
537
+ /**
538
+ * JWT 路由守卫, [ACL Document](https://ng-alain.com/auth/guard).
539
+ *
540
+ * ```ts
541
+ * data: {
542
+ * path: 'home',
543
+ * canActivate: [ JWTGuard ]
544
+ * },
545
+ * {
546
+ * path: 'my',
547
+ * canActivateChild: [JWTGuard],
548
+ * children: [
549
+ * { path: 'profile', component: MockComponent }
550
+ * ],
551
+ * },
552
+ * ```
553
+ */
554
+ class JWTGuard {
555
+ constructor(srv, injector) {
556
+ this.srv = srv;
557
+ this.injector = injector;
558
+ }
559
+ get cog() {
560
+ return this.srv.options;
561
+ }
562
+ process() {
563
+ const res = CheckJwt(this.srv.get(JWTTokenModel), this.cog.token_exp_offset);
564
+ if (!res) {
565
+ ToLogin(this.cog, this.injector, this.url);
566
+ }
567
+ return res;
568
+ }
569
+ // lazy loading
570
+ canLoad(route, _segments) {
571
+ this.url = route.path;
572
+ return this.process();
573
+ }
574
+ // all children route
575
+ canActivateChild(_childRoute, state) {
576
+ this.url = state.url;
577
+ return this.process();
578
+ }
579
+ // route
580
+ canActivate(_route, state) {
581
+ this.url = state.url;
582
+ return this.process();
583
+ }
584
+ }
585
+ JWTGuard.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: JWTGuard, deps: [{ token: DA_SERVICE_TOKEN }, { token: i0.Injector }], target: i0.ɵɵFactoryTarget.Injectable });
586
+ JWTGuard.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: JWTGuard, providedIn: 'root' });
587
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: JWTGuard, decorators: [{
588
+ type: Injectable,
589
+ args: [{ providedIn: 'root' }]
590
+ }], ctorParameters: function () { return [{ type: undefined, decorators: [{
591
+ type: Inject,
592
+ args: [DA_SERVICE_TOKEN]
593
+ }] }, { type: i0.Injector }]; } });
594
+
595
+ class SimpleTokenModel {
596
+ }
597
+
598
+ /**
599
+ * Simple 拦截器
600
+ *
601
+ * ```
602
+ * // app.module.ts
603
+ * { provide: HTTP_INTERCEPTORS, useClass: SimpleInterceptor, multi: true}
604
+ * ```
605
+ */
606
+ class SimpleInterceptor extends BaseInterceptor {
607
+ isAuth(_options) {
608
+ this.model = this.injector.get(DA_SERVICE_TOKEN).get();
609
+ return CheckSimple(this.model);
610
+ }
611
+ setReq(req, options) {
612
+ const { token_send_template, token_send_key } = options;
613
+ const token = token_send_template.replace(/\$\{([\w]+)\}/g, (_, g) => this.model[g]);
614
+ switch (options.token_send_place) {
615
+ case 'header':
616
+ const obj = {};
617
+ obj[token_send_key] = token;
618
+ req = req.clone({
619
+ setHeaders: obj
620
+ });
621
+ break;
622
+ case 'body':
623
+ const body = req.body || {};
624
+ body[token_send_key] = token;
625
+ req = req.clone({
626
+ body
627
+ });
628
+ break;
629
+ case 'url':
630
+ req = req.clone({
631
+ params: req.params.append(token_send_key, token)
632
+ });
633
+ break;
634
+ }
635
+ return req;
636
+ }
637
+ }
638
+ SimpleInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: SimpleInterceptor, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
639
+ SimpleInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: SimpleInterceptor });
640
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: SimpleInterceptor, decorators: [{
641
+ type: Injectable
642
+ }] });
643
+
644
+ /**
645
+ * Simple 路由守卫, [ACL Document](https://ng-alain.com/auth/guard).
646
+ *
647
+ * ```ts
648
+ * data: {
649
+ * path: 'home',
650
+ * canActivate: [ SimpleGuard ]
651
+ * },
652
+ * {
653
+ * path: 'my',
654
+ * canActivateChild: [SimpleGuard],
655
+ * children: [
656
+ * { path: 'profile', component: MockComponent }
657
+ * ],
658
+ * },
659
+ * ```
660
+ */
661
+ class SimpleGuard {
662
+ constructor(srv, injector) {
663
+ this.srv = srv;
664
+ this.injector = injector;
665
+ }
666
+ get cog() {
667
+ return this.srv.options;
668
+ }
669
+ process() {
670
+ const res = CheckSimple(this.srv.get());
671
+ if (!res) {
672
+ ToLogin(this.cog, this.injector, this.url);
673
+ }
674
+ return res;
675
+ }
676
+ // lazy loading
677
+ canLoad(route, _segments) {
678
+ this.url = route.path;
679
+ return this.process();
680
+ }
681
+ // all children route
682
+ canActivateChild(_childRoute, state) {
683
+ this.url = state.url;
684
+ return this.process();
685
+ }
686
+ // route
687
+ canActivate(_route, state) {
688
+ this.url = state.url;
689
+ return this.process();
690
+ }
691
+ }
692
+ SimpleGuard.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: SimpleGuard, deps: [{ token: DA_SERVICE_TOKEN }, { token: i0.Injector }], target: i0.ɵɵFactoryTarget.Injectable });
693
+ SimpleGuard.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: SimpleGuard, providedIn: 'root' });
694
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: SimpleGuard, decorators: [{
695
+ type: Injectable,
696
+ args: [{ providedIn: 'root' }]
697
+ }], ctorParameters: function () { return [{ type: undefined, decorators: [{
698
+ type: Inject,
699
+ args: [DA_SERVICE_TOKEN]
700
+ }] }, { type: i0.Injector }]; } });
701
+
702
+ class DelonAuthModule {
703
+ }
704
+ DelonAuthModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: DelonAuthModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
705
+ DelonAuthModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: DelonAuthModule });
706
+ DelonAuthModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: DelonAuthModule });
707
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.1.2", ngImport: i0, type: DelonAuthModule, decorators: [{
708
+ type: NgModule,
709
+ args: [{}]
710
+ }] });
711
+
712
+ /**
713
+ * Generated bundle index. Do not edit.
714
+ */
715
+
716
+ export { AUTH_DEFAULT_CONFIG, BaseInterceptor, CookieStorageStore, DA_SERVICE_TOKEN, DA_SERVICE_TOKEN_FACTORY, DA_STORE_TOKEN, DA_STORE_TOKEN_LOCAL_FACTORY, DelonAuthModule, JWTGuard, JWTInterceptor, JWTTokenModel, LocalStorageStore, MemoryStore, SessionStorageStore, SimpleGuard, SimpleInterceptor, SimpleTokenModel, SocialService, TokenService, mergeConfig, urlBase64Decode };
717
+ //# sourceMappingURL=auth.mjs.map