@nebular/auth
Version:
@nebular/auth
1,374 lines (1,357 loc) • 119 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common'), require('@angular/router'), require('@angular/forms'), require('@nebular/theme'), require('rxjs'), require('rxjs/operators'), require('tslib'), require('@angular/common/http')) :
typeof define === 'function' && define.amd ? define(['exports', '@angular/core', '@angular/common', '@angular/router', '@angular/forms', '@nebular/theme', 'rxjs', 'rxjs/operators', 'tslib', '@angular/common/http'], factory) :
(factory((global.nb = global.nb || {}, global.nb.auth = global.nb.auth || {}),global.ng.core,global.ng.common,global.ng.router,global.ng.forms,global.nb.theme,global.Rx,global.Rx.operators,global.tslib,global.ng.common.http));
}(this, (function (exports,_angular_core,_angular_common,_angular_router,_angular_forms,_nebular_theme,rxjs,rxjs_operators,tslib,_angular_common_http) { 'use strict';
var socialLinks = [];
var defaultAuthOptions = {
strategies: [],
forms: {
login: {
redirectDelay: 500,
strategy: 'email',
rememberMe: true,
showMessages: {
success: true,
error: true,
},
socialLinks: socialLinks, // social links at the bottom of a page
},
register: {
redirectDelay: 500,
strategy: 'email',
showMessages: {
success: true,
error: true,
},
terms: true,
socialLinks: socialLinks,
},
requestPassword: {
redirectDelay: 500,
strategy: 'email',
showMessages: {
success: true,
error: true,
},
socialLinks: socialLinks,
},
resetPassword: {
redirectDelay: 500,
strategy: 'email',
showMessages: {
success: true,
error: true,
},
socialLinks: socialLinks,
},
logout: {
redirectDelay: 500,
strategy: 'email',
},
validation: {
password: {
required: true,
minLength: 4,
maxLength: 50,
},
email: {
required: true,
},
fullName: {
required: false,
minLength: 4,
maxLength: 50,
},
},
},
};
var NB_AUTH_OPTIONS = new _angular_core.InjectionToken('Nebular Auth Options');
var NB_AUTH_USER_OPTIONS = new _angular_core.InjectionToken('Nebular User Auth Options');
var NB_AUTH_STRATEGIES = new _angular_core.InjectionToken('Nebular Auth Strategies');
var NB_AUTH_TOKENS = new _angular_core.InjectionToken('Nebular Auth Tokens');
var NB_AUTH_INTERCEPTOR_HEADER = new _angular_core.InjectionToken('Nebular Simple Interceptor Header');
var NB_AUTH_TOKEN_INTERCEPTOR_FILTER = new _angular_core.InjectionToken('Nebular Interceptor Filter');
/**
* Extending object that entered in first argument.
*
* Returns extended object or false if have no target object or incorrect type.
*
* If you wish to clone source object (without modify it), just use empty new
* object as first argument, like this:
* deepExtend({}, yourObj_1, [yourObj_N]);
*/
var deepExtend = function () {
var objects = [];
for (var _i = 0; _i < arguments.length; _i++) {
objects[_i] = arguments[_i];
}
if (arguments.length < 1 || typeof arguments[0] !== 'object') {
return false;
}
if (arguments.length < 2) {
return arguments[0];
}
var target = arguments[0];
// convert arguments to array and cut off target object
var args = Array.prototype.slice.call(arguments, 1);
var val, src;
args.forEach(function (obj) {
// skip argument if it is array or isn't object
if (typeof obj !== 'object' || Array.isArray(obj)) {
return;
}
Object.keys(obj).forEach(function (key) {
src = target[key]; // source value
val = obj[key]; // new value
// recursion prevention
if (val === target) {
return;
/**
* if new value isn't object then just overwrite by new value
* instead of extending.
*/
}
else if (typeof val !== 'object' || val === null) {
target[key] = val;
return;
// just clone arrays (and recursive clone objects inside)
}
else if (Array.isArray(val)) {
target[key] = deepCloneArray(val);
return;
// custom cloning and overwrite for specific objects
}
else if (isSpecificValue(val)) {
target[key] = cloneSpecificValue(val);
return;
// overwrite by new value if source isn't object or array
}
else if (typeof src !== 'object' || src === null || Array.isArray(src)) {
target[key] = deepExtend({}, val);
return;
// source value and new value is objects both, extending...
}
else {
target[key] = deepExtend(src, val);
return;
}
});
});
return target;
};
function isSpecificValue(val) {
return (val instanceof Date
|| val instanceof RegExp) ? true : false;
}
function cloneSpecificValue(val) {
if (val instanceof Date) {
return new Date(val.getTime());
}
else if (val instanceof RegExp) {
return new RegExp(val);
}
else {
throw new Error('cloneSpecificValue: Unexpected situation');
}
}
/**
* Recursive cloning array.
*/
function deepCloneArray(arr) {
var clone = [];
arr.forEach(function (item, index) {
if (typeof item === 'object' && item !== null) {
if (Array.isArray(item)) {
clone[index] = deepCloneArray(item);
}
else if (isSpecificValue(item)) {
clone[index] = cloneSpecificValue(item);
}
else {
clone[index] = deepExtend({}, item);
}
}
else {
clone[index] = item;
}
});
return clone;
}
// getDeepFromObject({result: {data: 1}}, 'result.data', 2); // returns 1
function getDeepFromObject(object, name, defaultValue) {
if (object === void 0) { object = {}; }
var keys = name.split('.');
// clone the object
var level = deepExtend({}, object || {});
keys.forEach(function (k) {
if (level && typeof level[k] !== 'undefined') {
level = level[k];
}
else {
level = undefined;
}
});
return typeof level === 'undefined' ? defaultValue : level;
}
function urlBase64Decode(str) {
var output = str.replace(/-/g, '+').replace(/_/g, '/');
switch (output.length % 4) {
case 0: {
break;
}
case 2: {
output += '==';
break;
}
case 3: {
output += '=';
break;
}
default: {
throw new Error('Illegal base64url string!');
}
}
return b64DecodeUnicode(output);
}
function b64decode(str) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var output = '';
str = String(str).replace(/=+$/, '');
if (str.length % 4 === 1) {
throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (
// initialize result and counters
var bc = 0, bs = void 0, buffer = void 0, idx = 0;
// get next character
buffer = str.charAt(idx++);
// character found in table? initialize bit storage and add its ascii value;
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
// and if not first of each 4 characters,
// convert the first 8 bits to one ascii character
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0) {
// try to find character in table (0-63, not found => -1)
buffer = chars.indexOf(buffer);
}
return output;
}
// https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem
function b64DecodeUnicode(str) {
return decodeURIComponent(Array.prototype.map.call(b64decode(str), function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
var NbAuthToken = /** @class */ (function () {
function NbAuthToken() {
this.payload = null;
}
NbAuthToken.prototype.getName = function () {
return this.constructor.NAME;
};
NbAuthToken.prototype.getPayload = function () {
return this.payload;
};
return NbAuthToken;
}());
var NbAuthTokenNotFoundError = /** @class */ (function (_super) {
tslib.__extends(NbAuthTokenNotFoundError, _super);
function NbAuthTokenNotFoundError(message) {
var _newTarget = this.constructor;
var _this = _super.call(this, message) || this;
Object.setPrototypeOf(_this, _newTarget.prototype);
return _this;
}
return NbAuthTokenNotFoundError;
}(Error));
var NbAuthIllegalTokenError = /** @class */ (function (_super) {
tslib.__extends(NbAuthIllegalTokenError, _super);
function NbAuthIllegalTokenError(message) {
var _newTarget = this.constructor;
var _this = _super.call(this, message) || this;
Object.setPrototypeOf(_this, _newTarget.prototype);
return _this;
}
return NbAuthIllegalTokenError;
}(Error));
var NbAuthEmptyTokenError = /** @class */ (function (_super) {
tslib.__extends(NbAuthEmptyTokenError, _super);
function NbAuthEmptyTokenError(message) {
var _newTarget = this.constructor;
var _this = _super.call(this, message) || this;
Object.setPrototypeOf(_this, _newTarget.prototype);
return _this;
}
return NbAuthEmptyTokenError;
}(NbAuthIllegalTokenError));
var NbAuthIllegalJWTTokenError = /** @class */ (function (_super) {
tslib.__extends(NbAuthIllegalJWTTokenError, _super);
function NbAuthIllegalJWTTokenError(message) {
var _newTarget = this.constructor;
var _this = _super.call(this, message) || this;
Object.setPrototypeOf(_this, _newTarget.prototype);
return _this;
}
return NbAuthIllegalJWTTokenError;
}(NbAuthIllegalTokenError));
function nbAuthCreateToken(tokenClass, token, ownerStrategyName, createdAt) {
return new tokenClass(token, ownerStrategyName, createdAt);
}
function decodeJwtPayload(payload) {
if (payload.length === 0) {
throw new NbAuthEmptyTokenError('Cannot extract from an empty payload.');
}
var parts = payload.split('.');
if (parts.length !== 3) {
throw new NbAuthIllegalJWTTokenError("The payload " + payload + " is not valid JWT payload and must consist of three parts.");
}
var decoded;
try {
decoded = urlBase64Decode(parts[1]);
}
catch (e) {
throw new NbAuthIllegalJWTTokenError("The payload " + payload + " is not valid JWT payload and cannot be parsed.");
}
if (!decoded) {
throw new NbAuthIllegalJWTTokenError("The payload " + payload + " is not valid JWT payload and cannot be decoded.");
}
return JSON.parse(decoded);
}
/**
* Wrapper for simple (text) token
*/
var NbAuthSimpleToken = /** @class */ (function (_super) {
tslib.__extends(NbAuthSimpleToken, _super);
function NbAuthSimpleToken(token, ownerStrategyName, createdAt) {
var _this = _super.call(this) || this;
_this.token = token;
_this.ownerStrategyName = ownerStrategyName;
_this.createdAt = createdAt;
try {
_this.parsePayload();
}
catch (err) {
if (!(err instanceof NbAuthTokenNotFoundError)) {
// token is present but has got a problem, including illegal
throw err;
}
}
_this.createdAt = _this.prepareCreatedAt(createdAt);
return _this;
}
NbAuthSimpleToken.prototype.parsePayload = function () {
this.payload = null;
};
NbAuthSimpleToken.prototype.prepareCreatedAt = function (date) {
return date ? date : new Date();
};
/**
* Returns the token's creation date
* @returns {Date}
*/
NbAuthSimpleToken.prototype.getCreatedAt = function () {
return this.createdAt;
};
/**
* Returns the token value
* @returns string
*/
NbAuthSimpleToken.prototype.getValue = function () {
return this.token;
};
NbAuthSimpleToken.prototype.getOwnerStrategyName = function () {
return this.ownerStrategyName;
};
/**
* Is non empty and valid
* @returns {boolean}
*/
NbAuthSimpleToken.prototype.isValid = function () {
return !!this.getValue();
};
/**
* Validate value and convert to string, if value is not valid return empty string
* @returns {string}
*/
NbAuthSimpleToken.prototype.toString = function () {
return !!this.token ? this.token : '';
};
NbAuthSimpleToken.NAME = 'nb:auth:simple:token';
return NbAuthSimpleToken;
}(NbAuthToken));
/**
* Wrapper for JWT token with additional methods.
*/
var NbAuthJWTToken = /** @class */ (function (_super) {
tslib.__extends(NbAuthJWTToken, _super);
function NbAuthJWTToken() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* for JWT token, the iat (issued at) field of the token payload contains the creation Date
*/
NbAuthJWTToken.prototype.prepareCreatedAt = function (date) {
var decoded = this.getPayload();
return decoded && decoded.iat ? new Date(Number(decoded.iat) * 1000) : _super.prototype.prepareCreatedAt.call(this, date);
};
/**
* Returns payload object
* @returns any
*/
NbAuthJWTToken.prototype.parsePayload = function () {
if (!this.token) {
throw new NbAuthTokenNotFoundError('Token not found. ');
}
this.payload = decodeJwtPayload(this.token);
};
/**
* Returns expiration date
* @returns Date
*/
NbAuthJWTToken.prototype.getTokenExpDate = function () {
var decoded = this.getPayload();
if (decoded && !decoded.hasOwnProperty('exp')) {
return null;
}
var date = new Date(0);
date.setUTCSeconds(decoded.exp); // 'cause jwt token are set in seconds
return date;
};
/**
* Is data expired
* @returns {boolean}
*/
NbAuthJWTToken.prototype.isValid = function () {
return _super.prototype.isValid.call(this) && (!this.getTokenExpDate() || new Date() < this.getTokenExpDate());
};
NbAuthJWTToken.NAME = 'nb:auth:jwt:token';
return NbAuthJWTToken;
}(NbAuthSimpleToken));
var prepareOAuth2Token = function (data) {
if (typeof data === 'string') {
try {
return JSON.parse(data);
}
catch (e) { }
}
return data;
};
var ɵ0 = prepareOAuth2Token;
/**
* Wrapper for OAuth2 token whose access_token is a JWT Token
*/
var NbAuthOAuth2Token = /** @class */ (function (_super) {
tslib.__extends(NbAuthOAuth2Token, _super);
function NbAuthOAuth2Token(data, ownerStrategyName, createdAt) {
if (data === void 0) { data = {}; }
// we may get it as string when retrieving from a storage
return _super.call(this, prepareOAuth2Token(data), ownerStrategyName, createdAt) || this;
}
/**
* Returns the token value
* @returns string
*/
NbAuthOAuth2Token.prototype.getValue = function () {
return this.token.access_token;
};
/**
* Returns the refresh token
* @returns string
*/
NbAuthOAuth2Token.prototype.getRefreshToken = function () {
return this.token.refresh_token;
};
/**
* put refreshToken in the token payload
* @param refreshToken
*/
NbAuthOAuth2Token.prototype.setRefreshToken = function (refreshToken) {
this.token.refresh_token = refreshToken;
};
/**
* Parses token payload
* @returns any
*/
NbAuthOAuth2Token.prototype.parsePayload = function () {
if (!this.token) {
throw new NbAuthTokenNotFoundError('Token not found.');
}
else {
if (!Object.keys(this.token).length) {
throw new NbAuthEmptyTokenError('Cannot extract payload from an empty token.');
}
}
this.payload = this.token;
};
/**
* Returns the token type
* @returns string
*/
NbAuthOAuth2Token.prototype.getType = function () {
return this.token.token_type;
};
/**
* Is data expired
* @returns {boolean}
*/
NbAuthOAuth2Token.prototype.isValid = function () {
return _super.prototype.isValid.call(this) && (!this.getTokenExpDate() || new Date() < this.getTokenExpDate());
};
/**
* Returns expiration date
* @returns Date
*/
NbAuthOAuth2Token.prototype.getTokenExpDate = function () {
if (!this.token.hasOwnProperty('expires_in')) {
return null;
}
return new Date(this.createdAt.getTime() + Number(this.token.expires_in) * 1000);
};
/**
* Convert to string
* @returns {string}
*/
NbAuthOAuth2Token.prototype.toString = function () {
return JSON.stringify(this.token);
};
NbAuthOAuth2Token.NAME = 'nb:auth:oauth2:token';
return NbAuthOAuth2Token;
}(NbAuthSimpleToken));
/**
* Wrapper for OAuth2 token embedding JWT tokens
*/
var NbAuthOAuth2JWTToken = /** @class */ (function (_super) {
tslib.__extends(NbAuthOAuth2JWTToken, _super);
function NbAuthOAuth2JWTToken() {
return _super !== null && _super.apply(this, arguments) || this;
}
NbAuthOAuth2JWTToken.prototype.parsePayload = function () {
_super.prototype.parsePayload.call(this);
this.parseAccessTokenPayload();
};
NbAuthOAuth2JWTToken.prototype.parseAccessTokenPayload = function () {
var accessToken = this.getValue();
if (!accessToken) {
throw new NbAuthTokenNotFoundError('access_token key not found.');
}
this.accessTokenPayload = decodeJwtPayload(accessToken);
};
/**
* Returns access token payload
* @returns any
*/
NbAuthOAuth2JWTToken.prototype.getAccessTokenPayload = function () {
return this.accessTokenPayload;
};
/**
* for Oauth2 JWT token, the iat (issued at) field of the access_token payload
*/
NbAuthOAuth2JWTToken.prototype.prepareCreatedAt = function (date) {
var payload = this.accessTokenPayload;
return payload && payload.iat ? new Date(Number(payload.iat) * 1000) : _super.prototype.prepareCreatedAt.call(this, date);
};
/**
* Is token valid
* @returns {boolean}
*/
NbAuthOAuth2JWTToken.prototype.isValid = function () {
return this.accessTokenPayload && _super.prototype.isValid.call(this);
};
/**
* Returns expiration date :
* - exp if set,
* - super.getExpDate() otherwise
* @returns Date
*/
NbAuthOAuth2JWTToken.prototype.getTokenExpDate = function () {
if (this.accessTokenPayload && this.accessTokenPayload.hasOwnProperty('exp')) {
var date = new Date(0);
date.setUTCSeconds(this.accessTokenPayload.exp);
return date;
}
else {
return _super.prototype.getTokenExpDate.call(this);
}
};
NbAuthOAuth2JWTToken.NAME = 'nb:auth:oauth2:jwt:token';
return NbAuthOAuth2JWTToken;
}(NbAuthOAuth2Token));
var NB_AUTH_FALLBACK_TOKEN = new _angular_core.InjectionToken('Nebular Auth Options');
/**
* Creates a token parcel which could be stored/restored
*/
var NbAuthTokenParceler = /** @class */ (function () {
function NbAuthTokenParceler(fallbackClass, tokenClasses) {
this.fallbackClass = fallbackClass;
this.tokenClasses = tokenClasses;
}
NbAuthTokenParceler.prototype.wrap = function (token) {
return JSON.stringify({
name: token.getName(),
ownerStrategyName: token.getOwnerStrategyName(),
createdAt: token.getCreatedAt().getTime(),
value: token.toString(),
});
};
NbAuthTokenParceler.prototype.unwrap = function (value) {
var tokenClass = this.fallbackClass;
var tokenValue = '';
var tokenOwnerStrategyName = '';
var tokenCreatedAt = null;
var tokenPack = this.parseTokenPack(value);
if (tokenPack) {
tokenClass = this.getClassByName(tokenPack.name) || this.fallbackClass;
tokenValue = tokenPack.value;
tokenOwnerStrategyName = tokenPack.ownerStrategyName;
tokenCreatedAt = new Date(Number(tokenPack.createdAt));
}
return nbAuthCreateToken(tokenClass, tokenValue, tokenOwnerStrategyName, tokenCreatedAt);
};
// TODO: this could be moved to a separate token registry
NbAuthTokenParceler.prototype.getClassByName = function (name) {
return this.tokenClasses.find(function (tokenClass) { return tokenClass.NAME === name; });
};
NbAuthTokenParceler.prototype.parseTokenPack = function (value) {
try {
return JSON.parse(value);
}
catch (e) { }
return null;
};
NbAuthTokenParceler.decorators = [
{ type: _angular_core.Injectable }
];
NbAuthTokenParceler.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: _angular_core.Inject, args: [NB_AUTH_FALLBACK_TOKEN,] }] },
{ type: Array, decorators: [{ type: _angular_core.Inject, args: [NB_AUTH_TOKENS,] }] }
]; };
return NbAuthTokenParceler;
}());
var NbTokenStorage = /** @class */ (function () {
function NbTokenStorage() {
}
return NbTokenStorage;
}());
/**
* Service that uses browser localStorage as a storage.
*
* The token storage is provided into auth module the following way:
* ```ts
* { provide: NbTokenStorage, useClass: NbTokenLocalStorage },
* ```
*
* If you need to change the storage behaviour or provide your own - just extend your class from basic `NbTokenStorage`
* or `NbTokenLocalStorage` and provide in your `app.module`:
* ```ts
* { provide: NbTokenStorage, useClass: NbTokenCustomStorage },
* ```
*
*/
var NbTokenLocalStorage = /** @class */ (function (_super) {
tslib.__extends(NbTokenLocalStorage, _super);
function NbTokenLocalStorage(parceler) {
var _this = _super.call(this) || this;
_this.parceler = parceler;
_this.key = 'auth_app_token';
return _this;
}
/**
* Returns token from localStorage
* @returns {NbAuthToken}
*/
NbTokenLocalStorage.prototype.get = function () {
var raw = localStorage.getItem(this.key);
return this.parceler.unwrap(raw);
};
/**
* Sets token to localStorage
* @param {NbAuthToken} token
*/
NbTokenLocalStorage.prototype.set = function (token) {
var raw = this.parceler.wrap(token);
localStorage.setItem(this.key, raw);
};
/**
* Clears token from localStorage
*/
NbTokenLocalStorage.prototype.clear = function () {
localStorage.removeItem(this.key);
};
NbTokenLocalStorage.decorators = [
{ type: _angular_core.Injectable }
];
NbTokenLocalStorage.ctorParameters = function () { return [
{ type: NbAuthTokenParceler }
]; };
return NbTokenLocalStorage;
}(NbTokenStorage));
/**
* Service that allows you to manage authentication token - get, set, clear and also listen to token changes over time.
*/
var NbTokenService = /** @class */ (function () {
function NbTokenService(tokenStorage) {
this.tokenStorage = tokenStorage;
this.token$ = new rxjs.BehaviorSubject(null);
this.publishStoredToken();
}
/**
* Publishes token when it changes.
* @returns {Observable<NbAuthToken>}
*/
NbTokenService.prototype.tokenChange = function () {
return this.token$
.pipe(rxjs_operators.filter(function (value) { return !!value; }), rxjs_operators.share());
};
/**
* Sets a token into the storage. This method is used by the NbAuthService automatically.
*
* @param {NbAuthToken} token
* @returns {Observable<any>}
*/
NbTokenService.prototype.set = function (token) {
this.tokenStorage.set(token);
this.publishStoredToken();
return rxjs.of(null);
};
/**
* Returns observable of current token
* @returns {Observable<NbAuthToken>}
*/
NbTokenService.prototype.get = function () {
var token = this.tokenStorage.get();
return rxjs.of(token);
};
/**
* Removes the token and published token value
*
* @returns {Observable<any>}
*/
NbTokenService.prototype.clear = function () {
this.tokenStorage.clear();
this.publishStoredToken();
return rxjs.of(null);
};
NbTokenService.prototype.publishStoredToken = function () {
this.token$.next(this.tokenStorage.get());
};
NbTokenService.decorators = [
{ type: _angular_core.Injectable }
];
NbTokenService.ctorParameters = function () { return [
{ type: NbTokenStorage }
]; };
return NbTokenService;
}());
/**
* @license
* Copyright Akveo. All Rights Reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
/**
* Common authentication service.
* Should be used to as an interlayer between UI Components and Auth Strategy.
*/
var NbAuthService = /** @class */ (function () {
function NbAuthService(tokenService, strategies) {
this.tokenService = tokenService;
this.strategies = strategies;
}
/**
* Retrieves current authenticated token stored
* @returns {Observable<any>}
*/
NbAuthService.prototype.getToken = function () {
return this.tokenService.get();
};
/**
* Returns true if auth token is present in the token storage
* @returns {Observable<boolean>}
*/
NbAuthService.prototype.isAuthenticated = function () {
return this.getToken()
.pipe(rxjs_operators.map(function (token) { return token.isValid(); }));
};
/**
* Returns true if valid auth token is present in the token storage.
* If not, calls the strategy refreshToken, and returns isAuthenticated() if success, false otherwise
* @returns {Observable<boolean>}
*/
NbAuthService.prototype.isAuthenticatedOrRefresh = function () {
var _this = this;
return this.getToken()
.pipe(rxjs_operators.switchMap(function (token) {
if (token.getValue() && !token.isValid()) {
return _this.refreshToken(token.getOwnerStrategyName(), token)
.pipe(rxjs_operators.switchMap(function (res) {
if (res.isSuccess()) {
return _this.isAuthenticated();
}
else {
return rxjs.of(false);
}
}));
}
else {
return rxjs.of(token.isValid());
}
}));
};
/**
* Returns tokens stream
* @returns {Observable<NbAuthSimpleToken>}
*/
NbAuthService.prototype.onTokenChange = function () {
return this.tokenService.tokenChange();
};
/**
* Returns authentication status stream
* @returns {Observable<boolean>}
*/
NbAuthService.prototype.onAuthenticationChange = function () {
return this.onTokenChange()
.pipe(rxjs_operators.map(function (token) { return token.isValid(); }));
};
/**
* Authenticates with the selected strategy
* Stores received token in the token storage
*
* Example:
* authenticate('email', {email: 'email@example.com', password: 'test'})
*
* @param strategyName
* @param data
* @returns {Observable<NbAuthResult>}
*/
NbAuthService.prototype.authenticate = function (strategyName, data) {
var _this = this;
return this.getStrategy(strategyName).authenticate(data)
.pipe(rxjs_operators.switchMap(function (result) {
return _this.processResultToken(result);
}));
};
/**
* Registers with the selected strategy
* Stores received token in the token storage
*
* Example:
* register('email', {email: 'email@example.com', name: 'Some Name', password: 'test'})
*
* @param strategyName
* @param data
* @returns {Observable<NbAuthResult>}
*/
NbAuthService.prototype.register = function (strategyName, data) {
var _this = this;
return this.getStrategy(strategyName).register(data)
.pipe(rxjs_operators.switchMap(function (result) {
return _this.processResultToken(result);
}));
};
/**
* Sign outs with the selected strategy
* Removes token from the token storage
*
* Example:
* logout('email')
*
* @param strategyName
* @returns {Observable<NbAuthResult>}
*/
NbAuthService.prototype.logout = function (strategyName) {
var _this = this;
return this.getStrategy(strategyName).logout()
.pipe(rxjs_operators.switchMap(function (result) {
if (result.isSuccess()) {
_this.tokenService.clear()
.pipe(rxjs_operators.map(function () { return result; }));
}
return rxjs.of(result);
}));
};
/**
* Sends forgot password request to the selected strategy
*
* Example:
* requestPassword('email', {email: 'email@example.com'})
*
* @param strategyName
* @param data
* @returns {Observable<NbAuthResult>}
*/
NbAuthService.prototype.requestPassword = function (strategyName, data) {
return this.getStrategy(strategyName).requestPassword(data);
};
/**
* Tries to reset password with the selected strategy
*
* Example:
* resetPassword('email', {newPassword: 'test'})
*
* @param strategyName
* @param data
* @returns {Observable<NbAuthResult>}
*/
NbAuthService.prototype.resetPassword = function (strategyName, data) {
return this.getStrategy(strategyName).resetPassword(data);
};
/**
* Sends a refresh token request
* Stores received token in the token storage
*
* Example:
* refreshToken('email', {token: token})
*
* @param {string} strategyName
* @param data
* @returns {Observable<NbAuthResult>}
*/
NbAuthService.prototype.refreshToken = function (strategyName, data) {
var _this = this;
return this.getStrategy(strategyName).refreshToken(data)
.pipe(rxjs_operators.switchMap(function (result) {
return _this.processResultToken(result);
}));
};
/**
* Get registered strategy by name
*
* Example:
* getStrategy('email')
*
* @param {string} provider
* @returns {NbAbstractAuthProvider}
*/
NbAuthService.prototype.getStrategy = function (strategyName) {
var found = this.strategies.find(function (strategy) { return strategy.getName() === strategyName; });
if (!found) {
throw new TypeError("There is no Auth Strategy registered under '" + strategyName + "' name");
}
return found;
};
NbAuthService.prototype.processResultToken = function (result) {
if (result.isSuccess() && result.getToken()) {
return this.tokenService.set(result.getToken())
.pipe(rxjs_operators.map(function (token) {
return result;
}));
}
return rxjs.of(result);
};
NbAuthService.decorators = [
{ type: _angular_core.Injectable }
];
NbAuthService.ctorParameters = function () { return [
{ type: NbTokenService },
{ type: undefined, decorators: [{ type: _angular_core.Inject, args: [NB_AUTH_STRATEGIES,] }] }
]; };
return NbAuthService;
}());
var NbAuthStrategy = /** @class */ (function () {
function NbAuthStrategy() {
}
// we should keep this any and validation should be done in `register` method instead
// otherwise it won't be possible to pass an empty object
NbAuthStrategy.prototype.setOptions = function (options) {
this.options = deepExtend({}, this.defaultOptions, options);
};
NbAuthStrategy.prototype.getOption = function (key) {
return getDeepFromObject(this.options, key, null);
};
NbAuthStrategy.prototype.createToken = function (value, failWhenInvalidToken) {
var token = nbAuthCreateToken(this.getOption('token.class'), value, this.getName());
// At this point, nbAuthCreateToken failed with NbAuthIllegalTokenError which MUST be intercepted by strategies
// Or token is created. It MAY be created even if backend did not return any token, in this case it is !Valid
if (failWhenInvalidToken && !token.isValid()) {
// If we require a valid token (i.e. isValid), then we MUST throw NbAuthIllegalTokenError so that the strategies
// intercept it
throw new NbAuthIllegalTokenError('Token is empty or invalid.');
}
return token;
};
NbAuthStrategy.prototype.getName = function () {
return this.getOption('name');
};
NbAuthStrategy.prototype.createFailResponse = function (data) {
return new _angular_common_http.HttpResponse({ body: {}, status: 401 });
};
NbAuthStrategy.prototype.createSuccessResponse = function (data) {
return new _angular_common_http.HttpResponse({ body: {}, status: 200 });
};
NbAuthStrategy.prototype.getActionEndpoint = function (action) {
var actionEndpoint = this.getOption(action + ".endpoint");
var baseEndpoint = this.getOption('baseEndpoint');
return actionEndpoint ? baseEndpoint + actionEndpoint : '';
};
return NbAuthStrategy;
}());
var NbAuthResult = /** @class */ (function () {
// TODO: better pass object
function NbAuthResult(success, response, redirect, errors, messages, token) {
if (token === void 0) { token = null; }
this.success = success;
this.response = response;
this.redirect = redirect;
this.errors = [];
this.messages = [];
this.errors = this.errors.concat([errors]);
if (errors instanceof Array) {
this.errors = errors;
}
this.messages = this.messages.concat([messages]);
if (messages instanceof Array) {
this.messages = messages;
}
this.token = token;
}
NbAuthResult.prototype.getResponse = function () {
return this.response;
};
NbAuthResult.prototype.getToken = function () {
return this.token;
};
NbAuthResult.prototype.getRedirect = function () {
return this.redirect;
};
NbAuthResult.prototype.getErrors = function () {
return this.errors.filter(function (val) { return !!val; });
};
NbAuthResult.prototype.getMessages = function () {
return this.messages.filter(function (val) { return !!val; });
};
NbAuthResult.prototype.isSuccess = function () {
return this.success;
};
NbAuthResult.prototype.isFailure = function () {
return !this.success;
};
return NbAuthResult;
}());
var NbAuthStrategyOptions = /** @class */ (function () {
function NbAuthStrategyOptions() {
}
return NbAuthStrategyOptions;
}());
/**
* @license
* Copyright Akveo. All Rights Reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
var NbDummyAuthStrategyOptions = /** @class */ (function (_super) {
tslib.__extends(NbDummyAuthStrategyOptions, _super);
function NbDummyAuthStrategyOptions() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.token = {
class: NbAuthSimpleToken,
};
_this.delay = 1000;
_this.alwaysFail = false;
return _this;
}
return NbDummyAuthStrategyOptions;
}(NbAuthStrategyOptions));
var dummyStrategyOptions = new NbDummyAuthStrategyOptions();
/**
* Dummy auth strategy. Could be useful for auth setup when backend is not available yet.
*
*
* Strategy settings.
*
* ```ts
* export class NbDummyAuthStrategyOptions extends NbAuthStrategyOptions {
* name = 'dummy';
* token = {
* class: NbAuthSimpleToken,
* };
* delay? = 1000;
* alwaysFail? = false;
* }
* ```
*/
var NbDummyAuthStrategy = /** @class */ (function (_super) {
tslib.__extends(NbDummyAuthStrategy, _super);
function NbDummyAuthStrategy() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.defaultOptions = dummyStrategyOptions;
return _this;
}
NbDummyAuthStrategy.setup = function (options) {
return [NbDummyAuthStrategy, options];
};
NbDummyAuthStrategy.prototype.authenticate = function (data) {
return rxjs.of(this.createDummyResult(data))
.pipe(rxjs_operators.delay(this.getOption('delay')));
};
NbDummyAuthStrategy.prototype.register = function (data) {
return rxjs.of(this.createDummyResult(data))
.pipe(rxjs_operators.delay(this.getOption('delay')));
};
NbDummyAuthStrategy.prototype.requestPassword = function (data) {
return rxjs.of(this.createDummyResult(data))
.pipe(rxjs_operators.delay(this.getOption('delay')));
};
NbDummyAuthStrategy.prototype.resetPassword = function (data) {
return rxjs.of(this.createDummyResult(data))
.pipe(rxjs_operators.delay(this.getOption('delay')));
};
NbDummyAuthStrategy.prototype.logout = function (data) {
return rxjs.of(this.createDummyResult(data))
.pipe(rxjs_operators.delay(this.getOption('delay')));
};
NbDummyAuthStrategy.prototype.refreshToken = function (data) {
return rxjs.of(this.createDummyResult(data))
.pipe(rxjs_operators.delay(this.getOption('delay')));
};
NbDummyAuthStrategy.prototype.createDummyResult = function (data) {
if (this.getOption('alwaysFail')) {
return new NbAuthResult(false, this.createFailResponse(data), null, ['Something went wrong.']);
}
try {
var token = this.createToken('test token', true);
return new NbAuthResult(true, this.createSuccessResponse(data), '/', [], ['Successfully logged in.'], token);
}
catch (err) {
return new NbAuthResult(false, this.createFailResponse(data), null, [err.message]);
}
};
NbDummyAuthStrategy.decorators = [
{ type: _angular_core.Injectable }
];
return NbDummyAuthStrategy;
}(NbAuthStrategy));
/**
* @license
* Copyright Akveo. All Rights Reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
(function (NbOAuth2ResponseType) {
NbOAuth2ResponseType["CODE"] = "code";
NbOAuth2ResponseType["TOKEN"] = "token";
})(exports.NbOAuth2ResponseType || (exports.NbOAuth2ResponseType = {}));
// TODO: client_credentials
(function (NbOAuth2GrantType) {
NbOAuth2GrantType["AUTHORIZATION_CODE"] = "authorization_code";
NbOAuth2GrantType["PASSWORD"] = "password";
NbOAuth2GrantType["REFRESH_TOKEN"] = "refresh_token";
})(exports.NbOAuth2GrantType || (exports.NbOAuth2GrantType = {}));
(function (NbOAuth2ClientAuthMethod) {
NbOAuth2ClientAuthMethod["NONE"] = "none";
NbOAuth2ClientAuthMethod["BASIC"] = "basic";
NbOAuth2ClientAuthMethod["REQUEST_BODY"] = "request-body";
})(exports.NbOAuth2ClientAuthMethod || (exports.NbOAuth2ClientAuthMethod = {}));
var NbOAuth2AuthStrategyOptions = /** @class */ (function (_super) {
tslib.__extends(NbOAuth2AuthStrategyOptions, _super);
function NbOAuth2AuthStrategyOptions() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.baseEndpoint = '';
_this.clientId = '';
_this.clientSecret = '';
_this.clientAuthMethod = exports.NbOAuth2ClientAuthMethod.NONE;
_this.redirect = {
success: '/',
failure: null,
};
_this.defaultErrors = ['Something went wrong, please try again.'];
_this.defaultMessages = ['You have been successfully authenticated.'];
_this.authorize = {
endpoint: 'authorize',
responseType: exports.NbOAuth2ResponseType.CODE,
requireValidToken: true,
};
_this.token = {
endpoint: 'token',
grantType: exports.NbOAuth2GrantType.AUTHORIZATION_CODE,
requireValidToken: true,
class: NbAuthOAuth2Token,
};
_this.refresh = {
endpoint: 'token',
grantType: exports.NbOAuth2GrantType.REFRESH_TOKEN,
requireValidToken: true,
};
return _this;
}
return NbOAuth2AuthStrategyOptions;
}(NbAuthStrategyOptions));
var auth2StrategyOptions = new NbOAuth2AuthStrategyOptions();
/**
* @license
* Copyright Akveo. All Rights Reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
/**
* OAuth2 authentication strategy.
*
* Strategy settings:
*
* ```ts
* export enum NbOAuth2ResponseType {
* CODE = 'code',
* TOKEN = 'token',
* }
*
* export enum NbOAuth2GrantType {
* AUTHORIZATION_CODE = 'authorization_code',
* PASSWORD = 'password',
* REFRESH_TOKEN = 'refresh_token',
* }
*
* export class NbOAuth2AuthStrategyOptions {
* name: string;
* baseEndpoint?: string = '';
* clientId: string = '';
* clientSecret: string = '';
* clientAuthMethod: string = NbOAuth2ClientAuthMethod.NONE;
* redirect?: { success?: string; failure?: string } = {
* success: '/',
* failure: null,
* };
* defaultErrors?: any[] = ['Something went wrong, please try again.'];
* defaultMessages?: any[] = ['You have been successfully authenticated.'];
* authorize?: {
* endpoint?: string;
* redirectUri?: string;
* responseType?: string;
* requireValidToken: true,
* scope?: string;
* state?: string;
* params?: { [key: string]: string };
* } = {
* endpoint: 'authorize',
* responseType: NbOAuth2ResponseType.CODE,
* };
* token?: {
* endpoint?: string;
* grantType?: string;
* requireValidToken: true,
* redirectUri?: string;
* scope?: string;
* class: NbAuthTokenClass,
* } = {
* endpoint: 'token',
* grantType: NbOAuth2GrantType.AUTHORIZATION_CODE,
* class: NbAuthOAuth2Token,
* };
* refresh?: {
* endpoint?: string;
* grantType?: string;
* scope?: string;
* requireValidToken: true,
* } = {
* endpoint: 'token',
* grantType: NbOAuth2GrantType.REFRESH_TOKEN,
* };
* }
* ```
*
*/
var NbOAuth2AuthStrategy = /** @class */ (function (_super) {
tslib.__extends(NbOAuth2AuthStrategy, _super);
function NbOAuth2AuthStrategy(http, route, window) {
var _a, _b;
var _this = _super.call(this) || this;
_this.http = http;
_this.route = route;
_this.window = window;
_this.redirectResultHandlers = (_a = {},
_a[exports.NbOAuth2ResponseType.CODE] = function () {
return rxjs.of(_this.route.snapshot.queryParams).pipe(rxjs_operators.switchMap(function (params) {
if (params.code) {
return _this.requestToken(params.code);
}
return rxjs.of(new NbAuthResult(false, params, _this.getOption('redirect.failure'), _this.getOption('defaultErrors'), []));
}));
},
_a[exports.NbOAuth2ResponseType.TOKEN] = function () {
var module = 'authorize';
var requireValidToken = _this.getOption(module + ".requireValidToken");
return rxjs.of(_this.route.snapshot.fragment).pipe(rxjs_operators.map(function (fragment) { return _this.parseHashAsQueryParams(fragment); }), rxjs_operators.map(function (params) {
if (!params.error) {
return new NbAuthResult(true, params, _this.getOption('redirect.success'), [], _this.getOption('defaultMessages'), _this.createToken(params, requireValidToken));
}
return new NbAuthResult(false, params, _this.getOption('redirect.failure'), _this.getOption('defaultErrors'), []);
}), rxjs_operators.catchError(function (err) {
var errors = [];
if (err instanceof NbAuthIllegalTokenError) {
errors.push(err.message);
}
else {
errors.push('Something went wrong.');
}
return rxjs.of(new NbAuthResult(false, err, _this.getOption('redirect.failure'), errors));
}));
},
_a);
_this.redirectResults = (_b = {},
_b[exports.NbOAuth2ResponseType.CODE] = function () {
return rxjs.of(_this.route.snapshot.queryParams).pipe(rxjs_operators.map(function (params) { return !!(params && (params.code || params.error)); }));
},
_b[exports.NbOAuth2ResponseType.TOKEN] = function () {
return rxjs.of(_this.route.snapshot.fragment).pipe(rxjs_operators.map(function (fragment) { return _this.parseHashAsQueryParams(fragment); }), rxjs_operators.map(function (params) { return !!(params && (params.access_token || params.error)); }));
},
_b);
_this.defaultOptions = auth2StrategyOptions;
return _this;
}
NbOAuth2AuthStrategy.setup = function (options) {
return [NbOAuth2AuthStrategy, options];
};
Object.defineProperty(NbOAuth2AuthStrategy.prototype, "responseType", {
get: function () {
return this.getOption('authorize.responseType');
},
enumerable: false,
configurable: true
});
Object.defineProperty(NbOAuth2AuthStrategy.prototype, "clientAuthMethod", {
get: function () {
return this.getOption('clientAuthMethod');
},
enumerable: false,
configurable: true
});
NbOAuth2AuthStrategy.prototype.authenticate = function (data) {
var _this = this;
if (this.getOption('token.grantType') === exports.NbOAuth2GrantType.PASSWORD) {
return this.passwordToken(data.email, data.password);
}
else {
return this.isRedirectResult()
.pipe(rxjs_operators.switchMap(function (result) {
if (!result) {
_this.authorizeRedirect();
return rxjs.of(new NbAuthResult(true));
}
return _this.getAuthorizationResult();
}));
}
};
NbOAuth2AuthStrategy.prototype.getAuthorizationResult = function () {
var redirectResultHandler = this.redirectResultHandlers[this.responseType];
if (redirectResultHandler) {
return redirectResultHandler.call(this);
}
throw new Error("'" + this.responseType + "' responseType is not supported,\n only 'token' and 'code' are supported now");
};
NbOAuth2AuthStrategy.prototype.refreshToken = function (token) {
var _this = this;
var module = 'refresh';
var url = this.getActionEndpoint(module);
var requireValidToken = this.getOption(module + ".requireValidToken");
var headers = this.buildAuthHeader() || new _angular_common_http.HttpHeaders();
headers = headers.append('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post(url, this.buildRefreshRequestData(token), { headers: headers })
.pipe(rxjs_operators.map(function (res) {
return new NbAuthResult(true, res, _this.getOption('redirect.success'), [], _this.getOption('defaultMessages'), _this.createRefreshedToken(res, token, requireValidToken));
}), rxjs_operators.catchError(function (res) { return _this.handleResponseError(res); }));
};
NbOAuth2AuthStrategy.prototype.passwordToken = function (username, password) {
var _this = this;
var module = 'token';
var url = this.getActionEndpoint(module);
var requireValidToken = this.getOption(module + ".requireValidToken");
var headers = this.buildAuthHeader() || new _angular_common_http.HttpHeaders();
headers = headers.append('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post(url, this.buildPasswordRequestData(username, password), { headers: headers })
.pipe(rxjs_operators.map(function (res) {
return new NbAuthResult(true, res, _this.getOption('redirect.success'), [], _this.getOption('defaultMessages'), _this.createToken(res, requireValidToken));
}), rxjs_operators.catchError(function (res) { retur