UNPKG

153 kBJavaScriptView Raw
1import * as i0 from '@angular/core';
2import { InjectionToken, Injectable, Inject, Component, ChangeDetectionStrategy, Injector, NgModule } from '@angular/core';
3import * as i4 from '@angular/common';
4import { CommonModule } from '@angular/common';
5import * as i2 from '@angular/router';
6import { RouterModule } from '@angular/router';
7import * as i5 from '@angular/forms';
8import { FormsModule } from '@angular/forms';
9import * as i3 from '@nebular/theme';
10import { NB_WINDOW, NbLayoutModule, NbCardModule, NbCheckboxModule, NbAlertModule, NbInputModule, NbButtonModule, NbIconModule } from '@nebular/theme';
11import { BehaviorSubject, of, Subject } from 'rxjs';
12import { filter, share, map, switchMap, delay, catchError, takeUntil } from 'rxjs/operators';
13import * as i1 from '@angular/common/http';
14import { HttpResponse, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
15
16const socialLinks = [];
17const defaultAuthOptions = {
18 strategies: [],
19 forms: {
20 login: {
21 redirectDelay: 500,
22 strategy: 'email',
23 rememberMe: true,
24 showMessages: {
25 success: true,
26 error: true,
27 },
28 socialLinks: socialLinks, // social links at the bottom of a page
29 },
30 register: {
31 redirectDelay: 500,
32 strategy: 'email',
33 showMessages: {
34 success: true,
35 error: true,
36 },
37 terms: true,
38 socialLinks: socialLinks,
39 },
40 requestPassword: {
41 redirectDelay: 500,
42 strategy: 'email',
43 showMessages: {
44 success: true,
45 error: true,
46 },
47 socialLinks: socialLinks,
48 },
49 resetPassword: {
50 redirectDelay: 500,
51 strategy: 'email',
52 showMessages: {
53 success: true,
54 error: true,
55 },
56 socialLinks: socialLinks,
57 },
58 logout: {
59 redirectDelay: 500,
60 strategy: 'email',
61 },
62 validation: {
63 password: {
64 required: true,
65 minLength: 4,
66 maxLength: 50,
67 },
68 email: {
69 required: true,
70 },
71 fullName: {
72 required: false,
73 minLength: 4,
74 maxLength: 50,
75 },
76 },
77 },
78};
79const NB_AUTH_OPTIONS = new InjectionToken('Nebular Auth Options');
80const NB_AUTH_USER_OPTIONS = new InjectionToken('Nebular User Auth Options');
81const NB_AUTH_STRATEGIES = new InjectionToken('Nebular Auth Strategies');
82const NB_AUTH_TOKENS = new InjectionToken('Nebular Auth Tokens');
83const NB_AUTH_INTERCEPTOR_HEADER = new InjectionToken('Nebular Simple Interceptor Header');
84const NB_AUTH_TOKEN_INTERCEPTOR_FILTER = new InjectionToken('Nebular Interceptor Filter');
85
86/**
87 * Extending object that entered in first argument.
88 *
89 * Returns extended object or false if have no target object or incorrect type.
90 *
91 * If you wish to clone source object (without modify it), just use empty new
92 * object as first argument, like this:
93 * deepExtend({}, yourObj_1, [yourObj_N]);
94 */
95const deepExtend = function (...objects) {
96 if (arguments.length < 1 || typeof arguments[0] !== 'object') {
97 return false;
98 }
99 if (arguments.length < 2) {
100 return arguments[0];
101 }
102 const target = arguments[0];
103 // convert arguments to array and cut off target object
104 const args = Array.prototype.slice.call(arguments, 1);
105 let val, src;
106 args.forEach(function (obj) {
107 // skip argument if it is array or isn't object
108 if (typeof obj !== 'object' || Array.isArray(obj)) {
109 return;
110 }
111 Object.keys(obj).forEach(function (key) {
112 src = target[key]; // source value
113 val = obj[key]; // new value
114 // recursion prevention
115 if (val === target) {
116 return;
117 /**
118 * if new value isn't object then just overwrite by new value
119 * instead of extending.
120 */
121 }
122 else if (typeof val !== 'object' || val === null) {
123 target[key] = val;
124 return;
125 // just clone arrays (and recursive clone objects inside)
126 }
127 else if (Array.isArray(val)) {
128 target[key] = deepCloneArray(val);
129 return;
130 // custom cloning and overwrite for specific objects
131 }
132 else if (isSpecificValue(val)) {
133 target[key] = cloneSpecificValue(val);
134 return;
135 // overwrite by new value if source isn't object or array
136 }
137 else if (typeof src !== 'object' || src === null || Array.isArray(src)) {
138 target[key] = deepExtend({}, val);
139 return;
140 // source value and new value is objects both, extending...
141 }
142 else {
143 target[key] = deepExtend(src, val);
144 return;
145 }
146 });
147 });
148 return target;
149};
150function isSpecificValue(val) {
151 return (val instanceof Date
152 || val instanceof RegExp) ? true : false;
153}
154function cloneSpecificValue(val) {
155 if (val instanceof Date) {
156 return new Date(val.getTime());
157 }
158 else if (val instanceof RegExp) {
159 return new RegExp(val);
160 }
161 else {
162 throw new Error('cloneSpecificValue: Unexpected situation');
163 }
164}
165/**
166 * Recursive cloning array.
167 */
168function deepCloneArray(arr) {
169 const clone = [];
170 arr.forEach(function (item, index) {
171 if (typeof item === 'object' && item !== null) {
172 if (Array.isArray(item)) {
173 clone[index] = deepCloneArray(item);
174 }
175 else if (isSpecificValue(item)) {
176 clone[index] = cloneSpecificValue(item);
177 }
178 else {
179 clone[index] = deepExtend({}, item);
180 }
181 }
182 else {
183 clone[index] = item;
184 }
185 });
186 return clone;
187}
188// getDeepFromObject({result: {data: 1}}, 'result.data', 2); // returns 1
189function getDeepFromObject(object = {}, name, defaultValue) {
190 const keys = name.split('.');
191 // clone the object
192 let level = deepExtend({}, object || {});
193 keys.forEach((k) => {
194 if (level && typeof level[k] !== 'undefined') {
195 level = level[k];
196 }
197 else {
198 level = undefined;
199 }
200 });
201 return typeof level === 'undefined' ? defaultValue : level;
202}
203function urlBase64Decode(str) {
204 let output = str.replace(/-/g, '+').replace(/_/g, '/');
205 switch (output.length % 4) {
206 case 0: {
207 break;
208 }
209 case 2: {
210 output += '==';
211 break;
212 }
213 case 3: {
214 output += '=';
215 break;
216 }
217 default: {
218 throw new Error('Illegal base64url string!');
219 }
220 }
221 return b64DecodeUnicode(output);
222}
223function b64decode(str) {
224 const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
225 let output = '';
226 str = String(str).replace(/=+$/, '');
227 if (str.length % 4 === 1) {
228 throw new Error(`'atob' failed: The string to be decoded is not correctly encoded.`);
229 }
230 for (
231 // initialize result and counters
232 let bc = 0, bs, buffer, idx = 0;
233 // get next character
234 buffer = str.charAt(idx++);
235 // character found in table? initialize bit storage and add its ascii value;
236 ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
237 // and if not first of each 4 characters,
238 // convert the first 8 bits to one ascii character
239 bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0) {
240 // try to find character in table (0-63, not found => -1)
241 buffer = chars.indexOf(buffer);
242 }
243 return output;
244}
245// https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem
246function b64DecodeUnicode(str) {
247 return decodeURIComponent(Array.prototype.map.call(b64decode(str), (c) => {
248 return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
249 }).join(''));
250}
251
252class NbAuthToken {
253 constructor() {
254 this.payload = null;
255 }
256 getName() {
257 return this.constructor.NAME;
258 }
259 getPayload() {
260 return this.payload;
261 }
262}
263class NbAuthTokenNotFoundError extends Error {
264 constructor(message) {
265 super(message);
266 Object.setPrototypeOf(this, new.target.prototype);
267 }
268}
269class NbAuthIllegalTokenError extends Error {
270 constructor(message) {
271 super(message);
272 Object.setPrototypeOf(this, new.target.prototype);
273 }
274}
275class NbAuthEmptyTokenError extends NbAuthIllegalTokenError {
276 constructor(message) {
277 super(message);
278 Object.setPrototypeOf(this, new.target.prototype);
279 }
280}
281class NbAuthIllegalJWTTokenError extends NbAuthIllegalTokenError {
282 constructor(message) {
283 super(message);
284 Object.setPrototypeOf(this, new.target.prototype);
285 }
286}
287function nbAuthCreateToken(tokenClass, token, ownerStrategyName, createdAt) {
288 return new tokenClass(token, ownerStrategyName, createdAt);
289}
290function decodeJwtPayload(payload) {
291 if (payload.length === 0) {
292 throw new NbAuthEmptyTokenError('Cannot extract from an empty payload.');
293 }
294 const parts = payload.split('.');
295 if (parts.length !== 3) {
296 throw new NbAuthIllegalJWTTokenError(`The payload ${payload} is not valid JWT payload and must consist of three parts.`);
297 }
298 let decoded;
299 try {
300 decoded = urlBase64Decode(parts[1]);
301 }
302 catch (e) {
303 throw new NbAuthIllegalJWTTokenError(`The payload ${payload} is not valid JWT payload and cannot be parsed.`);
304 }
305 if (!decoded) {
306 throw new NbAuthIllegalJWTTokenError(`The payload ${payload} is not valid JWT payload and cannot be decoded.`);
307 }
308 return JSON.parse(decoded);
309}
310/**
311 * Wrapper for simple (text) token
312 */
313class NbAuthSimpleToken extends NbAuthToken {
314 constructor(token, ownerStrategyName, createdAt) {
315 super();
316 this.token = token;
317 this.ownerStrategyName = ownerStrategyName;
318 this.createdAt = createdAt;
319 try {
320 this.parsePayload();
321 }
322 catch (err) {
323 if (!(err instanceof NbAuthTokenNotFoundError)) {
324 // token is present but has got a problem, including illegal
325 throw err;
326 }
327 }
328 this.createdAt = this.prepareCreatedAt(createdAt);
329 }
330 parsePayload() {
331 this.payload = null;
332 }
333 prepareCreatedAt(date) {
334 return date ? date : new Date();
335 }
336 /**
337 * Returns the token's creation date
338 * @returns {Date}
339 */
340 getCreatedAt() {
341 return this.createdAt;
342 }
343 /**
344 * Returns the token value
345 * @returns string
346 */
347 getValue() {
348 return this.token;
349 }
350 getOwnerStrategyName() {
351 return this.ownerStrategyName;
352 }
353 /**
354 * Is non empty and valid
355 * @returns {boolean}
356 */
357 isValid() {
358 return !!this.getValue();
359 }
360 /**
361 * Validate value and convert to string, if value is not valid return empty string
362 * @returns {string}
363 */
364 toString() {
365 return !!this.token ? this.token : '';
366 }
367}
368NbAuthSimpleToken.NAME = 'nb:auth:simple:token';
369/**
370 * Wrapper for JWT token with additional methods.
371 */
372class NbAuthJWTToken extends NbAuthSimpleToken {
373 /**
374 * for JWT token, the iat (issued at) field of the token payload contains the creation Date
375 */
376 prepareCreatedAt(date) {
377 const decoded = this.getPayload();
378 return decoded && decoded.iat ? new Date(Number(decoded.iat) * 1000) : super.prepareCreatedAt(date);
379 }
380 /**
381 * Returns payload object
382 * @returns any
383 */
384 parsePayload() {
385 if (!this.token) {
386 throw new NbAuthTokenNotFoundError('Token not found. ');
387 }
388 this.payload = decodeJwtPayload(this.token);
389 }
390 /**
391 * Returns expiration date
392 * @returns Date
393 */
394 getTokenExpDate() {
395 const decoded = this.getPayload();
396 if (decoded && !decoded.hasOwnProperty('exp')) {
397 return null;
398 }
399 const date = new Date(0);
400 date.setUTCSeconds(decoded.exp); // 'cause jwt token are set in seconds
401 return date;
402 }
403 /**
404 * Is data expired
405 * @returns {boolean}
406 */
407 isValid() {
408 return super.isValid() && (!this.getTokenExpDate() || new Date() < this.getTokenExpDate());
409 }
410}
411NbAuthJWTToken.NAME = 'nb:auth:jwt:token';
412const prepareOAuth2Token = (data) => {
413 if (typeof data === 'string') {
414 try {
415 return JSON.parse(data);
416 }
417 catch (e) { }
418 }
419 return data;
420};
421/**
422 * Wrapper for OAuth2 token whose access_token is a JWT Token
423 */
424class NbAuthOAuth2Token extends NbAuthSimpleToken {
425 constructor(data = {}, ownerStrategyName, createdAt) {
426 // we may get it as string when retrieving from a storage
427 super(prepareOAuth2Token(data), ownerStrategyName, createdAt);
428 }
429 /**
430 * Returns the token value
431 * @returns string
432 */
433 getValue() {
434 return this.token.access_token;
435 }
436 /**
437 * Returns the refresh token
438 * @returns string
439 */
440 getRefreshToken() {
441 return this.token.refresh_token;
442 }
443 /**
444 * put refreshToken in the token payload
445 * @param refreshToken
446 */
447 setRefreshToken(refreshToken) {
448 this.token.refresh_token = refreshToken;
449 }
450 /**
451 * Parses token payload
452 * @returns any
453 */
454 parsePayload() {
455 if (!this.token) {
456 throw new NbAuthTokenNotFoundError('Token not found.');
457 }
458 else {
459 if (!Object.keys(this.token).length) {
460 throw new NbAuthEmptyTokenError('Cannot extract payload from an empty token.');
461 }
462 }
463 this.payload = this.token;
464 }
465 /**
466 * Returns the token type
467 * @returns string
468 */
469 getType() {
470 return this.token.token_type;
471 }
472 /**
473 * Is data expired
474 * @returns {boolean}
475 */
476 isValid() {
477 return super.isValid() && (!this.getTokenExpDate() || new Date() < this.getTokenExpDate());
478 }
479 /**
480 * Returns expiration date
481 * @returns Date
482 */
483 getTokenExpDate() {
484 if (!this.token.hasOwnProperty('expires_in')) {
485 return null;
486 }
487 return new Date(this.createdAt.getTime() + Number(this.token.expires_in) * 1000);
488 }
489 /**
490 * Convert to string
491 * @returns {string}
492 */
493 toString() {
494 return JSON.stringify(this.token);
495 }
496}
497NbAuthOAuth2Token.NAME = 'nb:auth:oauth2:token';
498/**
499 * Wrapper for OAuth2 token embedding JWT tokens
500 */
501class NbAuthOAuth2JWTToken extends NbAuthOAuth2Token {
502 parsePayload() {
503 super.parsePayload();
504 this.parseAccessTokenPayload();
505 }
506 parseAccessTokenPayload() {
507 const accessToken = this.getValue();
508 if (!accessToken) {
509 throw new NbAuthTokenNotFoundError('access_token key not found.');
510 }
511 this.accessTokenPayload = decodeJwtPayload(accessToken);
512 }
513 /**
514 * Returns access token payload
515 * @returns any
516 */
517 getAccessTokenPayload() {
518 return this.accessTokenPayload;
519 }
520 /**
521 * for Oauth2 JWT token, the iat (issued at) field of the access_token payload
522 */
523 prepareCreatedAt(date) {
524 const payload = this.accessTokenPayload;
525 return payload && payload.iat ? new Date(Number(payload.iat) * 1000) : super.prepareCreatedAt(date);
526 }
527 /**
528 * Is token valid
529 * @returns {boolean}
530 */
531 isValid() {
532 return this.accessTokenPayload && super.isValid();
533 }
534 /**
535 * Returns expiration date :
536 * - exp if set,
537 * - super.getExpDate() otherwise
538 * @returns Date
539 */
540 getTokenExpDate() {
541 if (this.accessTokenPayload && this.accessTokenPayload.hasOwnProperty('exp')) {
542 const date = new Date(0);
543 date.setUTCSeconds(this.accessTokenPayload.exp);
544 return date;
545 }
546 else {
547 return super.getTokenExpDate();
548 }
549 }
550}
551NbAuthOAuth2JWTToken.NAME = 'nb:auth:oauth2:jwt:token';
552
553const NB_AUTH_FALLBACK_TOKEN = new InjectionToken('Nebular Auth Options');
554/**
555 * Creates a token parcel which could be stored/restored
556 */
557class NbAuthTokenParceler {
558 constructor(fallbackClass, tokenClasses) {
559 this.fallbackClass = fallbackClass;
560 this.tokenClasses = tokenClasses;
561 }
562 wrap(token) {
563 return JSON.stringify({
564 name: token.getName(),
565 ownerStrategyName: token.getOwnerStrategyName(),
566 createdAt: token.getCreatedAt().getTime(),
567 value: token.toString(),
568 });
569 }
570 unwrap(value) {
571 let tokenClass = this.fallbackClass;
572 let tokenValue = '';
573 let tokenOwnerStrategyName = '';
574 let tokenCreatedAt = null;
575 const tokenPack = this.parseTokenPack(value);
576 if (tokenPack) {
577 tokenClass = this.getClassByName(tokenPack.name) || this.fallbackClass;
578 tokenValue = tokenPack.value;
579 tokenOwnerStrategyName = tokenPack.ownerStrategyName;
580 tokenCreatedAt = new Date(Number(tokenPack.createdAt));
581 }
582 return nbAuthCreateToken(tokenClass, tokenValue, tokenOwnerStrategyName, tokenCreatedAt);
583 }
584 // TODO: this could be moved to a separate token registry
585 getClassByName(name) {
586 return this.tokenClasses.find((tokenClass) => tokenClass.NAME === name);
587 }
588 parseTokenPack(value) {
589 try {
590 return JSON.parse(value);
591 }
592 catch (e) { }
593 return null;
594 }
595}
596NbAuthTokenParceler.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthTokenParceler, deps: [{ token: NB_AUTH_FALLBACK_TOKEN }, { token: NB_AUTH_TOKENS }], target: i0.ɵɵFactoryTarget.Injectable });
597NbAuthTokenParceler.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthTokenParceler });
598i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthTokenParceler, decorators: [{
599 type: Injectable
600 }], ctorParameters: function () {
601 return [{ type: undefined, decorators: [{
602 type: Inject,
603 args: [NB_AUTH_FALLBACK_TOKEN]
604 }] }, { type: undefined, decorators: [{
605 type: Inject,
606 args: [NB_AUTH_TOKENS]
607 }] }];
608 } });
609
610class NbTokenStorage {
611}
612/**
613 * Service that uses browser localStorage as a storage.
614 *
615 * The token storage is provided into auth module the following way:
616 * ```ts
617 * { provide: NbTokenStorage, useClass: NbTokenLocalStorage },
618 * ```
619 *
620 * If you need to change the storage behaviour or provide your own - just extend your class from basic `NbTokenStorage`
621 * or `NbTokenLocalStorage` and provide in your `app.module`:
622 * ```ts
623 * { provide: NbTokenStorage, useClass: NbTokenCustomStorage },
624 * ```
625 *
626 */
627class NbTokenLocalStorage extends NbTokenStorage {
628 constructor(parceler) {
629 super();
630 this.parceler = parceler;
631 this.key = 'auth_app_token';
632 }
633 /**
634 * Returns token from localStorage
635 * @returns {NbAuthToken}
636 */
637 get() {
638 const raw = localStorage.getItem(this.key);
639 return this.parceler.unwrap(raw);
640 }
641 /**
642 * Sets token to localStorage
643 * @param {NbAuthToken} token
644 */
645 set(token) {
646 const raw = this.parceler.wrap(token);
647 localStorage.setItem(this.key, raw);
648 }
649 /**
650 * Clears token from localStorage
651 */
652 clear() {
653 localStorage.removeItem(this.key);
654 }
655}
656NbTokenLocalStorage.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbTokenLocalStorage, deps: [{ token: NbAuthTokenParceler }], target: i0.ɵɵFactoryTarget.Injectable });
657NbTokenLocalStorage.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbTokenLocalStorage });
658i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbTokenLocalStorage, decorators: [{
659 type: Injectable
660 }], ctorParameters: function () { return [{ type: NbAuthTokenParceler }]; } });
661
662/**
663 * Service that allows you to manage authentication token - get, set, clear and also listen to token changes over time.
664 */
665class NbTokenService {
666 constructor(tokenStorage) {
667 this.tokenStorage = tokenStorage;
668 this.token$ = new BehaviorSubject(null);
669 this.publishStoredToken();
670 }
671 /**
672 * Publishes token when it changes.
673 * @returns {Observable<NbAuthToken>}
674 */
675 tokenChange() {
676 return this.token$
677 .pipe(filter(value => !!value), share());
678 }
679 /**
680 * Sets a token into the storage. This method is used by the NbAuthService automatically.
681 *
682 * @param {NbAuthToken} token
683 * @returns {Observable<any>}
684 */
685 set(token) {
686 this.tokenStorage.set(token);
687 this.publishStoredToken();
688 return of(null);
689 }
690 /**
691 * Returns observable of current token
692 * @returns {Observable<NbAuthToken>}
693 */
694 get() {
695 const token = this.tokenStorage.get();
696 return of(token);
697 }
698 /**
699 * Removes the token and published token value
700 *
701 * @returns {Observable<any>}
702 */
703 clear() {
704 this.tokenStorage.clear();
705 this.publishStoredToken();
706 return of(null);
707 }
708 publishStoredToken() {
709 this.token$.next(this.tokenStorage.get());
710 }
711}
712NbTokenService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbTokenService, deps: [{ token: NbTokenStorage }], target: i0.ɵɵFactoryTarget.Injectable });
713NbTokenService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbTokenService });
714i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbTokenService, decorators: [{
715 type: Injectable
716 }], ctorParameters: function () { return [{ type: NbTokenStorage }]; } });
717
718/**
719 * @license
720 * Copyright Akveo. All Rights Reserved.
721 * Licensed under the MIT License. See License.txt in the project root for license information.
722 */
723/**
724 * Common authentication service.
725 * Should be used to as an interlayer between UI Components and Auth Strategy.
726 */
727class NbAuthService {
728 constructor(tokenService, strategies) {
729 this.tokenService = tokenService;
730 this.strategies = strategies;
731 }
732 /**
733 * Retrieves current authenticated token stored
734 * @returns {Observable<any>}
735 */
736 getToken() {
737 return this.tokenService.get();
738 }
739 /**
740 * Returns true if auth token is present in the token storage
741 * @returns {Observable<boolean>}
742 */
743 isAuthenticated() {
744 return this.getToken()
745 .pipe(map((token) => token.isValid()));
746 }
747 /**
748 * Returns true if valid auth token is present in the token storage.
749 * If not, calls the strategy refreshToken, and returns isAuthenticated() if success, false otherwise
750 * @returns {Observable<boolean>}
751 */
752 isAuthenticatedOrRefresh() {
753 return this.getToken()
754 .pipe(switchMap(token => {
755 if (token.getValue() && !token.isValid()) {
756 return this.refreshToken(token.getOwnerStrategyName(), token)
757 .pipe(switchMap(res => {
758 if (res.isSuccess()) {
759 return this.isAuthenticated();
760 }
761 else {
762 return of(false);
763 }
764 }));
765 }
766 else {
767 return of(token.isValid());
768 }
769 }));
770 }
771 /**
772 * Returns tokens stream
773 * @returns {Observable<NbAuthSimpleToken>}
774 */
775 onTokenChange() {
776 return this.tokenService.tokenChange();
777 }
778 /**
779 * Returns authentication status stream
780 * @returns {Observable<boolean>}
781 */
782 onAuthenticationChange() {
783 return this.onTokenChange()
784 .pipe(map((token) => token.isValid()));
785 }
786 /**
787 * Authenticates with the selected strategy
788 * Stores received token in the token storage
789 *
790 * Example:
791 * authenticate('email', {email: 'email@example.com', password: 'test'})
792 *
793 * @param strategyName
794 * @param data
795 * @returns {Observable<NbAuthResult>}
796 */
797 authenticate(strategyName, data) {
798 return this.getStrategy(strategyName).authenticate(data)
799 .pipe(switchMap((result) => {
800 return this.processResultToken(result);
801 }));
802 }
803 /**
804 * Registers with the selected strategy
805 * Stores received token in the token storage
806 *
807 * Example:
808 * register('email', {email: 'email@example.com', name: 'Some Name', password: 'test'})
809 *
810 * @param strategyName
811 * @param data
812 * @returns {Observable<NbAuthResult>}
813 */
814 register(strategyName, data) {
815 return this.getStrategy(strategyName).register(data)
816 .pipe(switchMap((result) => {
817 return this.processResultToken(result);
818 }));
819 }
820 /**
821 * Sign outs with the selected strategy
822 * Removes token from the token storage
823 *
824 * Example:
825 * logout('email')
826 *
827 * @param strategyName
828 * @returns {Observable<NbAuthResult>}
829 */
830 logout(strategyName) {
831 return this.getStrategy(strategyName).logout()
832 .pipe(switchMap((result) => {
833 if (result.isSuccess()) {
834 this.tokenService.clear()
835 .pipe(map(() => result));
836 }
837 return of(result);
838 }));
839 }
840 /**
841 * Sends forgot password request to the selected strategy
842 *
843 * Example:
844 * requestPassword('email', {email: 'email@example.com'})
845 *
846 * @param strategyName
847 * @param data
848 * @returns {Observable<NbAuthResult>}
849 */
850 requestPassword(strategyName, data) {
851 return this.getStrategy(strategyName).requestPassword(data);
852 }
853 /**
854 * Tries to reset password with the selected strategy
855 *
856 * Example:
857 * resetPassword('email', {newPassword: 'test'})
858 *
859 * @param strategyName
860 * @param data
861 * @returns {Observable<NbAuthResult>}
862 */
863 resetPassword(strategyName, data) {
864 return this.getStrategy(strategyName).resetPassword(data);
865 }
866 /**
867 * Sends a refresh token request
868 * Stores received token in the token storage
869 *
870 * Example:
871 * refreshToken('email', {token: token})
872 *
873 * @param {string} strategyName
874 * @param data
875 * @returns {Observable<NbAuthResult>}
876 */
877 refreshToken(strategyName, data) {
878 return this.getStrategy(strategyName).refreshToken(data)
879 .pipe(switchMap((result) => {
880 return this.processResultToken(result);
881 }));
882 }
883 /**
884 * Get registered strategy by name
885 *
886 * Example:
887 * getStrategy('email')
888 *
889 * @param {string} provider
890 * @returns {NbAbstractAuthProvider}
891 */
892 getStrategy(strategyName) {
893 const found = this.strategies.find((strategy) => strategy.getName() === strategyName);
894 if (!found) {
895 throw new TypeError(`There is no Auth Strategy registered under '${strategyName}' name`);
896 }
897 return found;
898 }
899 processResultToken(result) {
900 if (result.isSuccess() && result.getToken()) {
901 return this.tokenService.set(result.getToken())
902 .pipe(map((token) => {
903 return result;
904 }));
905 }
906 return of(result);
907 }
908}
909NbAuthService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthService, deps: [{ token: NbTokenService }, { token: NB_AUTH_STRATEGIES }], target: i0.ɵɵFactoryTarget.Injectable });
910NbAuthService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthService });
911i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthService, decorators: [{
912 type: Injectable
913 }], ctorParameters: function () {
914 return [{ type: NbTokenService }, { type: undefined, decorators: [{
915 type: Inject,
916 args: [NB_AUTH_STRATEGIES]
917 }] }];
918 } });
919
920class NbAuthStrategy {
921 // we should keep this any and validation should be done in `register` method instead
922 // otherwise it won't be possible to pass an empty object
923 setOptions(options) {
924 this.options = deepExtend({}, this.defaultOptions, options);
925 }
926 getOption(key) {
927 return getDeepFromObject(this.options, key, null);
928 }
929 createToken(value, failWhenInvalidToken) {
930 const token = nbAuthCreateToken(this.getOption('token.class'), value, this.getName());
931 // At this point, nbAuthCreateToken failed with NbAuthIllegalTokenError which MUST be intercepted by strategies
932 // Or token is created. It MAY be created even if backend did not return any token, in this case it is !Valid
933 if (failWhenInvalidToken && !token.isValid()) {
934 // If we require a valid token (i.e. isValid), then we MUST throw NbAuthIllegalTokenError so that the strategies
935 // intercept it
936 throw new NbAuthIllegalTokenError('Token is empty or invalid.');
937 }
938 return token;
939 }
940 getName() {
941 return this.getOption('name');
942 }
943 createFailResponse(data) {
944 return new HttpResponse({ body: {}, status: 401 });
945 }
946 createSuccessResponse(data) {
947 return new HttpResponse({ body: {}, status: 200 });
948 }
949 getActionEndpoint(action) {
950 const actionEndpoint = this.getOption(`${action}.endpoint`);
951 const baseEndpoint = this.getOption('baseEndpoint');
952 return actionEndpoint ? baseEndpoint + actionEndpoint : '';
953 }
954 getHeaders() {
955 var _a;
956 const customHeaders = (_a = this.getOption('headers')) !== null && _a !== void 0 ? _a : {};
957 if (customHeaders instanceof HttpHeaders) {
958 return customHeaders;
959 }
960 let headers = new HttpHeaders();
961 Object.entries(customHeaders).forEach(([key, value]) => {
962 headers = headers.append(key, value);
963 });
964 return headers;
965 }
966}
967
968class NbAuthResult {
969 // TODO: better pass object
970 constructor(success, response, redirect, errors, messages, token = null) {
971 this.success = success;
972 this.response = response;
973 this.redirect = redirect;
974 this.errors = [];
975 this.messages = [];
976 this.errors = this.errors.concat([errors]);
977 if (errors instanceof Array) {
978 this.errors = errors;
979 }
980 this.messages = this.messages.concat([messages]);
981 if (messages instanceof Array) {
982 this.messages = messages;
983 }
984 this.token = token;
985 }
986 getResponse() {
987 return this.response;
988 }
989 getToken() {
990 return this.token;
991 }
992 getRedirect() {
993 return this.redirect;
994 }
995 getErrors() {
996 return this.errors.filter(val => !!val);
997 }
998 getMessages() {
999 return this.messages.filter(val => !!val);
1000 }
1001 isSuccess() {
1002 return this.success;
1003 }
1004 isFailure() {
1005 return !this.success;
1006 }
1007}
1008
1009class NbAuthStrategyOptions {
1010}
1011
1012/**
1013 * @license
1014 * Copyright Akveo. All Rights Reserved.
1015 * Licensed under the MIT License. See License.txt in the project root for license information.
1016 */
1017class NbDummyAuthStrategyOptions extends NbAuthStrategyOptions {
1018 constructor() {
1019 super(...arguments);
1020 this.token = {
1021 class: NbAuthSimpleToken,
1022 };
1023 this.delay = 1000;
1024 this.alwaysFail = false;
1025 }
1026}
1027const dummyStrategyOptions = new NbDummyAuthStrategyOptions();
1028
1029/**
1030 * Dummy auth strategy. Could be useful for auth setup when backend is not available yet.
1031 *
1032 *
1033 * Strategy settings.
1034 *
1035 * ```ts
1036 * export class NbDummyAuthStrategyOptions extends NbAuthStrategyOptions {
1037 * name = 'dummy';
1038 * token = {
1039 * class: NbAuthSimpleToken,
1040 * };
1041 * delay? = 1000;
1042 * alwaysFail? = false;
1043 * }
1044 * ```
1045 */
1046class NbDummyAuthStrategy extends NbAuthStrategy {
1047 constructor() {
1048 super(...arguments);
1049 this.defaultOptions = dummyStrategyOptions;
1050 }
1051 static setup(options) {
1052 return [NbDummyAuthStrategy, options];
1053 }
1054 authenticate(data) {
1055 return of(this.createDummyResult(data)).pipe(delay(this.getOption('delay')));
1056 }
1057 register(data) {
1058 return of(this.createDummyResult(data)).pipe(delay(this.getOption('delay')));
1059 }
1060 requestPassword(data) {
1061 return of(this.createDummyResult(data)).pipe(delay(this.getOption('delay')));
1062 }
1063 resetPassword(data) {
1064 return of(this.createDummyResult(data)).pipe(delay(this.getOption('delay')));
1065 }
1066 logout(data) {
1067 return of(this.createDummyResult(data)).pipe(delay(this.getOption('delay')));
1068 }
1069 refreshToken(data) {
1070 return of(this.createDummyResult(data)).pipe(delay(this.getOption('delay')));
1071 }
1072 createDummyResult(data) {
1073 if (this.getOption('alwaysFail')) {
1074 return new NbAuthResult(false, this.createFailResponse(data), null, ['Something went wrong.']);
1075 }
1076 try {
1077 const token = this.createToken('test token', true);
1078 return new NbAuthResult(true, this.createSuccessResponse(data), '/', [], ['Successfully logged in.'], token);
1079 }
1080 catch (err) {
1081 return new NbAuthResult(false, this.createFailResponse(data), null, [err.message]);
1082 }
1083 }
1084}
1085NbDummyAuthStrategy.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbDummyAuthStrategy, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
1086NbDummyAuthStrategy.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbDummyAuthStrategy });
1087i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbDummyAuthStrategy, decorators: [{
1088 type: Injectable
1089 }] });
1090
1091/**
1092 * @license
1093 * Copyright Akveo. All Rights Reserved.
1094 * Licensed under the MIT License. See License.txt in the project root for license information.
1095 */
1096var NbOAuth2ResponseType;
1097(function (NbOAuth2ResponseType) {
1098 NbOAuth2ResponseType["CODE"] = "code";
1099 NbOAuth2ResponseType["TOKEN"] = "token";
1100})(NbOAuth2ResponseType || (NbOAuth2ResponseType = {}));
1101// TODO: client_credentials
1102var NbOAuth2GrantType;
1103(function (NbOAuth2GrantType) {
1104 NbOAuth2GrantType["AUTHORIZATION_CODE"] = "authorization_code";
1105 NbOAuth2GrantType["PASSWORD"] = "password";
1106 NbOAuth2GrantType["REFRESH_TOKEN"] = "refresh_token";
1107})(NbOAuth2GrantType || (NbOAuth2GrantType = {}));
1108var NbOAuth2ClientAuthMethod;
1109(function (NbOAuth2ClientAuthMethod) {
1110 NbOAuth2ClientAuthMethod["NONE"] = "none";
1111 NbOAuth2ClientAuthMethod["BASIC"] = "basic";
1112 NbOAuth2ClientAuthMethod["REQUEST_BODY"] = "request-body";
1113})(NbOAuth2ClientAuthMethod || (NbOAuth2ClientAuthMethod = {}));
1114class NbOAuth2AuthStrategyOptions extends NbAuthStrategyOptions {
1115 constructor() {
1116 super(...arguments);
1117 this.baseEndpoint = '';
1118 this.clientId = '';
1119 this.clientSecret = '';
1120 this.clientAuthMethod = NbOAuth2ClientAuthMethod.NONE;
1121 this.redirect = {
1122 success: '/',
1123 failure: null,
1124 };
1125 this.defaultErrors = ['Something went wrong, please try again.'];
1126 this.defaultMessages = ['You have been successfully authenticated.'];
1127 this.authorize = {
1128 endpoint: 'authorize',
1129 responseType: NbOAuth2ResponseType.CODE,
1130 requireValidToken: true,
1131 };
1132 this.token = {
1133 endpoint: 'token',
1134 grantType: NbOAuth2GrantType.AUTHORIZATION_CODE,
1135 requireValidToken: true,
1136 class: NbAuthOAuth2Token,
1137 };
1138 this.refresh = {
1139 endpoint: 'token',
1140 grantType: NbOAuth2GrantType.REFRESH_TOKEN,
1141 requireValidToken: true,
1142 };
1143 }
1144}
1145const auth2StrategyOptions = new NbOAuth2AuthStrategyOptions();
1146
1147/**
1148 * @license
1149 * Copyright Akveo. All Rights Reserved.
1150 * Licensed under the MIT License. See License.txt in the project root for license information.
1151 */
1152/**
1153 * OAuth2 authentication strategy.
1154 *
1155 * Strategy settings:
1156 *
1157 * ```ts
1158 * export enum NbOAuth2ResponseType {
1159 * CODE = 'code',
1160 * TOKEN = 'token',
1161 * }
1162 *
1163 * export enum NbOAuth2GrantType {
1164 * AUTHORIZATION_CODE = 'authorization_code',
1165 * PASSWORD = 'password',
1166 * REFRESH_TOKEN = 'refresh_token',
1167 * }
1168 *
1169 * export class NbOAuth2AuthStrategyOptions {
1170 * name: string;
1171 * baseEndpoint?: string = '';
1172 * clientId: string = '';
1173 * clientSecret: string = '';
1174 * clientAuthMethod: string = NbOAuth2ClientAuthMethod.NONE;
1175 * redirect?: { success?: string; failure?: string } = {
1176 * success: '/',
1177 * failure: null,
1178 * };
1179 * defaultErrors?: any[] = ['Something went wrong, please try again.'];
1180 * defaultMessages?: any[] = ['You have been successfully authenticated.'];
1181 * authorize?: {
1182 * endpoint?: string;
1183 * redirectUri?: string;
1184 * responseType?: string;
1185 * requireValidToken: true,
1186 * scope?: string;
1187 * state?: string;
1188 * params?: { [key: string]: string };
1189 * } = {
1190 * endpoint: 'authorize',
1191 * responseType: NbOAuth2ResponseType.CODE,
1192 * };
1193 * token?: {
1194 * endpoint?: string;
1195 * grantType?: string;
1196 * requireValidToken: true,
1197 * redirectUri?: string;
1198 * scope?: string;
1199 * class: NbAuthTokenClass,
1200 * } = {
1201 * endpoint: 'token',
1202 * grantType: NbOAuth2GrantType.AUTHORIZATION_CODE,
1203 * class: NbAuthOAuth2Token,
1204 * };
1205 * refresh?: {
1206 * endpoint?: string;
1207 * grantType?: string;
1208 * scope?: string;
1209 * requireValidToken: true,
1210 * } = {
1211 * endpoint: 'token',
1212 * grantType: NbOAuth2GrantType.REFRESH_TOKEN,
1213 * };
1214 * }
1215 * ```
1216 *
1217 */
1218class NbOAuth2AuthStrategy extends NbAuthStrategy {
1219 constructor(http, route, window) {
1220 super();
1221 this.http = http;
1222 this.route = route;
1223 this.window = window;
1224 this.redirectResultHandlers = {
1225 [NbOAuth2ResponseType.CODE]: () => {
1226 return of(this.route.snapshot.queryParams).pipe(switchMap((params) => {
1227 if (params.code) {
1228 return this.requestToken(params.code);
1229 }
1230 return of(new NbAuthResult(false, params, this.getOption('redirect.failure'), this.getOption('defaultErrors'), []));
1231 }));
1232 },
1233 [NbOAuth2ResponseType.TOKEN]: () => {
1234 const module = 'authorize';
1235 const requireValidToken = this.getOption(`${module}.requireValidToken`);
1236 return of(this.route.snapshot.fragment).pipe(map((fragment) => this.parseHashAsQueryParams(fragment)), map((params) => {
1237 if (!params.error) {
1238 return new NbAuthResult(true, params, this.getOption('redirect.success'), [], this.getOption('defaultMessages'), this.createToken(params, requireValidToken));
1239 }
1240 return new NbAuthResult(false, params, this.getOption('redirect.failure'), this.getOption('defaultErrors'), []);
1241 }), catchError((err) => {
1242 const errors = [];
1243 if (err instanceof NbAuthIllegalTokenError) {
1244 errors.push(err.message);
1245 }
1246 else {
1247 errors.push('Something went wrong.');
1248 }
1249 return of(new NbAuthResult(false, err, this.getOption('redirect.failure'), errors));
1250 }));
1251 },
1252 };
1253 this.redirectResults = {
1254 [NbOAuth2ResponseType.CODE]: () => {
1255 return of(this.route.snapshot.queryParams).pipe(map((params) => !!(params && (params.code || params.error))));
1256 },
1257 [NbOAuth2ResponseType.TOKEN]: () => {
1258 return of(this.route.snapshot.fragment).pipe(map((fragment) => this.parseHashAsQueryParams(fragment)), map((params) => !!(params && (params.access_token || params.error))));
1259 },
1260 };
1261 this.defaultOptions = auth2StrategyOptions;
1262 }
1263 static setup(options) {
1264 return [NbOAuth2AuthStrategy, options];
1265 }
1266 get responseType() {
1267 return this.getOption('authorize.responseType');
1268 }
1269 get clientAuthMethod() {
1270 return this.getOption('clientAuthMethod');
1271 }
1272 authenticate(data) {
1273 if (this.getOption('token.grantType') === NbOAuth2GrantType.PASSWORD) {
1274 return this.passwordToken(data.email, data.password);
1275 }
1276 else {
1277 return this.isRedirectResult().pipe(switchMap((result) => {
1278 if (!result) {
1279 this.authorizeRedirect();
1280 return of(new NbAuthResult(true));
1281 }
1282 return this.getAuthorizationResult();
1283 }));
1284 }
1285 }
1286 getAuthorizationResult() {
1287 const redirectResultHandler = this.redirectResultHandlers[this.responseType];
1288 if (redirectResultHandler) {
1289 return redirectResultHandler.call(this);
1290 }
1291 throw new Error(`'${this.responseType}' responseType is not supported,
1292 only 'token' and 'code' are supported now`);
1293 }
1294 refreshToken(token) {
1295 const module = 'refresh';
1296 const url = this.getActionEndpoint(module);
1297 const requireValidToken = this.getOption(`${module}.requireValidToken`);
1298 return this.http.post(url, this.buildRefreshRequestData(token), { headers: this.getHeaders() }).pipe(map((res) => {
1299 return new NbAuthResult(true, res, this.getOption('redirect.success'), [], this.getOption('defaultMessages'), this.createRefreshedToken(res, token, requireValidToken));
1300 }), catchError((res) => this.handleResponseError(res)));
1301 }
1302 passwordToken(username, password) {
1303 const module = 'token';
1304 const url = this.getActionEndpoint(module);
1305 const requireValidToken = this.getOption(`${module}.requireValidToken`);
1306 return this.http.post(url, this.buildPasswordRequestData(username, password), { headers: this.getHeaders() }).pipe(map((res) => {
1307 return new NbAuthResult(true, res, this.getOption('redirect.success'), [], this.getOption('defaultMessages'), this.createToken(res, requireValidToken));
1308 }), catchError((res) => this.handleResponseError(res)));
1309 }
1310 authorizeRedirect() {
1311 this.window.location.href = this.buildRedirectUrl();
1312 }
1313 isRedirectResult() {
1314 return this.redirectResults[this.responseType].call(this);
1315 }
1316 requestToken(code) {
1317 const module = 'token';
1318 const url = this.getActionEndpoint(module);
1319 const requireValidToken = this.getOption(`${module}.requireValidToken`);
1320 return this.http.post(url, this.buildCodeRequestData(code), { headers: this.getHeaders() }).pipe(map((res) => {
1321 return new NbAuthResult(true, res, this.getOption('redirect.success'), [], this.getOption('defaultMessages'), this.createToken(res, requireValidToken));
1322 }), catchError((res) => this.handleResponseError(res)));
1323 }
1324 buildCodeRequestData(code) {
1325 const params = {
1326 grant_type: this.getOption('token.grantType'),
1327 code: code,
1328 redirect_uri: this.getOption('token.redirectUri'),
1329 client_id: this.getOption('clientId'),
1330 };
1331 return this.urlEncodeParameters(this.cleanParams(this.addCredentialsToParams(params)));
1332 }
1333 buildRefreshRequestData(token) {
1334 const params = {
1335 grant_type: this.getOption('refresh.grantType'),
1336 refresh_token: token.getRefreshToken(),
1337 scope: this.getOption('refresh.scope'),
1338 client_id: this.getOption('clientId'),
1339 };
1340 return this.urlEncodeParameters(this.cleanParams(this.addCredentialsToParams(params)));
1341 }
1342 buildPasswordRequestData(username, password) {
1343 const params = {
1344 grant_type: this.getOption('token.grantType'),
1345 username: username,
1346 password: password,
1347 scope: this.getOption('token.scope'),
1348 };
1349 return this.urlEncodeParameters(this.cleanParams(this.addCredentialsToParams(params)));
1350 }
1351 buildAuthHeader() {
1352 if (this.clientAuthMethod === NbOAuth2ClientAuthMethod.BASIC) {
1353 if (this.getOption('clientId') && this.getOption('clientSecret')) {
1354 return new HttpHeaders({
1355 Authorization: 'Basic ' + btoa(this.getOption('clientId') + ':' + this.getOption('clientSecret')),
1356 });
1357 }
1358 else {
1359 throw Error('For basic client authentication method, please provide both clientId & clientSecret.');
1360 }
1361 }
1362 return undefined;
1363 }
1364 getHeaders() {
1365 let headers = super.getHeaders();
1366 headers = headers.append('Content-Type', 'application/x-www-form-urlencoded');
1367 const authHeaders = this.buildAuthHeader();
1368 if (authHeaders === undefined) {
1369 return headers;
1370 }
1371 for (const headerKey of authHeaders.keys()) {
1372 for (const headerValue of authHeaders.getAll(headerKey)) {
1373 headers = headers.append(headerKey, headerValue);
1374 }
1375 }
1376 return headers;
1377 }
1378 cleanParams(params) {
1379 Object.entries(params).forEach(([key, val]) => !val && delete params[key]);
1380 return params;
1381 }
1382 addCredentialsToParams(params) {
1383 if (this.clientAuthMethod === NbOAuth2ClientAuthMethod.REQUEST_BODY) {
1384 if (this.getOption('clientId') && this.getOption('clientSecret')) {
1385 return Object.assign(Object.assign({}, params), { client_id: this.getOption('clientId'), client_secret: this.getOption('clientSecret') });
1386 }
1387 else {
1388 throw Error('For request body client authentication method, please provide both clientId & clientSecret.');
1389 }
1390 }
1391 return params;
1392 }
1393 handleResponseError(res) {
1394 let errors = [];
1395 if (res instanceof HttpErrorResponse) {
1396 if (res.error.error_description) {
1397 errors.push(res.error.error_description);
1398 }
1399 else {
1400 errors = this.getOption('defaultErrors');
1401 }
1402 }
1403 else if (res instanceof NbAuthIllegalTokenError) {
1404 errors.push(res.message);
1405 }
1406 else {
1407 errors.push('Something went wrong.');
1408 }
1409 return of(new NbAuthResult(false, res, this.getOption('redirect.failure'), errors, []));
1410 }
1411 buildRedirectUrl() {
1412 const params = Object.assign({ response_type: this.getOption('authorize.responseType'), client_id: this.getOption('clientId'), redirect_uri: this.getOption('authorize.redirectUri'), scope: this.getOption('authorize.scope'), state: this.getOption('authorize.state') }, this.getOption('authorize.params'));
1413 const endpoint = this.getActionEndpoint('authorize');
1414 const query = this.urlEncodeParameters(this.cleanParams(params));
1415 return `${endpoint}?${query}`;
1416 }
1417 parseHashAsQueryParams(hash) {
1418 return hash
1419 ? hash.split('&').reduce((acc, part) => {
1420 const item = part.split('=');
1421 acc[item[0]] = decodeURIComponent(item[1]);
1422 return acc;
1423 }, {})
1424 : {};
1425 }
1426 urlEncodeParameters(params) {
1427 return Object.keys(params)
1428 .map((k) => {
1429 return `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`;
1430 })
1431 .join('&');
1432 }
1433 createRefreshedToken(res, existingToken, requireValidToken) {
1434 const refreshedToken = this.createToken(res, requireValidToken);
1435 if (!refreshedToken.getRefreshToken() && existingToken.getRefreshToken()) {
1436 refreshedToken.setRefreshToken(existingToken.getRefreshToken());
1437 }
1438 return refreshedToken;
1439 }
1440 register(data) {
1441 throw new Error('`register` is not supported by `NbOAuth2AuthStrategy`, use `authenticate`.');
1442 }
1443 requestPassword(data) {
1444 throw new Error('`requestPassword` is not supported by `NbOAuth2AuthStrategy`, use `authenticate`.');
1445 }
1446 resetPassword(data = {}) {
1447 throw new Error('`resetPassword` is not supported by `NbOAuth2AuthStrategy`, use `authenticate`.');
1448 }
1449 logout() {
1450 return of(new NbAuthResult(true));
1451 }
1452}
1453NbOAuth2AuthStrategy.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbOAuth2AuthStrategy, deps: [{ token: i1.HttpClient }, { token: i2.ActivatedRoute }, { token: NB_WINDOW }], target: i0.ɵɵFactoryTarget.Injectable });
1454NbOAuth2AuthStrategy.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbOAuth2AuthStrategy });
1455i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbOAuth2AuthStrategy, decorators: [{
1456 type: Injectable
1457 }], ctorParameters: function () {
1458 return [{ type: i1.HttpClient }, { type: i2.ActivatedRoute }, { type: undefined, decorators: [{
1459 type: Inject,
1460 args: [NB_WINDOW]
1461 }] }];
1462 } });
1463
1464/**
1465 * @license
1466 * Copyright Akveo. All Rights Reserved.
1467 * Licensed under the MIT License. See License.txt in the project root for license information.
1468 */
1469class NbPasswordAuthStrategyOptions extends NbAuthStrategyOptions {
1470 constructor() {
1471 super(...arguments);
1472 this.baseEndpoint = '/api/auth/';
1473 this.login = {
1474 alwaysFail: false,
1475 endpoint: 'login',
1476 method: 'post',
1477 requireValidToken: true,
1478 redirect: {
1479 success: '/',
1480 failure: null,
1481 },
1482 defaultErrors: ['Login/Email combination is not correct, please try again.'],
1483 defaultMessages: ['You have been successfully logged in.'],
1484 };
1485 this.register = {
1486 alwaysFail: false,
1487 endpoint: 'register',
1488 method: 'post',
1489 requireValidToken: true,
1490 redirect: {
1491 success: '/',
1492 failure: null,
1493 },
1494 defaultErrors: ['Something went wrong, please try again.'],
1495 defaultMessages: ['You have been successfully registered.'],
1496 };
1497 this.requestPass = {
1498 endpoint: 'request-pass',
1499 method: 'post',
1500 redirect: {
1501 success: '/',
1502 failure: null,
1503 },
1504 defaultErrors: ['Something went wrong, please try again.'],
1505 defaultMessages: ['Reset password instructions have been sent to your email.'],
1506 };
1507 this.resetPass = {
1508 endpoint: 'reset-pass',
1509 method: 'put',
1510 redirect: {
1511 success: '/',
1512 failure: null,
1513 },
1514 resetPasswordTokenKey: 'reset_password_token',
1515 defaultErrors: ['Something went wrong, please try again.'],
1516 defaultMessages: ['Your password has been successfully changed.'],
1517 };
1518 this.logout = {
1519 alwaysFail: false,
1520 endpoint: 'logout',
1521 method: 'delete',
1522 redirect: {
1523 success: '/',
1524 failure: null,
1525 },
1526 defaultErrors: ['Something went wrong, please try again.'],
1527 defaultMessages: ['You have been successfully logged out.'],
1528 };
1529 this.refreshToken = {
1530 endpoint: 'refresh-token',
1531 method: 'post',
1532 requireValidToken: true,
1533 redirect: {
1534 success: null,
1535 failure: null,
1536 },
1537 defaultErrors: ['Something went wrong, please try again.'],
1538 defaultMessages: ['Your token has been successfully refreshed.'],
1539 };
1540 this.token = {
1541 class: NbAuthSimpleToken,
1542 key: 'data.token',
1543 getter: (module, res, options) => getDeepFromObject(res.body, options.token.key),
1544 };
1545 this.errors = {
1546 key: 'data.errors',
1547 getter: (module, res, options) => getDeepFromObject(res.error, options.errors.key, options[module].defaultErrors),
1548 };
1549 this.messages = {
1550 key: 'data.messages',
1551 getter: (module, res, options) => getDeepFromObject(res.body, options.messages.key, options[module].defaultMessages),
1552 };
1553 }
1554}
1555const passwordStrategyOptions = new NbPasswordAuthStrategyOptions();
1556
1557/**
1558 * @license
1559 * Copyright Akveo. All Rights Reserved.
1560 * Licensed under the MIT License. See License.txt in the project root for license information.
1561 */
1562/**
1563 * The most common authentication provider for email/password strategy.
1564 *
1565 * Strategy settings. Note, there is no need to copy over the whole object to change the settings you need.
1566 * Also, this.getOption call won't work outside of the default options declaration
1567 * (which is inside of the `NbPasswordAuthStrategy` class), so you have to replace it with a custom helper function
1568 * if you need it.
1569 *
1570 * ```ts
1571 *export class NbPasswordAuthStrategyOptions extends NbAuthStrategyOptions {
1572 * name: string;
1573 * baseEndpoint? = '/api/auth/';
1574 * login?: boolean | NbPasswordStrategyModule = {
1575 * alwaysFail: false,
1576 * endpoint: 'login',
1577 * method: 'post',
1578 * requireValidToken: true,
1579 * redirect: {
1580 * success: '/',
1581 * failure: null,
1582 * },
1583 * defaultErrors: ['Login/Email combination is not correct, please try again.'],
1584 * defaultMessages: ['You have been successfully logged in.'],
1585 * };
1586 * register?: boolean | NbPasswordStrategyModule = {
1587 * alwaysFail: false,
1588 * endpoint: 'register',
1589 * method: 'post',
1590 * requireValidToken: true,
1591 * redirect: {
1592 * success: '/',
1593 * failure: null,
1594 * },
1595 * defaultErrors: ['Something went wrong, please try again.'],
1596 * defaultMessages: ['You have been successfully registered.'],
1597 * };
1598 * requestPass?: boolean | NbPasswordStrategyModule = {
1599 * endpoint: 'request-pass',
1600 * method: 'post',
1601 * redirect: {
1602 * success: '/',
1603 * failure: null,
1604 * },
1605 * defaultErrors: ['Something went wrong, please try again.'],
1606 * defaultMessages: ['Reset password instructions have been sent to your email.'],
1607 * };
1608 * resetPass?: boolean | NbPasswordStrategyReset = {
1609 * endpoint: 'reset-pass',
1610 * method: 'put',
1611 * redirect: {
1612 * success: '/',
1613 * failure: null,
1614 * },
1615 * resetPasswordTokenKey: 'reset_password_token',
1616 * defaultErrors: ['Something went wrong, please try again.'],
1617 * defaultMessages: ['Your password has been successfully changed.'],
1618 * };
1619 * logout?: boolean | NbPasswordStrategyReset = {
1620 * alwaysFail: false,
1621 * endpoint: 'logout',
1622 * method: 'delete',
1623 * redirect: {
1624 * success: '/',
1625 * failure: null,
1626 * },
1627 * defaultErrors: ['Something went wrong, please try again.'],
1628 * defaultMessages: ['You have been successfully logged out.'],
1629 * };
1630 * refreshToken?: boolean | NbPasswordStrategyModule = {
1631 * endpoint: 'refresh-token',
1632 * method: 'post',
1633 * requireValidToken: true,
1634 * redirect: {
1635 * success: null,
1636 * failure: null,
1637 * },
1638 * defaultErrors: ['Something went wrong, please try again.'],
1639 * defaultMessages: ['Your token has been successfully refreshed.'],
1640 * };
1641 * token?: NbPasswordStrategyToken = {
1642 * class: NbAuthSimpleToken,
1643 * key: 'data.token',
1644 * getter: (module: string, res: HttpResponse<Object>, options: NbPasswordAuthStrategyOptions) => getDeepFromObject(
1645 * res.body,
1646 * options.token.key,
1647 * ),
1648 * };
1649 * errors?: NbPasswordStrategyMessage = {
1650 * key: 'data.errors',
1651 * getter: (module: string, res: HttpErrorResponse, options: NbPasswordAuthStrategyOptions) => getDeepFromObject(
1652 * res.error,
1653 * options.errors.key,
1654 * options[module].defaultErrors,
1655 * ),
1656 * };
1657 * messages?: NbPasswordStrategyMessage = {
1658 * key: 'data.messages',
1659 * getter: (module: string, res: HttpResponse<Object>, options: NbPasswordAuthStrategyOptions) => getDeepFromObject(
1660 * res.body,
1661 * options.messages.key,
1662 * options[module].defaultMessages,
1663 * ),
1664 * };
1665 * validation?: {
1666 * password?: {
1667 * required?: boolean;
1668 * minLength?: number | null;
1669 * maxLength?: number | null;
1670 * regexp?: string | null;
1671 * };
1672 * email?: {
1673 * required?: boolean;
1674 * regexp?: string | null;
1675 * };
1676 * fullName?: {
1677 * required?: boolean;
1678 * minLength?: number | null;
1679 * maxLength?: number | null;
1680 * regexp?: string | null;
1681 * };
1682 * };
1683 *}
1684 * ```
1685 */
1686class NbPasswordAuthStrategy extends NbAuthStrategy {
1687 constructor(http, route) {
1688 super();
1689 this.http = http;
1690 this.route = route;
1691 this.defaultOptions = passwordStrategyOptions;
1692 }
1693 static setup(options) {
1694 return [NbPasswordAuthStrategy, options];
1695 }
1696 authenticate(data) {
1697 const module = 'login';
1698 const method = this.getOption(`${module}.method`);
1699 const url = this.getActionEndpoint(module);
1700 const requireValidToken = this.getOption(`${module}.requireValidToken`);
1701 return this.http.request(method, url, { body: data, observe: 'response', headers: this.getHeaders() }).pipe(map((res) => {
1702 if (this.getOption(`${module}.alwaysFail`)) {
1703 throw this.createFailResponse(data);
1704 }
1705 return res;
1706 }), map((res) => {
1707 return new NbAuthResult(true, res, this.getOption(`${module}.redirect.success`), [], this.getOption('messages.getter')(module, res, this.options), this.createToken(this.getOption('token.getter')(module, res, this.options), requireValidToken));
1708 }), catchError((res) => {
1709 return this.handleResponseError(res, module);
1710 }));
1711 }
1712 register(data) {
1713 const module = 'register';
1714 const method = this.getOption(`${module}.method`);
1715 const url = this.getActionEndpoint(module);
1716 const requireValidToken = this.getOption(`${module}.requireValidToken`);
1717 return this.http.request(method, url, { body: data, observe: 'response', headers: this.getHeaders() }).pipe(map((res) => {
1718 if (this.getOption(`${module}.alwaysFail`)) {
1719 throw this.createFailResponse(data);
1720 }
1721 return res;
1722 }), map((res) => {
1723 return new NbAuthResult(true, res, this.getOption(`${module}.redirect.success`), [], this.getOption('messages.getter')(module, res, this.options), this.createToken(this.getOption('token.getter')('login', res, this.options), requireValidToken));
1724 }), catchError((res) => {
1725 return this.handleResponseError(res, module);
1726 }));
1727 }
1728 requestPassword(data) {
1729 const module = 'requestPass';
1730 const method = this.getOption(`${module}.method`);
1731 const url = this.getActionEndpoint(module);
1732 return this.http.request(method, url, { body: data, observe: 'response', headers: this.getHeaders() }).pipe(map((res) => {
1733 if (this.getOption(`${module}.alwaysFail`)) {
1734 throw this.createFailResponse();
1735 }
1736 return res;
1737 }), map((res) => {
1738 return new NbAuthResult(true, res, this.getOption(`${module}.redirect.success`), [], this.getOption('messages.getter')(module, res, this.options));
1739 }), catchError((res) => {
1740 return this.handleResponseError(res, module);
1741 }));
1742 }
1743 resetPassword(data = {}) {
1744 const module = 'resetPass';
1745 const method = this.getOption(`${module}.method`);
1746 const url = this.getActionEndpoint(module);
1747 const tokenKey = this.getOption(`${module}.resetPasswordTokenKey`);
1748 data[tokenKey] = this.route.snapshot.queryParams[tokenKey];
1749 return this.http.request(method, url, { body: data, observe: 'response', headers: this.getHeaders() }).pipe(map((res) => {
1750 if (this.getOption(`${module}.alwaysFail`)) {
1751 throw this.createFailResponse();
1752 }
1753 return res;
1754 }), map((res) => {
1755 return new NbAuthResult(true, res, this.getOption(`${module}.redirect.success`), [], this.getOption('messages.getter')(module, res, this.options));
1756 }), catchError((res) => {
1757 return this.handleResponseError(res, module);
1758 }));
1759 }
1760 logout() {
1761 const module = 'logout';
1762 const method = this.getOption(`${module}.method`);
1763 const url = this.getActionEndpoint(module);
1764 return of({}).pipe(switchMap((res) => {
1765 if (!url) {
1766 return of(res);
1767 }
1768 return this.http.request(method, url, { observe: 'response', headers: this.getHeaders() });
1769 }), map((res) => {
1770 if (this.getOption(`${module}.alwaysFail`)) {
1771 throw this.createFailResponse();
1772 }
1773 return res;
1774 }), map((res) => {
1775 return new NbAuthResult(true, res, this.getOption(`${module}.redirect.success`), [], this.getOption('messages.getter')(module, res, this.options));
1776 }), catchError((res) => {
1777 return this.handleResponseError(res, module);
1778 }));
1779 }
1780 refreshToken(data) {
1781 const module = 'refreshToken';
1782 const method = this.getOption(`${module}.method`);
1783 const url = this.getActionEndpoint(module);
1784 const requireValidToken = this.getOption(`${module}.requireValidToken`);
1785 return this.http.request(method, url, { body: data, observe: 'response', headers: this.getHeaders() }).pipe(map((res) => {
1786 if (this.getOption(`${module}.alwaysFail`)) {
1787 throw this.createFailResponse(data);
1788 }
1789 return res;
1790 }), map((res) => {
1791 return new NbAuthResult(true, res, this.getOption(`${module}.redirect.success`), [], this.getOption('messages.getter')(module, res, this.options), this.createToken(this.getOption('token.getter')(module, res, this.options), requireValidToken));
1792 }), catchError((res) => {
1793 return this.handleResponseError(res, module);
1794 }));
1795 }
1796 handleResponseError(res, module) {
1797 let errors = [];
1798 if (res instanceof HttpErrorResponse) {
1799 errors = this.getOption('errors.getter')(module, res, this.options);
1800 }
1801 else if (res instanceof NbAuthIllegalTokenError) {
1802 errors.push(res.message);
1803 }
1804 else {
1805 errors.push('Something went wrong.');
1806 }
1807 return of(new NbAuthResult(false, res, this.getOption(`${module}.redirect.failure`), errors));
1808 }
1809}
1810NbPasswordAuthStrategy.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbPasswordAuthStrategy, deps: [{ token: i1.HttpClient }, { token: i2.ActivatedRoute }], target: i0.ɵɵFactoryTarget.Injectable });
1811NbPasswordAuthStrategy.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbPasswordAuthStrategy });
1812i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbPasswordAuthStrategy, decorators: [{
1813 type: Injectable
1814 }], ctorParameters: function () { return [{ type: i1.HttpClient }, { type: i2.ActivatedRoute }]; } });
1815
1816/**
1817 * @license
1818 * Copyright Akveo. All Rights Reserved.
1819 * Licensed under the MIT License. See License.txt in the project root for license information.
1820 */
1821class NbAuthBlockComponent {
1822}
1823NbAuthBlockComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthBlockComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
1824NbAuthBlockComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "13.0.0", type: NbAuthBlockComponent, selector: "nb-auth-block", ngImport: i0, template: `
1825 <ng-content></ng-content>
1826 `, isInline: true, styles: ["/**\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */:host{display:block;width:100%;max-width:35rem}:host ::ng-deep form{width:100%}:host ::ng-deep .label{display:block;margin-bottom:.5rem}:host ::ng-deep .forgot-password{text-decoration:none;margin-bottom:.5rem}:host ::ng-deep .caption{margin-top:.5rem}:host ::ng-deep .alert{text-align:center}:host ::ng-deep .title{margin-top:0;margin-bottom:.75rem;text-align:center}:host ::ng-deep .sub-title{margin-bottom:2rem;text-align:center}:host ::ng-deep .form-control-group{margin-bottom:2rem}:host ::ng-deep .form-control-group.accept-group{display:flex;justify-content:space-between;margin:2rem 0}:host ::ng-deep .label-with-link{display:flex;justify-content:space-between}:host ::ng-deep .links{text-align:center;margin-top:1.75rem}:host ::ng-deep .links .socials{margin-top:1.5rem}:host ::ng-deep .links .socials a{margin:0 1rem;text-decoration:none;vertical-align:middle}:host ::ng-deep .links .socials a.with-icon{font-size:2rem}:host ::ng-deep .another-action{margin-top:2rem;text-align:center}:host ::ng-deep .sign-in-or-up{margin-top:2rem;display:flex;justify-content:space-between}:host ::ng-deep nb-alert .alert-title,:host ::ng-deep nb-alert .alert-message{margin:0 0 .5rem}:host ::ng-deep nb-alert .alert-message-list{list-style-type:none;padding:0;margin:0}\n"] });
1827i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthBlockComponent, decorators: [{
1828 type: Component,
1829 args: [{ selector: 'nb-auth-block', template: `
1830 <ng-content></ng-content>
1831 `, styles: ["/**\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */:host{display:block;width:100%;max-width:35rem}:host ::ng-deep form{width:100%}:host ::ng-deep .label{display:block;margin-bottom:.5rem}:host ::ng-deep .forgot-password{text-decoration:none;margin-bottom:.5rem}:host ::ng-deep .caption{margin-top:.5rem}:host ::ng-deep .alert{text-align:center}:host ::ng-deep .title{margin-top:0;margin-bottom:.75rem;text-align:center}:host ::ng-deep .sub-title{margin-bottom:2rem;text-align:center}:host ::ng-deep .form-control-group{margin-bottom:2rem}:host ::ng-deep .form-control-group.accept-group{display:flex;justify-content:space-between;margin:2rem 0}:host ::ng-deep .label-with-link{display:flex;justify-content:space-between}:host ::ng-deep .links{text-align:center;margin-top:1.75rem}:host ::ng-deep .links .socials{margin-top:1.5rem}:host ::ng-deep .links .socials a{margin:0 1rem;text-decoration:none;vertical-align:middle}:host ::ng-deep .links .socials a.with-icon{font-size:2rem}:host ::ng-deep .another-action{margin-top:2rem;text-align:center}:host ::ng-deep .sign-in-or-up{margin-top:2rem;display:flex;justify-content:space-between}:host ::ng-deep nb-alert .alert-title,:host ::ng-deep nb-alert .alert-message{margin:0 0 .5rem}:host ::ng-deep nb-alert .alert-message-list{list-style-type:none;padding:0;margin:0}\n"] }]
1832 }] });
1833
1834/**
1835 * @license
1836 * Copyright Akveo. All Rights Reserved.
1837 * Licensed under the MIT License. See License.txt in the project root for license information.
1838 */
1839class NbAuthComponent {
1840 // showcase of how to use the onAuthenticationChange method
1841 constructor(auth, location) {
1842 this.auth = auth;
1843 this.location = location;
1844 this.destroy$ = new Subject();
1845 this.authenticated = false;
1846 this.token = '';
1847 this.subscription = auth.onAuthenticationChange()
1848 .pipe(takeUntil(this.destroy$))
1849 .subscribe((authenticated) => {
1850 this.authenticated = authenticated;
1851 });
1852 }
1853 back() {
1854 this.location.back();
1855 return false;
1856 }
1857 ngOnDestroy() {
1858 this.destroy$.next();
1859 this.destroy$.complete();
1860 }
1861}
1862NbAuthComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthComponent, deps: [{ token: NbAuthService }, { token: i4.Location }], target: i0.ɵɵFactoryTarget.Component });
1863NbAuthComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "13.0.0", type: NbAuthComponent, selector: "nb-auth", ngImport: i0, template: `
1864 <nb-layout>
1865 <nb-layout-column>
1866 <nb-card>
1867 <nb-card-header>
1868 <nav class="navigation">
1869 <a href="#" (click)="back()" class="link back-link" aria-label="Back">
1870 <nb-icon icon="arrow-back"></nb-icon>
1871 </a>
1872 </nav>
1873 </nb-card-header>
1874 <nb-card-body>
1875 <nb-auth-block>
1876 <router-outlet></router-outlet>
1877 </nb-auth-block>
1878 </nb-card-body>
1879 </nb-card>
1880 </nb-layout-column>
1881 </nb-layout>
1882 `, isInline: true, styles: ["/*!\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */.visually-hidden{position:absolute!important;height:1px;width:1px;overflow:hidden;clip:rect(1px 1px 1px 1px);clip:rect(1px,1px,1px,1px)}.cdk-overlay-container,.cdk-global-overlay-wrapper{pointer-events:none;top:0;left:0;height:100%;width:100%}.cdk-overlay-container{position:fixed;z-index:1000}.cdk-overlay-container:empty{display:none}.cdk-global-overlay-wrapper{display:flex;position:absolute;z-index:1000}.cdk-overlay-pane{position:absolute;pointer-events:auto;box-sizing:border-box;z-index:1000;display:flex;max-width:100%;max-height:100%}.cdk-overlay-backdrop{position:absolute;top:0;bottom:0;left:0;right:0;z-index:1000;pointer-events:auto;-webkit-tap-highlight-color:transparent;transition:opacity .4s cubic-bezier(.25,.8,.25,1);opacity:0}.cdk-overlay-backdrop.cdk-overlay-backdrop-showing{opacity:1}.cdk-high-contrast-active .cdk-overlay-backdrop.cdk-overlay-backdrop-showing{opacity:.6}.cdk-overlay-dark-backdrop{background:rgba(0,0,0,.32)}.cdk-overlay-transparent-backdrop,.cdk-overlay-transparent-backdrop.cdk-overlay-backdrop-showing{opacity:0}.cdk-overlay-connected-position-bounding-box{position:absolute;z-index:1000;display:flex;flex-direction:column;min-width:1px;min-height:1px}.cdk-global-scrollblock{position:fixed;width:100%;overflow-y:scroll}.nb-global-scrollblock{position:static;width:auto;overflow:hidden}/*\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *//*!\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */html{box-sizing:border-box}*,*:before,*:after{box-sizing:inherit}html,body{margin:0;padding:0}html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}h1{font-size:2em;margin:.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent}abbr[title]{border-bottom:none;text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}button,[type=button],[type=reset],[type=submit]{-webkit-appearance:button}button::-moz-focus-inner,[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner{border-style:none;padding:0}button:-moz-focusring,[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:.35em .75em .625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}template,[hidden]{display:none}/**\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */:host nb-card{margin:0;height:calc(100vh - 5rem)}:host .navigation .link{display:inline-block;text-decoration:none}:host .navigation .link nb-icon{font-size:2rem;vertical-align:middle}:host .links nb-icon{font-size:2.5rem}:host nb-card-body{display:flex;width:100%}:host nb-auth-block{margin:auto}@media (max-width: 767.98px){:host nb-card{border-radius:0;height:100vh}}:host ::ng-deep nb-layout .layout .layout-container .content .columns nb-layout-column{padding:2.5rem}@media (max-width: 767.98px){:host ::ng-deep nb-layout .layout .layout-container .content .columns nb-layout-column{padding:0}}\n"], components: [{ type: i3.NbLayoutComponent, selector: "nb-layout", inputs: ["center", "windowMode", "withScroll", "restoreScrollTop"] }, { type: i3.NbLayoutColumnComponent, selector: "nb-layout-column", inputs: ["left", "start"] }, { type: i3.NbCardComponent, selector: "nb-card", inputs: ["size", "status", "accent"] }, { type: i3.NbCardHeaderComponent, selector: "nb-card-header" }, { type: i3.NbIconComponent, selector: "nb-icon", inputs: ["icon", "pack", "options", "status", "config"] }, { type: i3.NbCardBodyComponent, selector: "nb-card-body" }, { type: NbAuthBlockComponent, selector: "nb-auth-block" }], directives: [{ type: i2.RouterOutlet, selector: "router-outlet", outputs: ["activate", "deactivate", "attach", "detach"], exportAs: ["outlet"] }] });
1883i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthComponent, decorators: [{
1884 type: Component,
1885 args: [{ selector: 'nb-auth', template: `
1886 <nb-layout>
1887 <nb-layout-column>
1888 <nb-card>
1889 <nb-card-header>
1890 <nav class="navigation">
1891 <a href="#" (click)="back()" class="link back-link" aria-label="Back">
1892 <nb-icon icon="arrow-back"></nb-icon>
1893 </a>
1894 </nav>
1895 </nb-card-header>
1896 <nb-card-body>
1897 <nb-auth-block>
1898 <router-outlet></router-outlet>
1899 </nb-auth-block>
1900 </nb-card-body>
1901 </nb-card>
1902 </nb-layout-column>
1903 </nb-layout>
1904 `, styles: ["/*!\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */.visually-hidden{position:absolute!important;height:1px;width:1px;overflow:hidden;clip:rect(1px 1px 1px 1px);clip:rect(1px,1px,1px,1px)}.cdk-overlay-container,.cdk-global-overlay-wrapper{pointer-events:none;top:0;left:0;height:100%;width:100%}.cdk-overlay-container{position:fixed;z-index:1000}.cdk-overlay-container:empty{display:none}.cdk-global-overlay-wrapper{display:flex;position:absolute;z-index:1000}.cdk-overlay-pane{position:absolute;pointer-events:auto;box-sizing:border-box;z-index:1000;display:flex;max-width:100%;max-height:100%}.cdk-overlay-backdrop{position:absolute;top:0;bottom:0;left:0;right:0;z-index:1000;pointer-events:auto;-webkit-tap-highlight-color:transparent;transition:opacity .4s cubic-bezier(.25,.8,.25,1);opacity:0}.cdk-overlay-backdrop.cdk-overlay-backdrop-showing{opacity:1}.cdk-high-contrast-active .cdk-overlay-backdrop.cdk-overlay-backdrop-showing{opacity:.6}.cdk-overlay-dark-backdrop{background:rgba(0,0,0,.32)}.cdk-overlay-transparent-backdrop,.cdk-overlay-transparent-backdrop.cdk-overlay-backdrop-showing{opacity:0}.cdk-overlay-connected-position-bounding-box{position:absolute;z-index:1000;display:flex;flex-direction:column;min-width:1px;min-height:1px}.cdk-global-scrollblock{position:fixed;width:100%;overflow-y:scroll}.nb-global-scrollblock{position:static;width:auto;overflow:hidden}/*\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *//*!\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */html{box-sizing:border-box}*,*:before,*:after{box-sizing:inherit}html,body{margin:0;padding:0}html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}h1{font-size:2em;margin:.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent}abbr[title]{border-bottom:none;text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}button,[type=button],[type=reset],[type=submit]{-webkit-appearance:button}button::-moz-focus-inner,[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner{border-style:none;padding:0}button:-moz-focusring,[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:.35em .75em .625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}template,[hidden]{display:none}/**\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */:host nb-card{margin:0;height:calc(100vh - 5rem)}:host .navigation .link{display:inline-block;text-decoration:none}:host .navigation .link nb-icon{font-size:2rem;vertical-align:middle}:host .links nb-icon{font-size:2.5rem}:host nb-card-body{display:flex;width:100%}:host nb-auth-block{margin:auto}@media (max-width: 767.98px){:host nb-card{border-radius:0;height:100vh}}:host ::ng-deep nb-layout .layout .layout-container .content .columns nb-layout-column{padding:2.5rem}@media (max-width: 767.98px){:host ::ng-deep nb-layout .layout .layout-container .content .columns nb-layout-column{padding:0}}\n"] }]
1905 }], ctorParameters: function () { return [{ type: NbAuthService }, { type: i4.Location }]; } });
1906
1907/**
1908 * @license
1909 * Copyright Akveo. All Rights Reserved.
1910 * Licensed under the MIT License. See License.txt in the project root for license information.
1911 */
1912class NbLoginComponent {
1913 constructor(service, options = {}, cd, router) {
1914 this.service = service;
1915 this.options = options;
1916 this.cd = cd;
1917 this.router = router;
1918 this.redirectDelay = 0;
1919 this.showMessages = {};
1920 this.strategy = '';
1921 this.errors = [];
1922 this.messages = [];
1923 this.user = {};
1924 this.submitted = false;
1925 this.socialLinks = [];
1926 this.rememberMe = false;
1927 this.redirectDelay = this.getConfigValue('forms.login.redirectDelay');
1928 this.showMessages = this.getConfigValue('forms.login.showMessages');
1929 this.strategy = this.getConfigValue('forms.login.strategy');
1930 this.socialLinks = this.getConfigValue('forms.login.socialLinks');
1931 this.rememberMe = this.getConfigValue('forms.login.rememberMe');
1932 }
1933 login() {
1934 this.errors = [];
1935 this.messages = [];
1936 this.submitted = true;
1937 this.service.authenticate(this.strategy, this.user).subscribe((result) => {
1938 this.submitted = false;
1939 if (result.isSuccess()) {
1940 this.messages = result.getMessages();
1941 }
1942 else {
1943 this.errors = result.getErrors();
1944 }
1945 const redirect = result.getRedirect();
1946 if (redirect) {
1947 setTimeout(() => {
1948 return this.router.navigateByUrl(redirect);
1949 }, this.redirectDelay);
1950 }
1951 this.cd.detectChanges();
1952 });
1953 }
1954 getConfigValue(key) {
1955 return getDeepFromObject(this.options, key, null);
1956 }
1957}
1958NbLoginComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbLoginComponent, deps: [{ token: NbAuthService }, { token: NB_AUTH_OPTIONS }, { token: i0.ChangeDetectorRef }, { token: i2.Router }], target: i0.ɵɵFactoryTarget.Component });
1959NbLoginComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "13.0.0", type: NbLoginComponent, selector: "nb-login", ngImport: i0, template: "<h1 id=\"title\" class=\"title\">Login</h1>\n<p class=\"sub-title\">Hello! Log in with your email.</p>\n\n<nb-alert *ngIf=\"showMessages.error && errors?.length && !submitted\" outline=\"danger\" role=\"alert\">\n <p class=\"alert-title\"><b>Oh snap!</b></p>\n <ul class=\"alert-message-list\">\n <li *ngFor=\"let error of errors\" class=\"alert-message\">{{ error }}</li>\n </ul>\n</nb-alert>\n\n<nb-alert *ngIf=\"showMessages.success && messages?.length && !submitted\" outline=\"success\" role=\"alert\">\n <p class=\"alert-title\"><b>Hooray!</b></p>\n <ul class=\"alert-message-list\">\n <li *ngFor=\"let message of messages\" class=\"alert-message\">{{ message }}</li>\n </ul>\n</nb-alert>\n\n<form (ngSubmit)=\"login()\" #form=\"ngForm\" aria-labelledby=\"title\">\n\n <div class=\"form-control-group\">\n <label class=\"label\" for=\"input-email\">Email address:</label>\n <input nbInput\n fullWidth\n [(ngModel)]=\"user.email\"\n #email=\"ngModel\"\n name=\"email\"\n id=\"input-email\"\n pattern=\".+@.+\\..+\"\n placeholder=\"Email address\"\n fieldSize=\"large\"\n autofocus\n [status]=\"email.dirty ? (email.invalid ? 'danger' : 'success') : 'basic'\"\n [required]=\"getConfigValue('forms.validation.email.required')\"\n [attr.aria-invalid]=\"email.invalid && email.touched ? true : null\">\n <ng-container *ngIf=\"email.invalid && email.touched\">\n <p class=\"caption status-danger\" *ngIf=\"email.errors?.required\">\n Email is required!\n </p>\n <p class=\"caption status-danger\" *ngIf=\"email.errors?.pattern\">\n Email should be the real one!\n </p>\n </ng-container>\n </div>\n\n <div class=\"form-control-group\">\n <span class=\"label-with-link\">\n <label class=\"label\" for=\"input-password\">Password:</label>\n <a class=\"forgot-password caption-2\" routerLink=\"../request-password\">Forgot Password?</a>\n </span>\n <input nbInput\n fullWidth\n [(ngModel)]=\"user.password\"\n #password=\"ngModel\"\n name=\"password\"\n type=\"password\"\n id=\"input-password\"\n placeholder=\"Password\"\n fieldSize=\"large\"\n [status]=\"password.dirty ? (password.invalid ? 'danger' : 'success') : 'basic'\"\n [required]=\"getConfigValue('forms.validation.password.required')\"\n [minlength]=\"getConfigValue('forms.validation.password.minLength')\"\n [maxlength]=\"getConfigValue('forms.validation.password.maxLength')\"\n [attr.aria-invalid]=\"password.invalid && password.touched ? true : null\">\n <ng-container *ngIf=\"password.invalid && password.touched \">\n <p class=\"caption status-danger\" *ngIf=\"password.errors?.required\">\n Password is required!\n </p>\n <p class=\"caption status-danger\" *ngIf=\"password.errors?.minlength || password.errors?.maxlength\">\n Password should contain\n from {{ getConfigValue('forms.validation.password.minLength') }}\n to {{ getConfigValue('forms.validation.password.maxLength') }}\n characters\n </p>\n </ng-container>\n </div>\n\n <div class=\"form-control-group accept-group\">\n <nb-checkbox name=\"rememberMe\" [(ngModel)]=\"user.rememberMe\" *ngIf=\"rememberMe\">Remember me</nb-checkbox>\n </div>\n\n <button nbButton\n fullWidth\n status=\"primary\"\n size=\"large\"\n [disabled]=\"submitted || !form.valid\"\n [class.btn-pulse]=\"submitted\">\n Log In\n </button>\n</form>\n\n<section *ngIf=\"socialLinks && socialLinks.length > 0\" class=\"links\" aria-label=\"Social sign in\">\n or enter with:\n <div class=\"socials\">\n <ng-container *ngFor=\"let socialLink of socialLinks\">\n <a *ngIf=\"socialLink.link\"\n [routerLink]=\"socialLink.link\"\n [attr.target]=\"socialLink.target\"\n [attr.class]=\"socialLink.icon\"\n [class.with-icon]=\"socialLink.icon\">\n <nb-icon *ngIf=\"socialLink.icon; else title\" [icon]=\"socialLink.icon\"></nb-icon>\n <ng-template #title>{{ socialLink.title }}</ng-template>\n </a>\n <a *ngIf=\"socialLink.url\"\n [attr.href]=\"socialLink.url\"\n [attr.target]=\"socialLink.target\"\n [attr.class]=\"socialLink.icon\"\n [class.with-icon]=\"socialLink.icon\">\n <nb-icon *ngIf=\"socialLink.icon; else title\" [icon]=\"socialLink.icon\"></nb-icon>\n <ng-template #title>{{ socialLink.title }}</ng-template>\n </a>\n </ng-container>\n </div>\n</section>\n\n<section class=\"another-action\" aria-label=\"Register\">\n Don't have an account? <a class=\"text-link\" routerLink=\"../register\">Register</a>\n</section>\n", components: [{ type: i3.NbAlertComponent, selector: "nb-alert", inputs: ["size", "status", "accent", "outline", "closable"], outputs: ["close"] }, { type: i3.NbCheckboxComponent, selector: "nb-checkbox", inputs: ["checked", "disabled", "status", "indeterminate"], outputs: ["checkedChange"] }, { type: i3.NbButtonComponent, selector: "button[nbButton],a[nbButton],input[type=\"button\"][nbButton],input[type=\"submit\"][nbButton]", inputs: ["hero"] }, { type: i3.NbIconComponent, selector: "nb-icon", inputs: ["icon", "pack", "options", "status", "config"] }], directives: [{ type: i4.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { type: i4.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { type: i5.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { type: i5.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { type: i5.NgForm, selector: "form:not([ngNoForm]):not([formGroup]),ng-form,[ngForm]", inputs: ["ngFormOptions"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { type: i3.NbInputDirective, selector: "input[nbInput],textarea[nbInput]", inputs: ["fieldSize", "status", "shape", "fullWidth"] }, { type: i5.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { type: i5.PatternValidator, selector: "[pattern][formControlName],[pattern][formControl],[pattern][ngModel]", inputs: ["pattern"] }, { type: i5.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { type: i5.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { type: i5.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { type: i2.RouterLinkWithHref, selector: "a[routerLink],area[routerLink]", inputs: ["target", "queryParams", "fragment", "queryParamsHandling", "preserveFragment", "skipLocationChange", "replaceUrl", "state", "relativeTo", "routerLink"] }, { type: i5.MinLengthValidator, selector: "[minlength][formControlName],[minlength][formControl],[minlength][ngModel]", inputs: ["minlength"] }, { type: i5.MaxLengthValidator, selector: "[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]", inputs: ["maxlength"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
1960i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbLoginComponent, decorators: [{
1961 type: Component,
1962 args: [{ selector: 'nb-login', changeDetection: ChangeDetectionStrategy.OnPush, template: "<h1 id=\"title\" class=\"title\">Login</h1>\n<p class=\"sub-title\">Hello! Log in with your email.</p>\n\n<nb-alert *ngIf=\"showMessages.error && errors?.length && !submitted\" outline=\"danger\" role=\"alert\">\n <p class=\"alert-title\"><b>Oh snap!</b></p>\n <ul class=\"alert-message-list\">\n <li *ngFor=\"let error of errors\" class=\"alert-message\">{{ error }}</li>\n </ul>\n</nb-alert>\n\n<nb-alert *ngIf=\"showMessages.success && messages?.length && !submitted\" outline=\"success\" role=\"alert\">\n <p class=\"alert-title\"><b>Hooray!</b></p>\n <ul class=\"alert-message-list\">\n <li *ngFor=\"let message of messages\" class=\"alert-message\">{{ message }}</li>\n </ul>\n</nb-alert>\n\n<form (ngSubmit)=\"login()\" #form=\"ngForm\" aria-labelledby=\"title\">\n\n <div class=\"form-control-group\">\n <label class=\"label\" for=\"input-email\">Email address:</label>\n <input nbInput\n fullWidth\n [(ngModel)]=\"user.email\"\n #email=\"ngModel\"\n name=\"email\"\n id=\"input-email\"\n pattern=\".+@.+\\..+\"\n placeholder=\"Email address\"\n fieldSize=\"large\"\n autofocus\n [status]=\"email.dirty ? (email.invalid ? 'danger' : 'success') : 'basic'\"\n [required]=\"getConfigValue('forms.validation.email.required')\"\n [attr.aria-invalid]=\"email.invalid && email.touched ? true : null\">\n <ng-container *ngIf=\"email.invalid && email.touched\">\n <p class=\"caption status-danger\" *ngIf=\"email.errors?.required\">\n Email is required!\n </p>\n <p class=\"caption status-danger\" *ngIf=\"email.errors?.pattern\">\n Email should be the real one!\n </p>\n </ng-container>\n </div>\n\n <div class=\"form-control-group\">\n <span class=\"label-with-link\">\n <label class=\"label\" for=\"input-password\">Password:</label>\n <a class=\"forgot-password caption-2\" routerLink=\"../request-password\">Forgot Password?</a>\n </span>\n <input nbInput\n fullWidth\n [(ngModel)]=\"user.password\"\n #password=\"ngModel\"\n name=\"password\"\n type=\"password\"\n id=\"input-password\"\n placeholder=\"Password\"\n fieldSize=\"large\"\n [status]=\"password.dirty ? (password.invalid ? 'danger' : 'success') : 'basic'\"\n [required]=\"getConfigValue('forms.validation.password.required')\"\n [minlength]=\"getConfigValue('forms.validation.password.minLength')\"\n [maxlength]=\"getConfigValue('forms.validation.password.maxLength')\"\n [attr.aria-invalid]=\"password.invalid && password.touched ? true : null\">\n <ng-container *ngIf=\"password.invalid && password.touched \">\n <p class=\"caption status-danger\" *ngIf=\"password.errors?.required\">\n Password is required!\n </p>\n <p class=\"caption status-danger\" *ngIf=\"password.errors?.minlength || password.errors?.maxlength\">\n Password should contain\n from {{ getConfigValue('forms.validation.password.minLength') }}\n to {{ getConfigValue('forms.validation.password.maxLength') }}\n characters\n </p>\n </ng-container>\n </div>\n\n <div class=\"form-control-group accept-group\">\n <nb-checkbox name=\"rememberMe\" [(ngModel)]=\"user.rememberMe\" *ngIf=\"rememberMe\">Remember me</nb-checkbox>\n </div>\n\n <button nbButton\n fullWidth\n status=\"primary\"\n size=\"large\"\n [disabled]=\"submitted || !form.valid\"\n [class.btn-pulse]=\"submitted\">\n Log In\n </button>\n</form>\n\n<section *ngIf=\"socialLinks && socialLinks.length > 0\" class=\"links\" aria-label=\"Social sign in\">\n or enter with:\n <div class=\"socials\">\n <ng-container *ngFor=\"let socialLink of socialLinks\">\n <a *ngIf=\"socialLink.link\"\n [routerLink]=\"socialLink.link\"\n [attr.target]=\"socialLink.target\"\n [attr.class]=\"socialLink.icon\"\n [class.with-icon]=\"socialLink.icon\">\n <nb-icon *ngIf=\"socialLink.icon; else title\" [icon]=\"socialLink.icon\"></nb-icon>\n <ng-template #title>{{ socialLink.title }}</ng-template>\n </a>\n <a *ngIf=\"socialLink.url\"\n [attr.href]=\"socialLink.url\"\n [attr.target]=\"socialLink.target\"\n [attr.class]=\"socialLink.icon\"\n [class.with-icon]=\"socialLink.icon\">\n <nb-icon *ngIf=\"socialLink.icon; else title\" [icon]=\"socialLink.icon\"></nb-icon>\n <ng-template #title>{{ socialLink.title }}</ng-template>\n </a>\n </ng-container>\n </div>\n</section>\n\n<section class=\"another-action\" aria-label=\"Register\">\n Don't have an account? <a class=\"text-link\" routerLink=\"../register\">Register</a>\n</section>\n" }]
1963 }], ctorParameters: function () {
1964 return [{ type: NbAuthService }, { type: undefined, decorators: [{
1965 type: Inject,
1966 args: [NB_AUTH_OPTIONS]
1967 }] }, { type: i0.ChangeDetectorRef }, { type: i2.Router }];
1968 } });
1969
1970/**
1971 * @license
1972 * Copyright Akveo. All Rights Reserved.
1973 * Licensed under the MIT License. See License.txt in the project root for license information.
1974 */
1975class NbRegisterComponent {
1976 constructor(service, options = {}, cd, router) {
1977 this.service = service;
1978 this.options = options;
1979 this.cd = cd;
1980 this.router = router;
1981 this.redirectDelay = 0;
1982 this.showMessages = {};
1983 this.strategy = '';
1984 this.submitted = false;
1985 this.errors = [];
1986 this.messages = [];
1987 this.user = {};
1988 this.socialLinks = [];
1989 this.redirectDelay = this.getConfigValue('forms.register.redirectDelay');
1990 this.showMessages = this.getConfigValue('forms.register.showMessages');
1991 this.strategy = this.getConfigValue('forms.register.strategy');
1992 this.socialLinks = this.getConfigValue('forms.login.socialLinks');
1993 }
1994 register() {
1995 this.errors = this.messages = [];
1996 this.submitted = true;
1997 this.service.register(this.strategy, this.user).subscribe((result) => {
1998 this.submitted = false;
1999 if (result.isSuccess()) {
2000 this.messages = result.getMessages();
2001 }
2002 else {
2003 this.errors = result.getErrors();
2004 }
2005 const redirect = result.getRedirect();
2006 if (redirect) {
2007 setTimeout(() => {
2008 return this.router.navigateByUrl(redirect);
2009 }, this.redirectDelay);
2010 }
2011 this.cd.detectChanges();
2012 });
2013 }
2014 getConfigValue(key) {
2015 return getDeepFromObject(this.options, key, null);
2016 }
2017}
2018NbRegisterComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbRegisterComponent, deps: [{ token: NbAuthService }, { token: NB_AUTH_OPTIONS }, { token: i0.ChangeDetectorRef }, { token: i2.Router }], target: i0.ɵɵFactoryTarget.Component });
2019NbRegisterComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "13.0.0", type: NbRegisterComponent, selector: "nb-register", ngImport: i0, template: "<h1 id=\"title\" class=\"title\">Register</h1>\n\n<nb-alert *ngIf=\"showMessages.error && errors?.length && !submitted\" outline=\"danger\" role=\"alert\">\n <p class=\"alert-title\"><b>Oh snap!</b></p>\n <ul class=\"alert-message-list\">\n <li *ngFor=\"let error of errors\" class=\"alert-message\">{{ error }}</li>\n </ul>\n</nb-alert>\n\n<nb-alert *ngIf=\"showMessages.success && messages?.length && !submitted\" outline=\"success\" role=\"alert\">\n <p class=\"alert-title\"><b>Hooray!</b></p>\n <ul class=\"alert-message-list\">\n <li *ngFor=\"let message of messages\" class=\"alert-message\">{{ message }}</li>\n </ul>\n</nb-alert>\n\n<form (ngSubmit)=\"register()\" #form=\"ngForm\" aria-labelledby=\"title\">\n\n <div class=\"form-control-group\">\n <label class=\"label\" for=\"input-name\">Full name:</label>\n <input nbInput\n [(ngModel)]=\"user.fullName\"\n #fullName=\"ngModel\"\n id=\"input-name\"\n name=\"fullName\"\n placeholder=\"Full name\"\n autofocus\n fullWidth\n fieldSize=\"large\"\n [status]=\"fullName.dirty ? (fullName.invalid ? 'danger' : 'success') : 'basic'\"\n [required]=\"getConfigValue('forms.validation.fullName.required')\"\n [minlength]=\"getConfigValue('forms.validation.fullName.minLength')\"\n [maxlength]=\"getConfigValue('forms.validation.fullName.maxLength')\"\n [attr.aria-invalid]=\"fullName.invalid && fullName.touched ? true : null\">\n <ng-container *ngIf=\"fullName.invalid && fullName.touched\">\n <p class=\"caption status-danger\" *ngIf=\"fullName.errors?.required\">\n Full name is required!\n </p>\n <p class=\"caption status-danger\" *ngIf=\"fullName.errors?.minlength || fullName.errors?.maxlength\">\n Full name should contains\n from {{getConfigValue('forms.validation.fullName.minLength')}}\n to {{getConfigValue('forms.validation.fullName.maxLength')}}\n characters\n </p>\n </ng-container>\n </div>\n\n <div class=\"form-control-group\">\n <label class=\"label\" for=\"input-email\">Email address:</label>\n <input nbInput\n [(ngModel)]=\"user.email\"\n #email=\"ngModel\"\n id=\"input-email\"\n name=\"email\"\n pattern=\".+@.+..+\"\n placeholder=\"Email address\"\n fullWidth\n fieldSize=\"large\"\n [status]=\"email.dirty ? (email.invalid ? 'danger' : 'success') : 'basic'\"\n [required]=\"getConfigValue('forms.validation.email.required')\"\n [attr.aria-invalid]=\"email.invalid && email.touched ? true : null\">\n <ng-container *ngIf=\"email.invalid && email.touched\">\n <p class=\"caption status-danger\" *ngIf=\"email.errors?.required\">\n Email is required!\n </p>\n <p class=\"caption status-danger\" *ngIf=\"email.errors?.pattern\">\n Email should be the real one!\n </p>\n </ng-container>\n </div>\n\n <div class=\"form-control-group\">\n <label class=\"label\" for=\"input-password\">Password:</label>\n <input nbInput\n [(ngModel)]=\"user.password\"\n #password=\"ngModel\"\n type=\"password\"\n id=\"input-password\"\n name=\"password\"\n placeholder=\"Password\"\n fullWidth\n fieldSize=\"large\"\n [status]=\"password.dirty ? (password.invalid ? 'danger' : 'success') : 'basic'\"\n [required]=\"getConfigValue('forms.validation.password.required')\"\n [minlength]=\"getConfigValue('forms.validation.password.minLength')\"\n [maxlength]=\"getConfigValue('forms.validation.password.maxLength')\"\n [attr.aria-invalid]=\"password.invalid && password.touched ? true : null\">\n <ng-container *ngIf=\"password.invalid && password.touched\">\n <p class=\"caption status-danger\" *ngIf=\"password.errors?.required\">\n Password is required!\n </p>\n <p class=\"caption status-danger\" *ngIf=\"password.errors?.minlength || password.errors?.maxlength\">\n Password should contain\n from {{ getConfigValue('forms.validation.password.minLength') }}\n to {{ getConfigValue('forms.validation.password.maxLength') }}\n characters\n </p>\n </ng-container>\n </div>\n\n <div class=\"form-control-group\">\n <label class=\"label\" for=\"input-re-password\">Repeat password:</label>\n <input nbInput\n [(ngModel)]=\"user.confirmPassword\"\n #rePass=\"ngModel\"\n type=\"password\"\n id=\"input-re-password\"\n name=\"rePass\"\n placeholder=\"Confirm Password\"\n fullWidth\n fieldSize=\"large\"\n [status]=\"rePass.dirty ? (rePass.invalid || password.value != rePass.value ? 'danger' : 'success') : 'basic'\"\n [required]=\"getConfigValue('forms.validation.password.required')\"\n [attr.aria-invalid]=\"rePass.invalid && rePass.touched ? true : null\">\n <ng-container *ngIf=\"rePass.invalid && rePass.touched\">\n <p class=\"caption status-danger\" *ngIf=\"rePass.errors?.required\">\n Password confirmation is required!\n </p>\n <p class=\"caption status-danger\" *ngIf=\"password.value != rePass.value && !rePass.errors?.required\">\n Password does not match the confirm password.\n </p>\n </ng-container>\n </div>\n\n <div class=\"form-control-group accept-group\" *ngIf=\"getConfigValue('forms.register.terms')\">\n <nb-checkbox name=\"terms\" [(ngModel)]=\"user.terms\" [required]=\"getConfigValue('forms.register.terms')\">\n Agree to <a href=\"#\" target=\"_blank\"><strong>Terms & Conditions</strong></a>\n </nb-checkbox>\n </div>\n\n <button nbButton\n fullWidth\n status=\"primary\"\n size=\"large\"\n [disabled]=\"submitted || !form.valid\"\n [class.btn-pulse]=\"submitted\">\n Register\n </button>\n</form>\n\n<section *ngIf=\"socialLinks && socialLinks.length > 0\" class=\"links\" aria-label=\"Social sign in\">\n or enter with:\n <div class=\"socials\">\n <ng-container *ngFor=\"let socialLink of socialLinks\">\n <a *ngIf=\"socialLink.link\"\n [routerLink]=\"socialLink.link\"\n [attr.target]=\"socialLink.target\"\n [attr.class]=\"socialLink.icon\"\n [class.with-icon]=\"socialLink.icon\">\n <nb-icon *ngIf=\"socialLink.icon; else title\" [icon]=\"socialLink.icon\"></nb-icon>\n <ng-template #title>{{ socialLink.title }}</ng-template>\n </a>\n <a *ngIf=\"socialLink.url\"\n [attr.href]=\"socialLink.url\"\n [attr.target]=\"socialLink.target\"\n [attr.class]=\"socialLink.icon\"\n [class.with-icon]=\"socialLink.icon\">\n <nb-icon *ngIf=\"socialLink.icon; else title\" [icon]=\"socialLink.icon\"></nb-icon>\n <ng-template #title>{{ socialLink.title }}</ng-template>\n </a>\n </ng-container>\n </div>\n</section>\n\n<section class=\"another-action\" aria-label=\"Sign in\">\n Already have an account? <a class=\"text-link\" routerLink=\"../login\">Log in</a>\n</section>\n", styles: ["/**\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */:host .title{margin-bottom:2rem}\n"], components: [{ type: i3.NbAlertComponent, selector: "nb-alert", inputs: ["size", "status", "accent", "outline", "closable"], outputs: ["close"] }, { type: i3.NbCheckboxComponent, selector: "nb-checkbox", inputs: ["checked", "disabled", "status", "indeterminate"], outputs: ["checkedChange"] }, { type: i3.NbButtonComponent, selector: "button[nbButton],a[nbButton],input[type=\"button\"][nbButton],input[type=\"submit\"][nbButton]", inputs: ["hero"] }, { type: i3.NbIconComponent, selector: "nb-icon", inputs: ["icon", "pack", "options", "status", "config"] }], directives: [{ type: i4.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { type: i4.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { type: i5.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { type: i5.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { type: i5.NgForm, selector: "form:not([ngNoForm]):not([formGroup]),ng-form,[ngForm]", inputs: ["ngFormOptions"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { type: i3.NbInputDirective, selector: "input[nbInput],textarea[nbInput]", inputs: ["fieldSize", "status", "shape", "fullWidth"] }, { type: i5.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { type: i5.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { type: i5.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { type: i5.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { type: i5.MinLengthValidator, selector: "[minlength][formControlName],[minlength][formControl],[minlength][ngModel]", inputs: ["minlength"] }, { type: i5.MaxLengthValidator, selector: "[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]", inputs: ["maxlength"] }, { type: i5.PatternValidator, selector: "[pattern][formControlName],[pattern][formControl],[pattern][ngModel]", inputs: ["pattern"] }, { type: i2.RouterLinkWithHref, selector: "a[routerLink],area[routerLink]", inputs: ["target", "queryParams", "fragment", "queryParamsHandling", "preserveFragment", "skipLocationChange", "replaceUrl", "state", "relativeTo", "routerLink"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
2020i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbRegisterComponent, decorators: [{
2021 type: Component,
2022 args: [{ selector: 'nb-register', changeDetection: ChangeDetectionStrategy.OnPush, template: "<h1 id=\"title\" class=\"title\">Register</h1>\n\n<nb-alert *ngIf=\"showMessages.error && errors?.length && !submitted\" outline=\"danger\" role=\"alert\">\n <p class=\"alert-title\"><b>Oh snap!</b></p>\n <ul class=\"alert-message-list\">\n <li *ngFor=\"let error of errors\" class=\"alert-message\">{{ error }}</li>\n </ul>\n</nb-alert>\n\n<nb-alert *ngIf=\"showMessages.success && messages?.length && !submitted\" outline=\"success\" role=\"alert\">\n <p class=\"alert-title\"><b>Hooray!</b></p>\n <ul class=\"alert-message-list\">\n <li *ngFor=\"let message of messages\" class=\"alert-message\">{{ message }}</li>\n </ul>\n</nb-alert>\n\n<form (ngSubmit)=\"register()\" #form=\"ngForm\" aria-labelledby=\"title\">\n\n <div class=\"form-control-group\">\n <label class=\"label\" for=\"input-name\">Full name:</label>\n <input nbInput\n [(ngModel)]=\"user.fullName\"\n #fullName=\"ngModel\"\n id=\"input-name\"\n name=\"fullName\"\n placeholder=\"Full name\"\n autofocus\n fullWidth\n fieldSize=\"large\"\n [status]=\"fullName.dirty ? (fullName.invalid ? 'danger' : 'success') : 'basic'\"\n [required]=\"getConfigValue('forms.validation.fullName.required')\"\n [minlength]=\"getConfigValue('forms.validation.fullName.minLength')\"\n [maxlength]=\"getConfigValue('forms.validation.fullName.maxLength')\"\n [attr.aria-invalid]=\"fullName.invalid && fullName.touched ? true : null\">\n <ng-container *ngIf=\"fullName.invalid && fullName.touched\">\n <p class=\"caption status-danger\" *ngIf=\"fullName.errors?.required\">\n Full name is required!\n </p>\n <p class=\"caption status-danger\" *ngIf=\"fullName.errors?.minlength || fullName.errors?.maxlength\">\n Full name should contains\n from {{getConfigValue('forms.validation.fullName.minLength')}}\n to {{getConfigValue('forms.validation.fullName.maxLength')}}\n characters\n </p>\n </ng-container>\n </div>\n\n <div class=\"form-control-group\">\n <label class=\"label\" for=\"input-email\">Email address:</label>\n <input nbInput\n [(ngModel)]=\"user.email\"\n #email=\"ngModel\"\n id=\"input-email\"\n name=\"email\"\n pattern=\".+@.+..+\"\n placeholder=\"Email address\"\n fullWidth\n fieldSize=\"large\"\n [status]=\"email.dirty ? (email.invalid ? 'danger' : 'success') : 'basic'\"\n [required]=\"getConfigValue('forms.validation.email.required')\"\n [attr.aria-invalid]=\"email.invalid && email.touched ? true : null\">\n <ng-container *ngIf=\"email.invalid && email.touched\">\n <p class=\"caption status-danger\" *ngIf=\"email.errors?.required\">\n Email is required!\n </p>\n <p class=\"caption status-danger\" *ngIf=\"email.errors?.pattern\">\n Email should be the real one!\n </p>\n </ng-container>\n </div>\n\n <div class=\"form-control-group\">\n <label class=\"label\" for=\"input-password\">Password:</label>\n <input nbInput\n [(ngModel)]=\"user.password\"\n #password=\"ngModel\"\n type=\"password\"\n id=\"input-password\"\n name=\"password\"\n placeholder=\"Password\"\n fullWidth\n fieldSize=\"large\"\n [status]=\"password.dirty ? (password.invalid ? 'danger' : 'success') : 'basic'\"\n [required]=\"getConfigValue('forms.validation.password.required')\"\n [minlength]=\"getConfigValue('forms.validation.password.minLength')\"\n [maxlength]=\"getConfigValue('forms.validation.password.maxLength')\"\n [attr.aria-invalid]=\"password.invalid && password.touched ? true : null\">\n <ng-container *ngIf=\"password.invalid && password.touched\">\n <p class=\"caption status-danger\" *ngIf=\"password.errors?.required\">\n Password is required!\n </p>\n <p class=\"caption status-danger\" *ngIf=\"password.errors?.minlength || password.errors?.maxlength\">\n Password should contain\n from {{ getConfigValue('forms.validation.password.minLength') }}\n to {{ getConfigValue('forms.validation.password.maxLength') }}\n characters\n </p>\n </ng-container>\n </div>\n\n <div class=\"form-control-group\">\n <label class=\"label\" for=\"input-re-password\">Repeat password:</label>\n <input nbInput\n [(ngModel)]=\"user.confirmPassword\"\n #rePass=\"ngModel\"\n type=\"password\"\n id=\"input-re-password\"\n name=\"rePass\"\n placeholder=\"Confirm Password\"\n fullWidth\n fieldSize=\"large\"\n [status]=\"rePass.dirty ? (rePass.invalid || password.value != rePass.value ? 'danger' : 'success') : 'basic'\"\n [required]=\"getConfigValue('forms.validation.password.required')\"\n [attr.aria-invalid]=\"rePass.invalid && rePass.touched ? true : null\">\n <ng-container *ngIf=\"rePass.invalid && rePass.touched\">\n <p class=\"caption status-danger\" *ngIf=\"rePass.errors?.required\">\n Password confirmation is required!\n </p>\n <p class=\"caption status-danger\" *ngIf=\"password.value != rePass.value && !rePass.errors?.required\">\n Password does not match the confirm password.\n </p>\n </ng-container>\n </div>\n\n <div class=\"form-control-group accept-group\" *ngIf=\"getConfigValue('forms.register.terms')\">\n <nb-checkbox name=\"terms\" [(ngModel)]=\"user.terms\" [required]=\"getConfigValue('forms.register.terms')\">\n Agree to <a href=\"#\" target=\"_blank\"><strong>Terms & Conditions</strong></a>\n </nb-checkbox>\n </div>\n\n <button nbButton\n fullWidth\n status=\"primary\"\n size=\"large\"\n [disabled]=\"submitted || !form.valid\"\n [class.btn-pulse]=\"submitted\">\n Register\n </button>\n</form>\n\n<section *ngIf=\"socialLinks && socialLinks.length > 0\" class=\"links\" aria-label=\"Social sign in\">\n or enter with:\n <div class=\"socials\">\n <ng-container *ngFor=\"let socialLink of socialLinks\">\n <a *ngIf=\"socialLink.link\"\n [routerLink]=\"socialLink.link\"\n [attr.target]=\"socialLink.target\"\n [attr.class]=\"socialLink.icon\"\n [class.with-icon]=\"socialLink.icon\">\n <nb-icon *ngIf=\"socialLink.icon; else title\" [icon]=\"socialLink.icon\"></nb-icon>\n <ng-template #title>{{ socialLink.title }}</ng-template>\n </a>\n <a *ngIf=\"socialLink.url\"\n [attr.href]=\"socialLink.url\"\n [attr.target]=\"socialLink.target\"\n [attr.class]=\"socialLink.icon\"\n [class.with-icon]=\"socialLink.icon\">\n <nb-icon *ngIf=\"socialLink.icon; else title\" [icon]=\"socialLink.icon\"></nb-icon>\n <ng-template #title>{{ socialLink.title }}</ng-template>\n </a>\n </ng-container>\n </div>\n</section>\n\n<section class=\"another-action\" aria-label=\"Sign in\">\n Already have an account? <a class=\"text-link\" routerLink=\"../login\">Log in</a>\n</section>\n", styles: ["/**\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */:host .title{margin-bottom:2rem}\n"] }]
2023 }], ctorParameters: function () {
2024 return [{ type: NbAuthService }, { type: undefined, decorators: [{
2025 type: Inject,
2026 args: [NB_AUTH_OPTIONS]
2027 }] }, { type: i0.ChangeDetectorRef }, { type: i2.Router }];
2028 } });
2029
2030/**
2031 * @license
2032 * Copyright Akveo. All Rights Reserved.
2033 * Licensed under the MIT License. See License.txt in the project root for license information.
2034 */
2035class NbLogoutComponent {
2036 constructor(service, options = {}, router) {
2037 this.service = service;
2038 this.options = options;
2039 this.router = router;
2040 this.redirectDelay = 0;
2041 this.strategy = '';
2042 this.redirectDelay = this.getConfigValue('forms.logout.redirectDelay');
2043 this.strategy = this.getConfigValue('forms.logout.strategy');
2044 }
2045 ngOnInit() {
2046 this.logout(this.strategy);
2047 }
2048 logout(strategy) {
2049 this.service.logout(strategy).subscribe((result) => {
2050 const redirect = result.getRedirect();
2051 if (redirect) {
2052 setTimeout(() => {
2053 return this.router.navigateByUrl(redirect);
2054 }, this.redirectDelay);
2055 }
2056 });
2057 }
2058 getConfigValue(key) {
2059 return getDeepFromObject(this.options, key, null);
2060 }
2061}
2062NbLogoutComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbLogoutComponent, deps: [{ token: NbAuthService }, { token: NB_AUTH_OPTIONS }, { token: i2.Router }], target: i0.ɵɵFactoryTarget.Component });
2063NbLogoutComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "13.0.0", type: NbLogoutComponent, selector: "nb-logout", ngImport: i0, template: "<div>Logging out, please wait...</div>\n" });
2064i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbLogoutComponent, decorators: [{
2065 type: Component,
2066 args: [{ selector: 'nb-logout', template: "<div>Logging out, please wait...</div>\n" }]
2067 }], ctorParameters: function () {
2068 return [{ type: NbAuthService }, { type: undefined, decorators: [{
2069 type: Inject,
2070 args: [NB_AUTH_OPTIONS]
2071 }] }, { type: i2.Router }];
2072 } });
2073
2074/**
2075 * @license
2076 * Copyright Akveo. All Rights Reserved.
2077 * Licensed under the MIT License. See License.txt in the project root for license information.
2078 */
2079class NbRequestPasswordComponent {
2080 constructor(service, options = {}, cd, router) {
2081 this.service = service;
2082 this.options = options;
2083 this.cd = cd;
2084 this.router = router;
2085 this.redirectDelay = 0;
2086 this.showMessages = {};
2087 this.strategy = '';
2088 this.submitted = false;
2089 this.errors = [];
2090 this.messages = [];
2091 this.user = {};
2092 this.redirectDelay = this.getConfigValue('forms.requestPassword.redirectDelay');
2093 this.showMessages = this.getConfigValue('forms.requestPassword.showMessages');
2094 this.strategy = this.getConfigValue('forms.requestPassword.strategy');
2095 }
2096 requestPass() {
2097 this.errors = this.messages = [];
2098 this.submitted = true;
2099 this.service.requestPassword(this.strategy, this.user).subscribe((result) => {
2100 this.submitted = false;
2101 if (result.isSuccess()) {
2102 this.messages = result.getMessages();
2103 }
2104 else {
2105 this.errors = result.getErrors();
2106 }
2107 const redirect = result.getRedirect();
2108 if (redirect) {
2109 setTimeout(() => {
2110 return this.router.navigateByUrl(redirect);
2111 }, this.redirectDelay);
2112 }
2113 this.cd.detectChanges();
2114 });
2115 }
2116 getConfigValue(key) {
2117 return getDeepFromObject(this.options, key, null);
2118 }
2119}
2120NbRequestPasswordComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbRequestPasswordComponent, deps: [{ token: NbAuthService }, { token: NB_AUTH_OPTIONS }, { token: i0.ChangeDetectorRef }, { token: i2.Router }], target: i0.ɵɵFactoryTarget.Component });
2121NbRequestPasswordComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "13.0.0", type: NbRequestPasswordComponent, selector: "nb-request-password-page", ngImport: i0, template: "<h1 id=\"title\" class=\"title\">Forgot Password</h1>\n<p class=\"sub-title\">Enter your email address and we\u2019ll send a link to reset your password</p>\n\n<nb-alert *ngIf=\"showMessages.error && errors?.length && !submitted\" outline=\"danger\" role=\"alert\">\n <p class=\"alert-title\"><b>Oh snap!</b></p>\n <ul class=\"alert-message-list\">\n <li *ngFor=\"let error of errors\" class=\"alert-message\">{{ error }}</li>\n </ul>\n</nb-alert>\n\n<nb-alert *ngIf=\"showMessages.success && messages?.length && !submitted\" outline=\"success\" role=\"alert\">\n <p class=\"alert-title\"><b>Hooray!</b></p>\n <ul class=\"alert-message-list\">\n <li *ngFor=\"let message of messages\" class=\"alert-message\">{{ message }}</li>\n </ul>\n</nb-alert>\n\n<form (ngSubmit)=\"requestPass()\" #requestPassForm=\"ngForm\" aria-labelledby=\"title\">\n\n <div class=\"form-control-group\">\n <label class=\"label\" for=\"input-email\">Enter your email address:</label>\n <input nbInput\n [(ngModel)]=\"user.email\"\n #email=\"ngModel\"\n id=\"input-email\"\n name=\"email\"\n pattern=\".+@.+\\..+\"\n placeholder=\"Email address\"\n autofocus\n fullWidth\n fieldSize=\"large\"\n [status]=\"email.dirty ? (email.invalid ? 'danger' : 'success') : 'basic'\"\n [required]=\"getConfigValue('forms.validation.email.required')\"\n [attr.aria-invalid]=\"email.invalid && email.touched ? true : null\">\n <ng-container *ngIf=\"email.invalid && email.touched\">\n <p class=\"caption status-danger\" *ngIf=\"email.errors?.required\">\n Email is required!\n </p>\n <p class=\"caption status-danger\" *ngIf=\"email.errors?.pattern\">\n Email should be the real one!\n </p>\n </ng-container>\n </div>\n\n <button nbButton\n fullWidth\n status=\"primary\"\n size=\"large\"\n [disabled]=\"submitted || !requestPassForm.valid\"\n [class.btn-pulse]=\"submitted\">\n Request password\n </button>\n</form>\n\n<section class=\"sign-in-or-up\" aria-label=\"Sign in or sign up\">\n <p><a class=\"text-link\" routerLink=\"../login\">Back to Log In</a></p>\n <p><a routerLink=\"../register\" class=\"text-link\">Register</a></p>\n</section>\n", styles: ["/**\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */:host .form-group:last-of-type{margin-bottom:3rem}\n"], components: [{ type: i3.NbAlertComponent, selector: "nb-alert", inputs: ["size", "status", "accent", "outline", "closable"], outputs: ["close"] }, { type: i3.NbButtonComponent, selector: "button[nbButton],a[nbButton],input[type=\"button\"][nbButton],input[type=\"submit\"][nbButton]", inputs: ["hero"] }], directives: [{ type: i4.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { type: i4.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { type: i5.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { type: i5.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { type: i5.NgForm, selector: "form:not([ngNoForm]):not([formGroup]),ng-form,[ngForm]", inputs: ["ngFormOptions"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { type: i3.NbInputDirective, selector: "input[nbInput],textarea[nbInput]", inputs: ["fieldSize", "status", "shape", "fullWidth"] }, { type: i5.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { type: i5.PatternValidator, selector: "[pattern][formControlName],[pattern][formControl],[pattern][ngModel]", inputs: ["pattern"] }, { type: i5.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { type: i5.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { type: i5.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { type: i2.RouterLinkWithHref, selector: "a[routerLink],area[routerLink]", inputs: ["target", "queryParams", "fragment", "queryParamsHandling", "preserveFragment", "skipLocationChange", "replaceUrl", "state", "relativeTo", "routerLink"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
2122i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbRequestPasswordComponent, decorators: [{
2123 type: Component,
2124 args: [{ selector: 'nb-request-password-page', changeDetection: ChangeDetectionStrategy.OnPush, template: "<h1 id=\"title\" class=\"title\">Forgot Password</h1>\n<p class=\"sub-title\">Enter your email address and we\u2019ll send a link to reset your password</p>\n\n<nb-alert *ngIf=\"showMessages.error && errors?.length && !submitted\" outline=\"danger\" role=\"alert\">\n <p class=\"alert-title\"><b>Oh snap!</b></p>\n <ul class=\"alert-message-list\">\n <li *ngFor=\"let error of errors\" class=\"alert-message\">{{ error }}</li>\n </ul>\n</nb-alert>\n\n<nb-alert *ngIf=\"showMessages.success && messages?.length && !submitted\" outline=\"success\" role=\"alert\">\n <p class=\"alert-title\"><b>Hooray!</b></p>\n <ul class=\"alert-message-list\">\n <li *ngFor=\"let message of messages\" class=\"alert-message\">{{ message }}</li>\n </ul>\n</nb-alert>\n\n<form (ngSubmit)=\"requestPass()\" #requestPassForm=\"ngForm\" aria-labelledby=\"title\">\n\n <div class=\"form-control-group\">\n <label class=\"label\" for=\"input-email\">Enter your email address:</label>\n <input nbInput\n [(ngModel)]=\"user.email\"\n #email=\"ngModel\"\n id=\"input-email\"\n name=\"email\"\n pattern=\".+@.+\\..+\"\n placeholder=\"Email address\"\n autofocus\n fullWidth\n fieldSize=\"large\"\n [status]=\"email.dirty ? (email.invalid ? 'danger' : 'success') : 'basic'\"\n [required]=\"getConfigValue('forms.validation.email.required')\"\n [attr.aria-invalid]=\"email.invalid && email.touched ? true : null\">\n <ng-container *ngIf=\"email.invalid && email.touched\">\n <p class=\"caption status-danger\" *ngIf=\"email.errors?.required\">\n Email is required!\n </p>\n <p class=\"caption status-danger\" *ngIf=\"email.errors?.pattern\">\n Email should be the real one!\n </p>\n </ng-container>\n </div>\n\n <button nbButton\n fullWidth\n status=\"primary\"\n size=\"large\"\n [disabled]=\"submitted || !requestPassForm.valid\"\n [class.btn-pulse]=\"submitted\">\n Request password\n </button>\n</form>\n\n<section class=\"sign-in-or-up\" aria-label=\"Sign in or sign up\">\n <p><a class=\"text-link\" routerLink=\"../login\">Back to Log In</a></p>\n <p><a routerLink=\"../register\" class=\"text-link\">Register</a></p>\n</section>\n", styles: ["/**\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */:host .form-group:last-of-type{margin-bottom:3rem}\n"] }]
2125 }], ctorParameters: function () {
2126 return [{ type: NbAuthService }, { type: undefined, decorators: [{
2127 type: Inject,
2128 args: [NB_AUTH_OPTIONS]
2129 }] }, { type: i0.ChangeDetectorRef }, { type: i2.Router }];
2130 } });
2131
2132/**
2133 * @license
2134 * Copyright Akveo. All Rights Reserved.
2135 * Licensed under the MIT License. See License.txt in the project root for license information.
2136 */
2137class NbResetPasswordComponent {
2138 constructor(service, options = {}, cd, router) {
2139 this.service = service;
2140 this.options = options;
2141 this.cd = cd;
2142 this.router = router;
2143 this.redirectDelay = 0;
2144 this.showMessages = {};
2145 this.strategy = '';
2146 this.submitted = false;
2147 this.errors = [];
2148 this.messages = [];
2149 this.user = {};
2150 this.redirectDelay = this.getConfigValue('forms.resetPassword.redirectDelay');
2151 this.showMessages = this.getConfigValue('forms.resetPassword.showMessages');
2152 this.strategy = this.getConfigValue('forms.resetPassword.strategy');
2153 }
2154 resetPass() {
2155 this.errors = this.messages = [];
2156 this.submitted = true;
2157 this.service.resetPassword(this.strategy, this.user).subscribe((result) => {
2158 this.submitted = false;
2159 if (result.isSuccess()) {
2160 this.messages = result.getMessages();
2161 }
2162 else {
2163 this.errors = result.getErrors();
2164 }
2165 const redirect = result.getRedirect();
2166 if (redirect) {
2167 setTimeout(() => {
2168 return this.router.navigateByUrl(redirect);
2169 }, this.redirectDelay);
2170 }
2171 this.cd.detectChanges();
2172 });
2173 }
2174 getConfigValue(key) {
2175 return getDeepFromObject(this.options, key, null);
2176 }
2177}
2178NbResetPasswordComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbResetPasswordComponent, deps: [{ token: NbAuthService }, { token: NB_AUTH_OPTIONS }, { token: i0.ChangeDetectorRef }, { token: i2.Router }], target: i0.ɵɵFactoryTarget.Component });
2179NbResetPasswordComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "13.0.0", type: NbResetPasswordComponent, selector: "nb-reset-password-page", ngImport: i0, template: "<h1 id=\"title\" class=\"title\">Change password</h1>\n<p class=\"sub-title\">Please set a new password</p>\n\n<nb-alert *ngIf=\"showMessages.error && errors?.length && !submitted\" outline=\"danger\" role=\"alert\">\n <p class=\"alert-title\"><b>Oh snap!</b></p>\n <ul class=\"alert-message-list\">\n <li *ngFor=\"let error of errors\" class=\"alert-message\">{{ error }}</li>\n </ul>\n</nb-alert>\n\n<nb-alert *ngIf=\"showMessages.success && messages?.length && !submitted\" outline=\"success\" role=\"alert\">\n <p class=\"alert-title\"><b>Hooray!</b></p>\n <ul class=\"alert-message-list\">\n <li *ngFor=\"let message of messages\" class=\"alert-message\">{{ message }}</li>\n </ul>\n</nb-alert>\n\n<form (ngSubmit)=\"resetPass()\" #resetPassForm=\"ngForm\" aria-labelledby=\"title\">\n\n <div class=\"form-control-group\">\n <label class=\"label\" for=\"input-password\">New Password:</label>\n <input nbInput\n [(ngModel)]=\"user.password\"\n #password=\"ngModel\"\n type=\"password\"\n id=\"input-password\"\n name=\"password\"\n class=\"first\"\n placeholder=\"New Password\"\n autofocus\n fullWidth\n fieldSize=\"large\"\n [status]=\"password.dirty ? (password.invalid ? 'danger' : 'success') : 'basic'\"\n [required]=\"getConfigValue('forms.validation.password.required')\"\n [minlength]=\"getConfigValue('forms.validation.password.minLength')\"\n [maxlength]=\"getConfigValue('forms.validation.password.maxLength')\"\n [attr.aria-invalid]=\"password.invalid && password.touched ? true : null\">\n <ng-container *ngIf=\"password.invalid && password.touched\">\n <p class=\"caption status-danger\" *ngIf=\"password.errors?.required\">\n Password is required!\n </p>\n <p class=\"caption status-danger\" *ngIf=\"password.errors?.minlength || password.errors?.maxlength\">\n Password should contains\n from {{getConfigValue('forms.validation.password.minLength')}}\n to {{getConfigValue('forms.validation.password.maxLength')}}\n characters\n </p>\n </ng-container>\n </div>\n\n <div class=\"form-group\">\n <label class=\"label\" for=\"input-re-password\">Confirm Password:</label>\n <input nbInput\n [(ngModel)]=\"user.confirmPassword\"\n #rePass=\"ngModel\"\n id=\"input-re-password\"\n name=\"rePass\"\n type=\"password\"\n class=\"last\"\n placeholder=\"Confirm Password\"\n fullWidth\n fieldSize=\"large\"\n [status]=\"rePass.touched\n ? (rePass.invalid || password.value != rePass.value ? 'danger' : 'success')\n : 'basic'\"\n [required]=\"getConfigValue('forms.validation.password.required')\"\n [attr.aria-invalid]=\"rePass.invalid && rePass.touched ? true : null\">\n <ng-container *ngIf=\"rePass.touched\">\n <p class=\"caption status-danger\" *ngIf=\"rePass.invalid && rePass.errors?.required\">\n Password confirmation is required!\n </p>\n <p class=\"caption status-danger\" *ngIf=\"password.value != rePass.value && !rePass.errors?.required\">\n Password does not match the confirm password.\n </p>\n </ng-container>\n </div>\n\n <button nbButton\n status=\"primary\"\n fullWidth\n size=\"large\"\n [disabled]=\"submitted || !resetPassForm.valid\"\n [class.btn-pulse]=\"submitted\">\n Change password\n </button>\n</form>\n\n<section class=\"sign-in-or-up\" aria-label=\"Sign in or sign up\">\n <p><a class=\"text-link\" routerLink=\"../login\">Back to Log In</a></p>\n <p><a class=\"text-link\" routerLink=\"../register\">Register</a></p>\n</section>\n", styles: ["/**\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */:host .form-group:last-of-type{margin-bottom:3rem}\n"], components: [{ type: i3.NbAlertComponent, selector: "nb-alert", inputs: ["size", "status", "accent", "outline", "closable"], outputs: ["close"] }, { type: i3.NbButtonComponent, selector: "button[nbButton],a[nbButton],input[type=\"button\"][nbButton],input[type=\"submit\"][nbButton]", inputs: ["hero"] }], directives: [{ type: i4.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { type: i4.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { type: i5.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { type: i5.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { type: i5.NgForm, selector: "form:not([ngNoForm]):not([formGroup]),ng-form,[ngForm]", inputs: ["ngFormOptions"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { type: i3.NbInputDirective, selector: "input[nbInput],textarea[nbInput]", inputs: ["fieldSize", "status", "shape", "fullWidth"] }, { type: i5.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { type: i5.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { type: i5.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { type: i5.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { type: i5.MinLengthValidator, selector: "[minlength][formControlName],[minlength][formControl],[minlength][ngModel]", inputs: ["minlength"] }, { type: i5.MaxLengthValidator, selector: "[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]", inputs: ["maxlength"] }, { type: i2.RouterLinkWithHref, selector: "a[routerLink],area[routerLink]", inputs: ["target", "queryParams", "fragment", "queryParamsHandling", "preserveFragment", "skipLocationChange", "replaceUrl", "state", "relativeTo", "routerLink"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
2180i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbResetPasswordComponent, decorators: [{
2181 type: Component,
2182 args: [{ selector: 'nb-reset-password-page', changeDetection: ChangeDetectionStrategy.OnPush, template: "<h1 id=\"title\" class=\"title\">Change password</h1>\n<p class=\"sub-title\">Please set a new password</p>\n\n<nb-alert *ngIf=\"showMessages.error && errors?.length && !submitted\" outline=\"danger\" role=\"alert\">\n <p class=\"alert-title\"><b>Oh snap!</b></p>\n <ul class=\"alert-message-list\">\n <li *ngFor=\"let error of errors\" class=\"alert-message\">{{ error }}</li>\n </ul>\n</nb-alert>\n\n<nb-alert *ngIf=\"showMessages.success && messages?.length && !submitted\" outline=\"success\" role=\"alert\">\n <p class=\"alert-title\"><b>Hooray!</b></p>\n <ul class=\"alert-message-list\">\n <li *ngFor=\"let message of messages\" class=\"alert-message\">{{ message }}</li>\n </ul>\n</nb-alert>\n\n<form (ngSubmit)=\"resetPass()\" #resetPassForm=\"ngForm\" aria-labelledby=\"title\">\n\n <div class=\"form-control-group\">\n <label class=\"label\" for=\"input-password\">New Password:</label>\n <input nbInput\n [(ngModel)]=\"user.password\"\n #password=\"ngModel\"\n type=\"password\"\n id=\"input-password\"\n name=\"password\"\n class=\"first\"\n placeholder=\"New Password\"\n autofocus\n fullWidth\n fieldSize=\"large\"\n [status]=\"password.dirty ? (password.invalid ? 'danger' : 'success') : 'basic'\"\n [required]=\"getConfigValue('forms.validation.password.required')\"\n [minlength]=\"getConfigValue('forms.validation.password.minLength')\"\n [maxlength]=\"getConfigValue('forms.validation.password.maxLength')\"\n [attr.aria-invalid]=\"password.invalid && password.touched ? true : null\">\n <ng-container *ngIf=\"password.invalid && password.touched\">\n <p class=\"caption status-danger\" *ngIf=\"password.errors?.required\">\n Password is required!\n </p>\n <p class=\"caption status-danger\" *ngIf=\"password.errors?.minlength || password.errors?.maxlength\">\n Password should contains\n from {{getConfigValue('forms.validation.password.minLength')}}\n to {{getConfigValue('forms.validation.password.maxLength')}}\n characters\n </p>\n </ng-container>\n </div>\n\n <div class=\"form-group\">\n <label class=\"label\" for=\"input-re-password\">Confirm Password:</label>\n <input nbInput\n [(ngModel)]=\"user.confirmPassword\"\n #rePass=\"ngModel\"\n id=\"input-re-password\"\n name=\"rePass\"\n type=\"password\"\n class=\"last\"\n placeholder=\"Confirm Password\"\n fullWidth\n fieldSize=\"large\"\n [status]=\"rePass.touched\n ? (rePass.invalid || password.value != rePass.value ? 'danger' : 'success')\n : 'basic'\"\n [required]=\"getConfigValue('forms.validation.password.required')\"\n [attr.aria-invalid]=\"rePass.invalid && rePass.touched ? true : null\">\n <ng-container *ngIf=\"rePass.touched\">\n <p class=\"caption status-danger\" *ngIf=\"rePass.invalid && rePass.errors?.required\">\n Password confirmation is required!\n </p>\n <p class=\"caption status-danger\" *ngIf=\"password.value != rePass.value && !rePass.errors?.required\">\n Password does not match the confirm password.\n </p>\n </ng-container>\n </div>\n\n <button nbButton\n status=\"primary\"\n fullWidth\n size=\"large\"\n [disabled]=\"submitted || !resetPassForm.valid\"\n [class.btn-pulse]=\"submitted\">\n Change password\n </button>\n</form>\n\n<section class=\"sign-in-or-up\" aria-label=\"Sign in or sign up\">\n <p><a class=\"text-link\" routerLink=\"../login\">Back to Log In</a></p>\n <p><a class=\"text-link\" routerLink=\"../register\">Register</a></p>\n</section>\n", styles: ["/**\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */:host .form-group:last-of-type{margin-bottom:3rem}\n"] }]
2183 }], ctorParameters: function () {
2184 return [{ type: NbAuthService }, { type: undefined, decorators: [{
2185 type: Inject,
2186 args: [NB_AUTH_OPTIONS]
2187 }] }, { type: i0.ChangeDetectorRef }, { type: i2.Router }];
2188 } });
2189
2190function nbStrategiesFactory(options, injector) {
2191 const strategies = [];
2192 options.strategies
2193 .forEach(([strategyClass, strategyOptions]) => {
2194 const strategy = injector.get(strategyClass);
2195 strategy.setOptions(strategyOptions);
2196 strategies.push(strategy);
2197 });
2198 return strategies;
2199}
2200function nbTokensFactory(strategies) {
2201 const tokens = [];
2202 strategies
2203 .forEach((strategy) => {
2204 tokens.push(strategy.getOption('token.class'));
2205 });
2206 return tokens;
2207}
2208function nbOptionsFactory(options) {
2209 return deepExtend(defaultAuthOptions, options);
2210}
2211function nbNoOpInterceptorFilter(req) {
2212 return true;
2213}
2214class NbAuthModule {
2215 static forRoot(nbAuthOptions) {
2216 return {
2217 ngModule: NbAuthModule,
2218 providers: [
2219 { provide: NB_AUTH_USER_OPTIONS, useValue: nbAuthOptions },
2220 { provide: NB_AUTH_OPTIONS, useFactory: nbOptionsFactory, deps: [NB_AUTH_USER_OPTIONS] },
2221 { provide: NB_AUTH_STRATEGIES, useFactory: nbStrategiesFactory, deps: [NB_AUTH_OPTIONS, Injector] },
2222 { provide: NB_AUTH_TOKENS, useFactory: nbTokensFactory, deps: [NB_AUTH_STRATEGIES] },
2223 { provide: NB_AUTH_FALLBACK_TOKEN, useValue: NbAuthSimpleToken },
2224 { provide: NB_AUTH_INTERCEPTOR_HEADER, useValue: 'Authorization' },
2225 { provide: NB_AUTH_TOKEN_INTERCEPTOR_FILTER, useValue: nbNoOpInterceptorFilter },
2226 { provide: NbTokenStorage, useClass: NbTokenLocalStorage },
2227 NbAuthTokenParceler,
2228 NbAuthService,
2229 NbTokenService,
2230 NbDummyAuthStrategy,
2231 NbPasswordAuthStrategy,
2232 NbOAuth2AuthStrategy,
2233 ],
2234 };
2235 }
2236}
2237NbAuthModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
2238NbAuthModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthModule, declarations: [NbAuthComponent,
2239 NbAuthBlockComponent,
2240 NbLoginComponent,
2241 NbRegisterComponent,
2242 NbRequestPasswordComponent,
2243 NbResetPasswordComponent,
2244 NbLogoutComponent], imports: [CommonModule,
2245 NbLayoutModule,
2246 NbCardModule,
2247 NbCheckboxModule,
2248 NbAlertModule,
2249 NbInputModule,
2250 NbButtonModule,
2251 RouterModule,
2252 FormsModule,
2253 NbIconModule], exports: [NbAuthComponent,
2254 NbAuthBlockComponent,
2255 NbLoginComponent,
2256 NbRegisterComponent,
2257 NbRequestPasswordComponent,
2258 NbResetPasswordComponent,
2259 NbLogoutComponent] });
2260NbAuthModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthModule, imports: [[
2261 CommonModule,
2262 NbLayoutModule,
2263 NbCardModule,
2264 NbCheckboxModule,
2265 NbAlertModule,
2266 NbInputModule,
2267 NbButtonModule,
2268 RouterModule,
2269 FormsModule,
2270 NbIconModule,
2271 ]] });
2272i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthModule, decorators: [{
2273 type: NgModule,
2274 args: [{
2275 imports: [
2276 CommonModule,
2277 NbLayoutModule,
2278 NbCardModule,
2279 NbCheckboxModule,
2280 NbAlertModule,
2281 NbInputModule,
2282 NbButtonModule,
2283 RouterModule,
2284 FormsModule,
2285 NbIconModule,
2286 ],
2287 declarations: [
2288 NbAuthComponent,
2289 NbAuthBlockComponent,
2290 NbLoginComponent,
2291 NbRegisterComponent,
2292 NbRequestPasswordComponent,
2293 NbResetPasswordComponent,
2294 NbLogoutComponent,
2295 ],
2296 exports: [
2297 NbAuthComponent,
2298 NbAuthBlockComponent,
2299 NbLoginComponent,
2300 NbRegisterComponent,
2301 NbRequestPasswordComponent,
2302 NbResetPasswordComponent,
2303 NbLogoutComponent,
2304 ],
2305 }]
2306 }] });
2307
2308const routes = [
2309 {
2310 path: 'auth',
2311 component: NbAuthComponent,
2312 children: [
2313 {
2314 path: '',
2315 component: NbLoginComponent,
2316 },
2317 {
2318 path: 'login',
2319 component: NbLoginComponent,
2320 },
2321 {
2322 path: 'register',
2323 component: NbRegisterComponent,
2324 },
2325 {
2326 path: 'logout',
2327 component: NbLogoutComponent,
2328 },
2329 {
2330 path: 'request-password',
2331 component: NbRequestPasswordComponent,
2332 },
2333 {
2334 path: 'reset-password',
2335 component: NbResetPasswordComponent,
2336 },
2337 ],
2338 },
2339];
2340
2341class NbAuthJWTInterceptor {
2342 constructor(injector, filter) {
2343 this.injector = injector;
2344 this.filter = filter;
2345 }
2346 intercept(req, next) {
2347 // do not intercept request whose urls are filtered by the injected filter
2348 if (!this.filter(req)) {
2349 return this.authService.isAuthenticatedOrRefresh()
2350 .pipe(switchMap(authenticated => {
2351 if (authenticated) {
2352 return this.authService.getToken().pipe(switchMap((token) => {
2353 const JWT = `Bearer ${token.getValue()}`;
2354 req = req.clone({
2355 setHeaders: {
2356 Authorization: JWT,
2357 },
2358 });
2359 return next.handle(req);
2360 }));
2361 }
2362 else {
2363 // Request is sent to server without authentication so that the client code
2364 // receives the 401/403 error and can act as desired ('session expired', redirect to login, aso)
2365 return next.handle(req);
2366 }
2367 }));
2368 }
2369 else {
2370 return next.handle(req);
2371 }
2372 }
2373 get authService() {
2374 return this.injector.get(NbAuthService);
2375 }
2376}
2377NbAuthJWTInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthJWTInterceptor, deps: [{ token: i0.Injector }, { token: NB_AUTH_TOKEN_INTERCEPTOR_FILTER }], target: i0.ɵɵFactoryTarget.Injectable });
2378NbAuthJWTInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthJWTInterceptor });
2379i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthJWTInterceptor, decorators: [{
2380 type: Injectable
2381 }], ctorParameters: function () {
2382 return [{ type: i0.Injector }, { type: undefined, decorators: [{
2383 type: Inject,
2384 args: [NB_AUTH_TOKEN_INTERCEPTOR_FILTER]
2385 }] }];
2386 } });
2387
2388class NbAuthSimpleInterceptor {
2389 constructor(injector, headerName = 'Authorization') {
2390 this.injector = injector;
2391 this.headerName = headerName;
2392 }
2393 intercept(req, next) {
2394 return this.authService.getToken().pipe(switchMap((token) => {
2395 if (token && token.getValue()) {
2396 req = req.clone({
2397 setHeaders: {
2398 [this.headerName]: token.getValue(),
2399 },
2400 });
2401 }
2402 return next.handle(req);
2403 }));
2404 }
2405 get authService() {
2406 return this.injector.get(NbAuthService);
2407 }
2408}
2409NbAuthSimpleInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthSimpleInterceptor, deps: [{ token: i0.Injector }, { token: NB_AUTH_INTERCEPTOR_HEADER }], target: i0.ɵɵFactoryTarget.Injectable });
2410NbAuthSimpleInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthSimpleInterceptor });
2411i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.0", ngImport: i0, type: NbAuthSimpleInterceptor, decorators: [{
2412 type: Injectable
2413 }], ctorParameters: function () {
2414 return [{ type: i0.Injector }, { type: undefined, decorators: [{
2415 type: Inject,
2416 args: [NB_AUTH_INTERCEPTOR_HEADER]
2417 }] }];
2418 } });
2419
2420class NbUser {
2421 constructor(id, email, password, rememberMe, terms, confirmPassword, fullName) {
2422 this.id = id;
2423 this.email = email;
2424 this.password = password;
2425 this.rememberMe = rememberMe;
2426 this.terms = terms;
2427 this.confirmPassword = confirmPassword;
2428 this.fullName = fullName;
2429 }
2430}
2431
2432/**
2433 * @license
2434 * Copyright Akveo. All Rights Reserved.
2435 * Licensed under the MIT License. See License.txt in the project root for license information.
2436 */
2437
2438/**
2439 * Generated bundle index. Do not edit.
2440 */
2441
2442export { NB_AUTH_FALLBACK_TOKEN, NB_AUTH_INTERCEPTOR_HEADER, NB_AUTH_OPTIONS, NB_AUTH_STRATEGIES, NB_AUTH_TOKENS, NB_AUTH_TOKEN_INTERCEPTOR_FILTER, NB_AUTH_USER_OPTIONS, NbAuthBlockComponent, NbAuthComponent, NbAuthEmptyTokenError, NbAuthIllegalJWTTokenError, NbAuthIllegalTokenError, NbAuthJWTInterceptor, NbAuthJWTToken, NbAuthModule, NbAuthOAuth2JWTToken, NbAuthOAuth2Token, NbAuthResult, NbAuthService, NbAuthSimpleInterceptor, NbAuthSimpleToken, NbAuthStrategy, NbAuthStrategyOptions, NbAuthToken, NbAuthTokenNotFoundError, NbAuthTokenParceler, NbDummyAuthStrategy, NbDummyAuthStrategyOptions, NbLoginComponent, NbLogoutComponent, NbOAuth2AuthStrategy, NbOAuth2AuthStrategyOptions, NbOAuth2ClientAuthMethod, NbOAuth2GrantType, NbOAuth2ResponseType, NbPasswordAuthStrategy, NbPasswordAuthStrategyOptions, NbRegisterComponent, NbRequestPasswordComponent, NbResetPasswordComponent, NbTokenLocalStorage, NbTokenService, NbTokenStorage, NbUser, auth2StrategyOptions, b64DecodeUnicode, b64decode, decodeJwtPayload, deepExtend, defaultAuthOptions, dummyStrategyOptions, getDeepFromObject, nbAuthCreateToken, nbNoOpInterceptorFilter, nbOptionsFactory, nbStrategiesFactory, nbTokensFactory, passwordStrategyOptions, routes, urlBase64Decode };