UNPKG

6.21 kBJavaScriptView Raw
1/**
2 * @license
3 * Copyright Akveo. All Rights Reserved.
4 * Licensed under the MIT License. See License.txt in the project root for license information.
5 */
6import { Inject, Injectable } from '@angular/core';
7import { of as observableOf } from 'rxjs';
8import { switchMap, map } from 'rxjs/operators';
9import { NB_AUTH_STRATEGIES } from '../auth.options';
10import { NbTokenService } from './token/token.service';
11/**
12 * Common authentication service.
13 * Should be used to as an interlayer between UI Components and Auth Strategy.
14 */
15export class NbAuthService {
16 constructor(tokenService, strategies) {
17 this.tokenService = tokenService;
18 this.strategies = strategies;
19 }
20 /**
21 * Retrieves current authenticated token stored
22 * @returns {Observable<any>}
23 */
24 getToken() {
25 return this.tokenService.get();
26 }
27 /**
28 * Returns true if auth token is present in the token storage
29 * @returns {Observable<boolean>}
30 */
31 isAuthenticated() {
32 return this.getToken()
33 .pipe(map((token) => token.isValid()));
34 }
35 /**
36 * Returns true if valid auth token is present in the token storage.
37 * If not, calls the strategy refreshToken, and returns isAuthenticated() if success, false otherwise
38 * @returns {Observable<boolean>}
39 */
40 isAuthenticatedOrRefresh() {
41 return this.getToken()
42 .pipe(switchMap(token => {
43 if (token.getValue() && !token.isValid()) {
44 return this.refreshToken(token.getOwnerStrategyName(), token)
45 .pipe(switchMap(res => {
46 if (res.isSuccess()) {
47 return this.isAuthenticated();
48 }
49 else {
50 return observableOf(false);
51 }
52 }));
53 }
54 else {
55 return observableOf(token.isValid());
56 }
57 }));
58 }
59 /**
60 * Returns tokens stream
61 * @returns {Observable<NbAuthSimpleToken>}
62 */
63 onTokenChange() {
64 return this.tokenService.tokenChange();
65 }
66 /**
67 * Returns authentication status stream
68 * @returns {Observable<boolean>}
69 */
70 onAuthenticationChange() {
71 return this.onTokenChange()
72 .pipe(map((token) => token.isValid()));
73 }
74 /**
75 * Authenticates with the selected strategy
76 * Stores received token in the token storage
77 *
78 * Example:
79 * authenticate('email', {email: 'email@example.com', password: 'test'})
80 *
81 * @param strategyName
82 * @param data
83 * @returns {Observable<NbAuthResult>}
84 */
85 authenticate(strategyName, data) {
86 return this.getStrategy(strategyName).authenticate(data)
87 .pipe(switchMap((result) => {
88 return this.processResultToken(result);
89 }));
90 }
91 /**
92 * Registers with the selected strategy
93 * Stores received token in the token storage
94 *
95 * Example:
96 * register('email', {email: 'email@example.com', name: 'Some Name', password: 'test'})
97 *
98 * @param strategyName
99 * @param data
100 * @returns {Observable<NbAuthResult>}
101 */
102 register(strategyName, data) {
103 return this.getStrategy(strategyName).register(data)
104 .pipe(switchMap((result) => {
105 return this.processResultToken(result);
106 }));
107 }
108 /**
109 * Sign outs with the selected strategy
110 * Removes token from the token storage
111 *
112 * Example:
113 * logout('email')
114 *
115 * @param strategyName
116 * @returns {Observable<NbAuthResult>}
117 */
118 logout(strategyName) {
119 return this.getStrategy(strategyName).logout()
120 .pipe(switchMap((result) => {
121 if (result.isSuccess()) {
122 this.tokenService.clear()
123 .pipe(map(() => result));
124 }
125 return observableOf(result);
126 }));
127 }
128 /**
129 * Sends forgot password request to the selected strategy
130 *
131 * Example:
132 * requestPassword('email', {email: 'email@example.com'})
133 *
134 * @param strategyName
135 * @param data
136 * @returns {Observable<NbAuthResult>}
137 */
138 requestPassword(strategyName, data) {
139 return this.getStrategy(strategyName).requestPassword(data);
140 }
141 /**
142 * Tries to reset password with the selected strategy
143 *
144 * Example:
145 * resetPassword('email', {newPassword: 'test'})
146 *
147 * @param strategyName
148 * @param data
149 * @returns {Observable<NbAuthResult>}
150 */
151 resetPassword(strategyName, data) {
152 return this.getStrategy(strategyName).resetPassword(data);
153 }
154 /**
155 * Sends a refresh token request
156 * Stores received token in the token storage
157 *
158 * Example:
159 * refreshToken('email', {token: token})
160 *
161 * @param {string} strategyName
162 * @param data
163 * @returns {Observable<NbAuthResult>}
164 */
165 refreshToken(strategyName, data) {
166 return this.getStrategy(strategyName).refreshToken(data)
167 .pipe(switchMap((result) => {
168 return this.processResultToken(result);
169 }));
170 }
171 /**
172 * Get registered strategy by name
173 *
174 * Example:
175 * getStrategy('email')
176 *
177 * @param {string} provider
178 * @returns {NbAbstractAuthProvider}
179 */
180 getStrategy(strategyName) {
181 const found = this.strategies.find((strategy) => strategy.getName() === strategyName);
182 if (!found) {
183 throw new TypeError(`There is no Auth Strategy registered under '${strategyName}' name`);
184 }
185 return found;
186 }
187 processResultToken(result) {
188 if (result.isSuccess() && result.getToken()) {
189 return this.tokenService.set(result.getToken())
190 .pipe(map((token) => {
191 return result;
192 }));
193 }
194 return observableOf(result);
195 }
196}
197NbAuthService.decorators = [
198 { type: Injectable }
199];
200NbAuthService.ctorParameters = () => [
201 { type: NbTokenService },
202 { type: undefined, decorators: [{ type: Inject, args: [NB_AUTH_STRATEGIES,] }] }
203];
204//# sourceMappingURL=auth.service.js.map
\No newline at end of file