UNPKG

8.43 kBJavaScriptView Raw
1import { urlBase64Decode } from '../../helpers';
2export class NbAuthToken {
3 constructor() {
4 this.payload = null;
5 }
6 getName() {
7 return this.constructor.NAME;
8 }
9 getPayload() {
10 return this.payload;
11 }
12}
13export class NbAuthTokenNotFoundError extends Error {
14 constructor(message) {
15 super(message);
16 Object.setPrototypeOf(this, new.target.prototype);
17 }
18}
19export class NbAuthIllegalTokenError extends Error {
20 constructor(message) {
21 super(message);
22 Object.setPrototypeOf(this, new.target.prototype);
23 }
24}
25export class NbAuthEmptyTokenError extends NbAuthIllegalTokenError {
26 constructor(message) {
27 super(message);
28 Object.setPrototypeOf(this, new.target.prototype);
29 }
30}
31export class NbAuthIllegalJWTTokenError extends NbAuthIllegalTokenError {
32 constructor(message) {
33 super(message);
34 Object.setPrototypeOf(this, new.target.prototype);
35 }
36}
37export function nbAuthCreateToken(tokenClass, token, ownerStrategyName, createdAt) {
38 return new tokenClass(token, ownerStrategyName, createdAt);
39}
40export function decodeJwtPayload(payload) {
41 if (payload.length === 0) {
42 throw new NbAuthEmptyTokenError('Cannot extract from an empty payload.');
43 }
44 const parts = payload.split('.');
45 if (parts.length !== 3) {
46 throw new NbAuthIllegalJWTTokenError(`The payload ${payload} is not valid JWT payload and must consist of three parts.`);
47 }
48 let decoded;
49 try {
50 decoded = urlBase64Decode(parts[1]);
51 }
52 catch (e) {
53 throw new NbAuthIllegalJWTTokenError(`The payload ${payload} is not valid JWT payload and cannot be parsed.`);
54 }
55 if (!decoded) {
56 throw new NbAuthIllegalJWTTokenError(`The payload ${payload} is not valid JWT payload and cannot be decoded.`);
57 }
58 return JSON.parse(decoded);
59}
60/**
61 * Wrapper for simple (text) token
62 */
63export class NbAuthSimpleToken extends NbAuthToken {
64 constructor(token, ownerStrategyName, createdAt) {
65 super();
66 this.token = token;
67 this.ownerStrategyName = ownerStrategyName;
68 this.createdAt = createdAt;
69 try {
70 this.parsePayload();
71 }
72 catch (err) {
73 if (!(err instanceof NbAuthTokenNotFoundError)) {
74 // token is present but has got a problem, including illegal
75 throw err;
76 }
77 }
78 this.createdAt = this.prepareCreatedAt(createdAt);
79 }
80 parsePayload() {
81 this.payload = null;
82 }
83 prepareCreatedAt(date) {
84 return date ? date : new Date();
85 }
86 /**
87 * Returns the token's creation date
88 * @returns {Date}
89 */
90 getCreatedAt() {
91 return this.createdAt;
92 }
93 /**
94 * Returns the token value
95 * @returns string
96 */
97 getValue() {
98 return this.token;
99 }
100 getOwnerStrategyName() {
101 return this.ownerStrategyName;
102 }
103 /**
104 * Is non empty and valid
105 * @returns {boolean}
106 */
107 isValid() {
108 return !!this.getValue();
109 }
110 /**
111 * Validate value and convert to string, if value is not valid return empty string
112 * @returns {string}
113 */
114 toString() {
115 return !!this.token ? this.token : '';
116 }
117}
118NbAuthSimpleToken.NAME = 'nb:auth:simple:token';
119/**
120 * Wrapper for JWT token with additional methods.
121 */
122export class NbAuthJWTToken extends NbAuthSimpleToken {
123 /**
124 * for JWT token, the iat (issued at) field of the token payload contains the creation Date
125 */
126 prepareCreatedAt(date) {
127 const decoded = this.getPayload();
128 return decoded && decoded.iat ? new Date(Number(decoded.iat) * 1000) : super.prepareCreatedAt(date);
129 }
130 /**
131 * Returns payload object
132 * @returns any
133 */
134 parsePayload() {
135 if (!this.token) {
136 throw new NbAuthTokenNotFoundError('Token not found. ');
137 }
138 this.payload = decodeJwtPayload(this.token);
139 }
140 /**
141 * Returns expiration date
142 * @returns Date
143 */
144 getTokenExpDate() {
145 const decoded = this.getPayload();
146 if (decoded && !decoded.hasOwnProperty('exp')) {
147 return null;
148 }
149 const date = new Date(0);
150 date.setUTCSeconds(decoded.exp); // 'cause jwt token are set in seconds
151 return date;
152 }
153 /**
154 * Is data expired
155 * @returns {boolean}
156 */
157 isValid() {
158 return super.isValid() && (!this.getTokenExpDate() || new Date() < this.getTokenExpDate());
159 }
160}
161NbAuthJWTToken.NAME = 'nb:auth:jwt:token';
162const prepareOAuth2Token = (data) => {
163 if (typeof data === 'string') {
164 try {
165 return JSON.parse(data);
166 }
167 catch (e) { }
168 }
169 return data;
170};
171const ɵ0 = prepareOAuth2Token;
172/**
173 * Wrapper for OAuth2 token whose access_token is a JWT Token
174 */
175export class NbAuthOAuth2Token extends NbAuthSimpleToken {
176 constructor(data = {}, ownerStrategyName, createdAt) {
177 // we may get it as string when retrieving from a storage
178 super(prepareOAuth2Token(data), ownerStrategyName, createdAt);
179 }
180 /**
181 * Returns the token value
182 * @returns string
183 */
184 getValue() {
185 return this.token.access_token;
186 }
187 /**
188 * Returns the refresh token
189 * @returns string
190 */
191 getRefreshToken() {
192 return this.token.refresh_token;
193 }
194 /**
195 * put refreshToken in the token payload
196 * @param refreshToken
197 */
198 setRefreshToken(refreshToken) {
199 this.token.refresh_token = refreshToken;
200 }
201 /**
202 * Parses token payload
203 * @returns any
204 */
205 parsePayload() {
206 if (!this.token) {
207 throw new NbAuthTokenNotFoundError('Token not found.');
208 }
209 else {
210 if (!Object.keys(this.token).length) {
211 throw new NbAuthEmptyTokenError('Cannot extract payload from an empty token.');
212 }
213 }
214 this.payload = this.token;
215 }
216 /**
217 * Returns the token type
218 * @returns string
219 */
220 getType() {
221 return this.token.token_type;
222 }
223 /**
224 * Is data expired
225 * @returns {boolean}
226 */
227 isValid() {
228 return super.isValid() && (!this.getTokenExpDate() || new Date() < this.getTokenExpDate());
229 }
230 /**
231 * Returns expiration date
232 * @returns Date
233 */
234 getTokenExpDate() {
235 if (!this.token.hasOwnProperty('expires_in')) {
236 return null;
237 }
238 return new Date(this.createdAt.getTime() + Number(this.token.expires_in) * 1000);
239 }
240 /**
241 * Convert to string
242 * @returns {string}
243 */
244 toString() {
245 return JSON.stringify(this.token);
246 }
247}
248NbAuthOAuth2Token.NAME = 'nb:auth:oauth2:token';
249/**
250 * Wrapper for OAuth2 token embedding JWT tokens
251 */
252export class NbAuthOAuth2JWTToken extends NbAuthOAuth2Token {
253 parsePayload() {
254 super.parsePayload();
255 this.parseAccessTokenPayload();
256 }
257 parseAccessTokenPayload() {
258 const accessToken = this.getValue();
259 if (!accessToken) {
260 throw new NbAuthTokenNotFoundError('access_token key not found.');
261 }
262 this.accessTokenPayload = decodeJwtPayload(accessToken);
263 }
264 /**
265 * Returns access token payload
266 * @returns any
267 */
268 getAccessTokenPayload() {
269 return this.accessTokenPayload;
270 }
271 /**
272 * for Oauth2 JWT token, the iat (issued at) field of the access_token payload
273 */
274 prepareCreatedAt(date) {
275 const payload = this.accessTokenPayload;
276 return payload && payload.iat ? new Date(Number(payload.iat) * 1000) : super.prepareCreatedAt(date);
277 }
278 /**
279 * Is token valid
280 * @returns {boolean}
281 */
282 isValid() {
283 return this.accessTokenPayload && super.isValid();
284 }
285 /**
286 * Returns expiration date :
287 * - exp if set,
288 * - super.getExpDate() otherwise
289 * @returns Date
290 */
291 getTokenExpDate() {
292 if (this.accessTokenPayload && this.accessTokenPayload.hasOwnProperty('exp')) {
293 const date = new Date(0);
294 date.setUTCSeconds(this.accessTokenPayload.exp);
295 return date;
296 }
297 else {
298 return super.getTokenExpDate();
299 }
300 }
301}
302NbAuthOAuth2JWTToken.NAME = 'nb:auth:oauth2:jwt:token';
303export { ɵ0 };
304//# sourceMappingURL=token.js.map
\No newline at end of file