@auth0/auth0-spa-js
Version:
Auth0 SDK for Single Page Applications using Authorization Code Grant Flow with PKCE
789 lines (768 loc) • 33.7 kB
JavaScript
'use strict';
require('fast-text-encoding');
var qs = require('qs');
var Cookies = require('es-cookie');
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
var _this = undefined;
var TIMEOUT_ERROR = { error: 'timeout', error_description: 'Timeout' };
var getUniqueScopes = function () {
var scopes = [];
for (var _i = 0; _i < arguments.length; _i++) {
scopes[_i] = arguments[_i];
}
var scopeString = scopes.filter(Boolean).join();
return Array.from(new Set(scopeString.replace(/\s/g, ',').split(',')))
.join(' ')
.trim();
};
var parseQueryResult = function (hash) {
var hashed = qs.parse(hash);
return __assign({}, hashed, { expires_in: parseInt(hashed.expires_in) });
};
var runIframe = function (authorizeUrl, eventOrigin) {
return new Promise(function (res, rej) {
var iframe = window.document.createElement('iframe');
iframe.setAttribute('width', '0');
iframe.setAttribute('height', '0');
iframe.style.display = 'none';
var timeoutSetTimeoutId = setTimeout(function () {
rej(TIMEOUT_ERROR);
window.document.body.removeChild(iframe);
}, 60 * 1000);
var iframeEventHandler = function (e) {
if (e.origin != eventOrigin)
return;
if (!e.data || e.data.type !== 'authorization_response')
return;
e.source.close();
e.data.response.error ? rej(e.data.response) : res(e.data.response);
clearTimeout(timeoutSetTimeoutId);
window.removeEventListener('message', iframeEventHandler, false);
window.document.body.removeChild(iframe);
};
window.addEventListener('message', iframeEventHandler, false);
window.document.body.appendChild(iframe);
iframe.setAttribute('src', authorizeUrl);
});
};
var openPopup = function () {
var popup = window.open('', 'auth0:authorize:popup', 'left=100,top=100,width=400,height=600,resizable,scrollbars=yes,status=1');
if (!popup) {
throw new Error('Could not open popup');
}
return popup;
};
var runPopup = function (popup, authorizeUrl) {
popup.location.href = authorizeUrl;
return new Promise(function (resolve, reject) {
var timeoutId = setTimeout(function () {
reject(TIMEOUT_ERROR);
}, 60 * 1000);
window.addEventListener('message', function (e) {
if (!e.data || e.data.type !== 'authorization_response') {
return;
}
clearTimeout(timeoutId);
popup.close();
if (e.data.response.error) {
return reject(e.data.response);
}
resolve(e.data.response);
});
});
};
var createRandomString = function () {
var charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-_~.';
var random = '';
var randomValues = crypto.getRandomValues(new Uint8Array(43));
randomValues.forEach(function (v) { return (random += charset[v % charset.length]); });
return random;
};
var encodeState = function (state) { return btoa(state); };
var createQueryParams = function (params) { return qs.stringify(params); };
var sha256 = function (s) {
return window.crypto.subtle.digest({ name: 'SHA-256' }, new TextEncoder().encode(s));
};
var urlEncodeB64 = function (input) {
var b64Chars = { '+': '-', '/': '_', '=': '' };
return input.replace(/[\+\/=]/g, function (m) { return b64Chars[m]; });
};
// https://stackoverflow.com/questions/30106476/
var decodeB64 = function (input) {
return decodeURIComponent(atob(input)
.split('')
.map(function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
})
.join(''));
};
var urlDecodeB64 = function (input) {
return decodeB64(input.replace(/_/g, '/').replace(/-/g, '+'));
};
var bufferToBase64UrlEncoded = function (input) {
return urlEncodeB64(window.btoa(String.fromCharCode.apply(String, Array.from(new Uint8Array(input)))));
};
var oauthToken = function (_a) { return __awaiter(_this, void 0, void 0, function () {
var baseUrl = _a.baseUrl, options = __rest(_a, ["baseUrl"]);
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, fetch(baseUrl + "/oauth/token", {
method: 'POST',
body: JSON.stringify(__assign({ grant_type: 'authorization_code', redirect_uri: window.location.origin }, options)),
headers: {
'Content-type': 'application/json'
}
}).then(function (r) { return r.json(); })];
case 1: return [2 /*return*/, _b.sent()];
}
});
}); };
var createKey = function (e) { return e.audience + "::" + e.scope; };
var getExpirationTimeoutInMilliseconds = function (expiresIn, exp) {
var expTime = (new Date(exp * 1000).getTime() - new Date().getTime()) / 1000;
return Math.min(expiresIn, expTime) * 1000;
};
var Cache = /** @class */ (function () {
function Cache() {
this.cache = {};
}
Cache.prototype.save = function (entry) {
var _this = this;
var key = createKey(entry);
this.cache[key] = entry;
var timeout = getExpirationTimeoutInMilliseconds(entry.expires_in, entry.decodedToken.claims.exp);
setTimeout(function () {
delete _this.cache[key];
}, timeout);
};
Cache.prototype.get = function (key) {
return this.cache[createKey(key)];
};
return Cache;
}());
var getAllKeys = function () { return Object.keys(Cookies.getAll() || {}); };
var get = function (key) {
var value = Cookies.get(key);
if (typeof value === 'undefined') {
return;
}
return JSON.parse(value);
};
var save = function (key, value, options) {
Cookies.set(key, JSON.stringify(value), {
expires: options.daysUntilExpire
});
};
var remove = function (key) {
Cookies.remove(key);
};
var COOKIE_KEY = 'a0.spajs.txs.';
var getTransactionKey = function (state) { return "" + COOKIE_KEY + state; };
var TransactionManager = /** @class */ (function () {
function TransactionManager() {
var _this = this;
this.transactions = {};
getAllKeys()
.filter(function (k) { return k.startsWith(COOKIE_KEY); })
.forEach(function (k) {
var state = k.replace(COOKIE_KEY, '');
_this.transactions[state] = get(k);
});
}
TransactionManager.prototype.create = function (state, transaction) {
this.transactions[state] = transaction;
save(getTransactionKey(state), transaction, {
daysUntilExpire: 1
});
};
TransactionManager.prototype.get = function (state) {
return this.transactions[state];
};
TransactionManager.prototype.remove = function (state) {
delete this.transactions[state];
remove(getTransactionKey(state));
};
return TransactionManager;
}());
var idTokendecoded = [
'iss',
'aud',
'exp',
'nbf',
'iat',
'jti',
'azp',
'nonce',
'auth_time',
'at_hash',
'c_hash',
'acr',
'amr',
'sub_jwk',
'cnf',
'sip_from_tag',
'sip_date',
'sip_callid',
'sip_cseq_num',
'sip_via_branch',
'orig',
'dest',
'mky',
'events',
'toe',
'txn',
'rph',
'sid',
'vot',
'vtm'
];
var decode = function (token) {
var _a = token.split('.'), header = _a[0], payload = _a[1], signature = _a[2];
var payloadJSON = JSON.parse(urlDecodeB64(payload));
var claims = {};
var user = {};
Object.keys(payloadJSON).forEach(function (k) {
claims[k] = payloadJSON[k];
if (!idTokendecoded.includes(k)) {
user[k] = payloadJSON[k];
}
});
return {
encoded: { header: header, payload: payload, signature: signature },
header: JSON.parse(urlDecodeB64(header)),
claims: claims,
user: user
};
};
var verify = function (options) {
var decoded = decode(options.id_token);
if (decoded.claims.iss !== options.iss) {
throw new Error('Invalid issuer');
}
if (decoded.claims.aud !== options.aud) {
throw new Error('Invalid audience');
}
if (decoded.header.alg !== 'RS256') {
throw new Error('Invalid algorithm');
}
if (decoded.claims.nonce !== options.nonce) {
throw new Error('Invalid nonce');
}
var now = new Date();
var expDate = new Date(0);
var iatDate = new Date(0);
var nbfDate = new Date(0);
var leeway = options.leeway || 60;
expDate.setUTCSeconds(decoded.claims.exp + leeway);
iatDate.setUTCSeconds(decoded.claims.iat - leeway);
nbfDate.setUTCSeconds(decoded.claims.nbf - leeway);
if (now > expDate) {
throw new Error('id_token expired');
}
if (now < iatDate) {
throw new Error('id_token was issued in the future (invalid iat)');
}
if (typeof decoded.claims.nbf !== 'undefined' && now < nbfDate) {
throw new Error('token is not yet valid (invalid notBefore)');
}
return decoded;
};
var AuthenticationError = /** @class */ (function (_super) {
__extends(AuthenticationError, _super);
function AuthenticationError(error, error_description, state) {
var _this = _super.call(this, error_description) || this;
_this.error = error;
_this.error_description = error_description;
_this.state = state;
return _this;
}
return AuthenticationError;
}(Error));
var version = '1.1.1';
/**
* Auth0 SDK for Single Page Applications using [Authorization Code Grant Flow with PKCE](https://auth0.com/docs/api-auth/tutorials/authorization-code-grant-pkce).
*/
var Auth0Client = /** @class */ (function () {
function Auth0Client(options) {
this.options = options;
this.DEFAULT_SCOPE = 'openid profile email';
this.cache = new Cache();
this.transactionManager = new TransactionManager();
this.domainUrl = "https://" + this.options.domain;
}
Auth0Client.prototype._url = function (path) {
var telemetry = encodeURIComponent(btoa(JSON.stringify({
name: 'auth0-spa-js',
version: version
})));
return "" + this.domainUrl + path + "&auth0Client=" + telemetry;
};
Auth0Client.prototype._getParams = function (authorizeOptions, state, nonce, code_challenge, redirect_uri) {
var _a = this.options, domain = _a.domain, withoutDomain = __rest(_a, ["domain"]);
return __assign({}, withoutDomain, authorizeOptions, { scope: getUniqueScopes(this.DEFAULT_SCOPE, this.options.scope, authorizeOptions.scope), response_type: 'code', response_mode: 'query', state: state,
nonce: nonce, redirect_uri: redirect_uri || this.options.redirect_uri, code_challenge: code_challenge, code_challenge_method: 'S256' });
};
Auth0Client.prototype._authorizeUrl = function (authorizeOptions) {
return this._url("/authorize?" + createQueryParams(authorizeOptions));
};
Auth0Client.prototype._verifyIdToken = function (id_token, nonce) {
return verify({
iss: this.domainUrl + "/",
aud: this.options.client_id,
id_token: id_token,
nonce: nonce,
leeway: this.options.leeway
});
};
/**
* ```js
* await auth0.loginWithPopup(options);
* ```
*
* Opens a popup with the `/authorize` URL using the parameters
* provided as arguments. Random and secure `state` and `nonce`
* parameters will be auto-generated. If the response is successful,
* results will be valid according to their expiration times.
*
* IMPORTANT: This method has to be called from an event handler
* that was started by the user like a button click, for example,
* otherwise the popup will be blocked in most browsers.
*
* @param options
*/
Auth0Client.prototype.loginWithPopup = function (options) {
if (options === void 0) { options = {}; }
return __awaiter(this, void 0, void 0, function () {
var popup, authorizeOptions, stateIn, nonceIn, code_verifier, code_challengeBuffer, code_challenge, params, url, codeResult, authResult, decodedToken, cacheEntry;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, openPopup()];
case 1:
popup = _a.sent();
authorizeOptions = __rest(options, []);
stateIn = encodeState(createRandomString());
nonceIn = createRandomString();
code_verifier = createRandomString();
return [4 /*yield*/, sha256(code_verifier)];
case 2:
code_challengeBuffer = _a.sent();
code_challenge = bufferToBase64UrlEncoded(code_challengeBuffer);
params = this._getParams(authorizeOptions, stateIn, nonceIn, code_challenge, this.options.redirect_uri || window.location.origin);
url = this._authorizeUrl(__assign({}, params, { response_mode: 'web_message' }));
return [4 /*yield*/, runPopup(popup, url)];
case 3:
codeResult = _a.sent();
if (stateIn !== codeResult.state) {
throw new Error('Invalid state');
}
return [4 /*yield*/, oauthToken({
baseUrl: this.domainUrl,
audience: this.options.audience,
client_id: this.options.client_id,
code_verifier: code_verifier,
code: codeResult.code
})];
case 4:
authResult = _a.sent();
decodedToken = this._verifyIdToken(authResult.id_token, nonceIn);
cacheEntry = __assign({}, authResult, { decodedToken: decodedToken, scope: params.scope, audience: params.audience || 'default' });
this.cache.save(cacheEntry);
save('auth0.is.authenticated', true, { daysUntilExpire: 1 });
return [2 /*return*/];
}
});
});
};
/**
* ```js
* const user = await auth0.getUser();
* ```
*
* Returns the user information if available (decoded
* from the `id_token`).
*
* @param options
*/
Auth0Client.prototype.getUser = function (options) {
if (options === void 0) { options = {
audience: this.options.audience || 'default',
scope: this.options.scope || this.DEFAULT_SCOPE
}; }
return __awaiter(this, void 0, void 0, function () {
var cache;
return __generator(this, function (_a) {
options.scope = getUniqueScopes(this.DEFAULT_SCOPE, options.scope);
cache = this.cache.get(options);
return [2 /*return*/, cache && cache.decodedToken.user];
});
});
};
/**
* ```js
* const claims = await auth0.getIdTokenClaims();
* ```
*
* Returns all claims from the id_token if available.
*
* @param options
*/
Auth0Client.prototype.getIdTokenClaims = function (options) {
if (options === void 0) { options = {
audience: this.options.audience || 'default',
scope: this.options.scope || this.DEFAULT_SCOPE
}; }
return __awaiter(this, void 0, void 0, function () {
var cache;
return __generator(this, function (_a) {
options.scope = getUniqueScopes(this.DEFAULT_SCOPE, options.scope);
cache = this.cache.get(options);
return [2 /*return*/, cache && cache.decodedToken.claims];
});
});
};
/**
* ```js
* await auth0.loginWithRedirect(options);
* ```
*
* Performs a redirect to `/authorize` using the parameters
* provided as arguments. Random and secure `state` and `nonce`
* parameters will be auto-generated.
*
* @param options
*/
Auth0Client.prototype.loginWithRedirect = function (options) {
if (options === void 0) { options = {}; }
return __awaiter(this, void 0, void 0, function () {
var redirect_uri, appState, authorizeOptions, stateIn, nonceIn, code_verifier, code_challengeBuffer, code_challenge, params, url;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
redirect_uri = options.redirect_uri, appState = options.appState, authorizeOptions = __rest(options, ["redirect_uri", "appState"]);
stateIn = encodeState(createRandomString());
nonceIn = createRandomString();
code_verifier = createRandomString();
return [4 /*yield*/, sha256(code_verifier)];
case 1:
code_challengeBuffer = _a.sent();
code_challenge = bufferToBase64UrlEncoded(code_challengeBuffer);
params = this._getParams(authorizeOptions, stateIn, nonceIn, code_challenge, redirect_uri);
url = this._authorizeUrl(params);
this.transactionManager.create(stateIn, {
nonce: nonceIn,
code_verifier: code_verifier,
appState: appState,
scope: params.scope,
audience: params.audience || 'default'
});
window.location.assign(url);
return [2 /*return*/];
}
});
});
};
/**
* After the browser redirects back to the callback page,
* call `handleRedirectCallback` to handle success and error
* responses from Auth0. If the response is successful, results
* will be valid according to their expiration times.
*/
Auth0Client.prototype.handleRedirectCallback = function () {
return __awaiter(this, void 0, void 0, function () {
var _a, state, code, error, error_description, transaction, authResult, decodedToken, cacheEntry;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!window.location.search) {
throw new Error('There are no query params available at `window.location.search`.');
}
_a = parseQueryResult(window.location.search.substr(1)), state = _a.state, code = _a.code, error = _a.error, error_description = _a.error_description;
if (error) {
throw new AuthenticationError(error, error_description, state);
}
transaction = this.transactionManager.get(state);
if (!transaction) {
throw new Error('Invalid state');
}
this.transactionManager.remove(state);
return [4 /*yield*/, oauthToken({
baseUrl: this.domainUrl,
audience: this.options.audience,
client_id: this.options.client_id,
code_verifier: transaction.code_verifier,
code: code
})];
case 1:
authResult = _b.sent();
decodedToken = this._verifyIdToken(authResult.id_token, transaction.nonce);
cacheEntry = __assign({}, authResult, { decodedToken: decodedToken, audience: transaction.audience, scope: transaction.scope });
this.cache.save(cacheEntry);
save('auth0.is.authenticated', true, { daysUntilExpire: 1 });
return [2 /*return*/, {
appState: transaction.appState
}];
}
});
});
};
/**
* ```js
* const token = await auth0.getTokenSilently(options);
* ```
*
* If there's a valid token stored, return it. Otherwise, opens an
* iframe with the `/authorize` URL using the parameters provided
* as arguments. Random and secure `state` and `nonce` parameters
* will be auto-generated. If the response is successful, results
* will be valid according to their expiration times.
*
* @param options
*/
Auth0Client.prototype.getTokenSilently = function (options) {
if (options === void 0) { options = {
audience: this.options.audience,
scope: this.options.scope || this.DEFAULT_SCOPE,
ignoreCache: false
}; }
return __awaiter(this, void 0, void 0, function () {
var cache, stateIn, nonceIn, code_verifier, code_challengeBuffer, code_challenge, authorizeOptions, params, url, codeResult, authResult, decodedToken, cacheEntry;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
options.scope = getUniqueScopes(this.DEFAULT_SCOPE, options.scope);
if (!options.ignoreCache) {
cache = this.cache.get({
scope: options.scope,
audience: options.audience || 'default'
});
if (cache) {
return [2 /*return*/, cache.access_token];
}
}
stateIn = encodeState(createRandomString());
nonceIn = createRandomString();
code_verifier = createRandomString();
return [4 /*yield*/, sha256(code_verifier)];
case 1:
code_challengeBuffer = _a.sent();
code_challenge = bufferToBase64UrlEncoded(code_challengeBuffer);
authorizeOptions = {
audience: options.audience,
scope: options.scope
};
params = this._getParams(authorizeOptions, stateIn, nonceIn, code_challenge, this.options.redirect_uri || window.location.origin);
url = this._authorizeUrl(__assign({}, params, { prompt: 'none', response_mode: 'web_message' }));
return [4 /*yield*/, runIframe(url, this.domainUrl)];
case 2:
codeResult = _a.sent();
if (stateIn !== codeResult.state) {
throw new Error('Invalid state');
}
return [4 /*yield*/, oauthToken({
baseUrl: this.domainUrl,
audience: this.options.audience,
client_id: this.options.client_id,
code_verifier: code_verifier,
code: codeResult.code
})];
case 3:
authResult = _a.sent();
decodedToken = this._verifyIdToken(authResult.id_token, nonceIn);
cacheEntry = __assign({}, authResult, { decodedToken: decodedToken, scope: params.scope, audience: params.audience || 'default' });
this.cache.save(cacheEntry);
save('auth0.is.authenticated', true, { daysUntilExpire: 1 });
return [2 /*return*/, authResult.access_token];
}
});
});
};
/**
* ```js
* const token = await auth0.getTokenWithPopup(options);
* ```
* Opens a popup with the `/authorize` URL using the parameters
* provided as arguments. Random and secure `state` and `nonce`
* parameters will be auto-generated. If the response is successful,
* results will be valid according to their expiration times.
*
* @param options
*/
Auth0Client.prototype.getTokenWithPopup = function (options) {
if (options === void 0) { options = {
audience: this.options.audience,
scope: this.options.scope || this.DEFAULT_SCOPE
}; }
return __awaiter(this, void 0, void 0, function () {
var cache;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
options.scope = getUniqueScopes(this.DEFAULT_SCOPE, this.options.scope, options.scope);
return [4 /*yield*/, this.loginWithPopup(options)];
case 1:
_a.sent();
cache = this.cache.get({
scope: options.scope,
audience: options.audience || 'default'
});
return [2 /*return*/, cache.access_token];
}
});
});
};
/**
* ```js
* const isAuthenticated = await auth0.isAuthenticated();
* ```
*
* Returns `true` if there's valid information stored,
* otherwise returns `false`.
*
*/
Auth0Client.prototype.isAuthenticated = function () {
return __awaiter(this, void 0, void 0, function () {
var user;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getUser()];
case 1:
user = _a.sent();
return [2 /*return*/, !!user];
}
});
});
};
/**
* ```js
* auth0.logout();
* ```
*
* Performs a redirect to `/v2/logout` using the parameters provided
* as arguments. [Read more about how Logout works at Auth0](https://auth0.com/docs/logout).
*
* @param options
*/
Auth0Client.prototype.logout = function (options) {
if (options === void 0) { options = {}; }
if (options.client_id !== null) {
options.client_id = options.client_id || this.options.client_id;
}
else {
delete options.client_id;
}
remove('auth0.is.authenticated');
var url = this._url("/v2/logout?" + createQueryParams(options));
window.location.assign(url);
};
return Auth0Client;
}());
function createAuth0Client(options) {
return __awaiter(this, void 0, void 0, function () {
var auth0, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
auth0 = new Auth0Client(options);
if (!get('auth0.is.authenticated')) {
return [2 /*return*/, auth0];
}
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, auth0.getTokenSilently({
audience: options.audience,
scope: options.scope,
ignoreCache: true
})];
case 2:
_a.sent();
return [3 /*break*/, 4];
case 3:
error_1 = _a.sent();
return [3 /*break*/, 4];
case 4: return [2 /*return*/, auth0];
}
});
});
}
module.exports = createAuth0Client;
//# sourceMappingURL=auth0-spa-js.cjs.js.map