UNPKG

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