init
This commit is contained in:
commit
d282e2bcae
3481 files changed
+568488
No files matched your search
+588
@@ -0,0 +1,588 @@
|
||||
import React, { createContext, useState, useReducer, useRef, useCallback, useEffect, useMemo, useContext } from 'react';
|
||||
|
||||
/******************************************************************************
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
PERFORMANCE OF THIS SOFTWARE.
|
||||
***************************************************************************** */
|
||||
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
|
||||
|
||||
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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
|
||||
return extendStatics(d, b);
|
||||
};
|
||||
|
||||
function __extends(d, b) {
|
||||
if (typeof b !== "function" && b !== null)
|
||||
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
|
||||
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) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
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) : adopt(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 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
||||
return g.next = verb(0), g["throw"] = verb(1), g["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 (g && (g = 0, op[0] && (_ = 0)), _) 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 };
|
||||
}
|
||||
}
|
||||
|
||||
function __spreadArray(to, from, pack) {
|
||||
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
|
||||
if (ar || !(i in from)) {
|
||||
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
|
||||
ar[i] = from[i];
|
||||
}
|
||||
}
|
||||
return to.concat(ar || Array.prototype.slice.call(from));
|
||||
}
|
||||
|
||||
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
|
||||
var e = new Error(message);
|
||||
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
||||
};
|
||||
|
||||
function e(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(o=Object.getOwnPropertySymbols(e);i<o.length;i++)t.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(e,o[i])&&(n[o[i]]=e[o[i]]);}return n}"function"==typeof SuppressedError&&SuppressedError;var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function o(e,t){return e(t={exports:{}},t.exports),t.exports}var i=o((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,n){var o=e.locked.get(t);void 0===o?void 0===n?e.locked.set(t,[]):e.locked.set(t,[n]):void 0!==n&&(o.unshift(n),e.locked.set(t,o));},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise((function(n,o){e.isLocked(t)?e.addToLocked(t,n):(e.addToLocked(t),n());}))},this.unlock=function(t){var n=e.locked.get(t);if(void 0!==n&&0!==n.length){var o=n.pop();e.locked.set(t,n),void 0!==o&&setTimeout(o,0);}else e.locked.delete(t);};}return e.getInstance=function(){return void 0===e.instance&&(e.instance=new e),e.instance},e}();t.default=function(){return n.getInstance()};}));n(i);var r=n(o((function(e,n){var o=t&&t.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function s(e){try{c(o.next(e));}catch(e){r(e);}}function a(e){try{c(o.throw(e));}catch(e){r(e);}}function c(e){e.done?i(e.value):new n((function(t){t(e.value);})).then(s,a);}c((o=o.apply(e,t||[])).next());}))},r=t&&t.__generator||function(e,t){var n,o,i,r,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,o&&(i=2&r[0]?o.return:r[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,r[1])).done)return i;switch(o=0,i&&(r=[2&r[0],i.value]),r[0]){case 0:case 1:i=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,o=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==r[0]&&2!==r[0])){s=0;continue}if(3===r[0]&&(!i||r[1]>i[0]&&r[1]<i[3])){s.label=r[1];break}if(6===r[0]&&s.label<i[1]){s.label=i[1],i=r;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(r);break}i[2]&&s.ops.pop(),s.trys.pop();continue}r=t.call(e,s);}catch(e){r=[6,e],o=0;}finally{n=i=0;}if(5&r[0])throw r[1];return {value:r[0]?r[1]:void 0,done:!0}}([r,a])}}},s=t;Object.defineProperty(n,"__esModule",{value:!0});var a="browser-tabs-lock-key",c={key:function(e){return o(s,void 0,void 0,(function(){return r(this,(function(e){throw new Error("Unsupported")}))}))},getItem:function(e){return o(s,void 0,void 0,(function(){return r(this,(function(e){throw new Error("Unsupported")}))}))},clear:function(){return o(s,void 0,void 0,(function(){return r(this,(function(e){return [2,window.localStorage.clear()]}))}))},removeItem:function(e){return o(s,void 0,void 0,(function(){return r(this,(function(e){throw new Error("Unsupported")}))}))},setItem:function(e,t){return o(s,void 0,void 0,(function(){return r(this,(function(e){throw new Error("Unsupported")}))}))},keySync:function(e){return window.localStorage.key(e)},getItemSync:function(e){return window.localStorage.getItem(e)},clearSync:function(){return window.localStorage.clear()},removeItemSync:function(e){return window.localStorage.removeItem(e)},setItemSync:function(e,t){return window.localStorage.setItem(e,t)}};function u(e){return new Promise((function(t){return setTimeout(t,e)}))}function d(e){for(var t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",n="",o=0;o<e;o++){n+=t[Math.floor(Math.random()*t.length)];}return n}var h=function(){function e(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+d(15),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=t,void 0===e.waiters&&(e.waiters=[]);}return e.prototype.acquireLock=function(t,n){return void 0===n&&(n=5e3),o(this,void 0,void 0,(function(){var o,i,s,h,l,p,m;return r(this,(function(r){switch(r.label){case 0:o=Date.now()+d(4),i=Date.now()+n,s=a+"-"+t,h=void 0===this.storageHandler?c:this.storageHandler,r.label=1;case 1:return Date.now()<i?[4,u(30)]:[3,8];case 2:return r.sent(),null!==h.getItemSync(s)?[3,5]:(l=this.id+"-"+t+"-"+o,[4,u(MathLine truncated
|
||||
|
||||
/**
|
||||
* The initial auth state.
|
||||
*/
|
||||
var initialAuthState = {
|
||||
isAuthenticated: false,
|
||||
isLoading: true,
|
||||
error: undefined,
|
||||
user: undefined,
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
var stub = function () {
|
||||
throw new Error('You forgot to wrap your component in <Auth0Provider>.');
|
||||
};
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
var initialContext = __assign(__assign({}, initialAuthState), { buildAuthorizeUrl: stub, buildLogoutUrl: stub, getAccessTokenSilently: stub, getAccessTokenWithPopup: stub, getIdTokenClaims: stub, loginWithRedirect: stub, loginWithPopup: stub, connectAccountWithRedirect: stub, logout: stub, handleRedirectCallback: stub, getDpopNonce: stub, setDpopNonce: stub, generateDpopProof: stub, createFetcher: stub });
|
||||
/**
|
||||
* The Auth0 Context
|
||||
*/
|
||||
var Auth0Context = createContext(initialContext);
|
||||
|
||||
/**
|
||||
* An OAuth2 error will come from the authorization server and will have at least an `error` property which will
|
||||
* be the error code. And possibly an `error_description` property
|
||||
*
|
||||
* See: https://openid.net/specs/openid-connect-core-1_0.html#rfc.section.3.1.2.6
|
||||
*/
|
||||
var OAuthError = /** @class */ (function (_super) {
|
||||
__extends(OAuthError, _super);
|
||||
function OAuthError(error, error_description) {
|
||||
var _this = _super.call(this, error_description !== null && error_description !== void 0 ? error_description : error) || this;
|
||||
_this.error = error;
|
||||
_this.error_description = error_description;
|
||||
// https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
|
||||
Object.setPrototypeOf(_this, OAuthError.prototype);
|
||||
return _this;
|
||||
}
|
||||
return OAuthError;
|
||||
}(Error));
|
||||
|
||||
var CODE_RE = /[?&](?:connect_)?code=[^&]+/;
|
||||
var STATE_RE = /[?&]state=[^&]+/;
|
||||
var ERROR_RE = /[?&]error=[^&]+/;
|
||||
var hasAuthParams = function (searchParams) {
|
||||
if (searchParams === void 0) { searchParams = window.location.search; }
|
||||
return (CODE_RE.test(searchParams) || ERROR_RE.test(searchParams)) &&
|
||||
STATE_RE.test(searchParams);
|
||||
};
|
||||
var normalizeErrorFn = function (fallbackMessage) {
|
||||
return function (error) {
|
||||
if (error instanceof Error) {
|
||||
return error;
|
||||
}
|
||||
// try to check errors of the following form: {error: string; error_description?: string}
|
||||
if (error !== null &&
|
||||
typeof error === 'object' &&
|
||||
'error' in error &&
|
||||
typeof error.error === 'string') {
|
||||
if ('error_description' in error &&
|
||||
typeof error.error_description === 'string') {
|
||||
var e_1 = error;
|
||||
return new OAuthError(e_1.error, e_1.error_description);
|
||||
}
|
||||
var e = error;
|
||||
return new OAuthError(e.error);
|
||||
}
|
||||
return new Error(fallbackMessage);
|
||||
};
|
||||
};
|
||||
var loginError = normalizeErrorFn('Login failed');
|
||||
var tokenError = normalizeErrorFn('Get access token failed');
|
||||
/**
|
||||
* @ignore
|
||||
* Helper function to map the v1 `redirectUri` option to the v2 `authorizationParams.redirect_uri`
|
||||
* and log a warning.
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
var deprecateRedirectUri = function (options) {
|
||||
var _a, _b;
|
||||
if (options === null || options === void 0 ? void 0 : options.redirectUri) {
|
||||
console.warn('Using `redirectUri` has been deprecated, please use `authorizationParams.redirect_uri` instead as `redirectUri` will be no longer supported in a future version');
|
||||
options.authorizationParams = (_a = options.authorizationParams) !== null && _a !== void 0 ? _a : {};
|
||||
options.authorizationParams.redirect_uri = options.redirectUri;
|
||||
delete options.redirectUri;
|
||||
}
|
||||
if ((_b = options === null || options === void 0 ? void 0 : options.authorizationParams) === null || _b === void 0 ? void 0 : _b.redirectUri) {
|
||||
console.warn('Using `authorizationParams.redirectUri` has been deprecated, please use `authorizationParams.redirect_uri` instead as `authorizationParams.redirectUri` will be removed in a future version');
|
||||
options.authorizationParams.redirect_uri =
|
||||
options.authorizationParams.redirectUri;
|
||||
delete options.authorizationParams.redirectUri;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles how that state changes in the `useAuth0` hook.
|
||||
*/
|
||||
var reducer = function (state, action) {
|
||||
switch (action.type) {
|
||||
case 'LOGIN_POPUP_STARTED':
|
||||
return __assign(__assign({}, state), { isLoading: true });
|
||||
case 'LOGIN_POPUP_COMPLETE':
|
||||
case 'INITIALISED':
|
||||
return __assign(__assign({}, state), { isAuthenticated: !!action.user, user: action.user, isLoading: false, error: undefined });
|
||||
case 'HANDLE_REDIRECT_COMPLETE':
|
||||
case 'GET_ACCESS_TOKEN_COMPLETE':
|
||||
if (state.user === action.user) {
|
||||
return state;
|
||||
}
|
||||
return __assign(__assign({}, state), { isAuthenticated: !!action.user, user: action.user });
|
||||
case 'LOGOUT':
|
||||
return __assign(__assign({}, state), { isAuthenticated: false, user: undefined });
|
||||
case 'ERROR':
|
||||
return __assign(__assign({}, state), { isLoading: false, error: action.error });
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
var toAuth0ClientOptions = function (opts) {
|
||||
deprecateRedirectUri(opts);
|
||||
return __assign(__assign({}, opts), { auth0Client: {
|
||||
name: 'auth0-react',
|
||||
version: '2.9.0',
|
||||
} });
|
||||
};
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
var defaultOnRedirectCallback = function (appState) {
|
||||
var _a;
|
||||
window.history.replaceState({}, document.title, (_a = appState.returnTo) !== null && _a !== void 0 ? _a : window.location.pathname);
|
||||
};
|
||||
/**
|
||||
* ```jsx
|
||||
* <Auth0Provider
|
||||
* domain={domain}
|
||||
* clientId={clientId}
|
||||
* authorizationParams={{ redirect_uri: window.location.origin }}>
|
||||
* <MyApp />
|
||||
* </Auth0Provider>
|
||||
* ```
|
||||
*
|
||||
* Provides the Auth0Context to its child components.
|
||||
*/
|
||||
var Auth0Provider = function (opts) {
|
||||
var children = opts.children, skipRedirectCallback = opts.skipRedirectCallback, _a = opts.onRedirectCallback, onRedirectCallback = _a === void 0 ? defaultOnRedirectCallback : _a, _b = opts.context, context = _b === void 0 ? Auth0Context : _b, clientOpts = __rest(opts, ["children", "skipRedirectCallback", "onRedirectCallback", "context"]);
|
||||
var client = useState(function () { return new Ue(toAuth0ClientOptions(clientOpts)); })[0];
|
||||
var _c = useReducer((reducer), initialAuthState), state = _c[0], dispatch = _c[1];
|
||||
var didInitialise = useRef(false);
|
||||
var handleError = useCallback(function (error) {
|
||||
dispatch({ type: 'ERROR', error: error });
|
||||
return error;
|
||||
}, []);
|
||||
useEffect(function () {
|
||||
if (didInitialise.current) {
|
||||
return;
|
||||
}
|
||||
didInitialise.current = true;
|
||||
(function () { return __awaiter(void 0, void 0, void 0, function () {
|
||||
var user, _a, _b, appState, response_type, result, error_1;
|
||||
return __generator(this, function (_c) {
|
||||
switch (_c.label) {
|
||||
case 0:
|
||||
_c.trys.push([0, 7, , 8]);
|
||||
user = void 0;
|
||||
if (!(hasAuthParams() && !skipRedirectCallback)) return [3 /*break*/, 3];
|
||||
return [4 /*yield*/, client.handleRedirectCallback()];
|
||||
case 1:
|
||||
_a = _c.sent(), _b = _a.appState, appState = _b === void 0 ? {} : _b, response_type = _a.response_type, result = __rest(_a, ["appState", "response_type"]);
|
||||
return [4 /*yield*/, client.getUser()];
|
||||
case 2:
|
||||
user = _c.sent();
|
||||
appState.response_type = response_type;
|
||||
if (response_type === ge.ConnectCode) {
|
||||
appState.connectedAccount = result;
|
||||
}
|
||||
onRedirectCallback(appState, user);
|
||||
return [3 /*break*/, 6];
|
||||
case 3: return [4 /*yield*/, client.checkSession()];
|
||||
case 4:
|
||||
_c.sent();
|
||||
return [4 /*yield*/, client.getUser()];
|
||||
case 5:
|
||||
user = _c.sent();
|
||||
_c.label = 6;
|
||||
case 6:
|
||||
dispatch({ type: 'INITIALISED', user: user });
|
||||
return [3 /*break*/, 8];
|
||||
case 7:
|
||||
error_1 = _c.sent();
|
||||
handleError(loginError(error_1));
|
||||
return [3 /*break*/, 8];
|
||||
case 8: return [2 /*return*/];
|
||||
}
|
||||
});
|
||||
}); })();
|
||||
}, [client, onRedirectCallback, skipRedirectCallback, handleError]);
|
||||
var loginWithRedirect = useCallback(function (opts) {
|
||||
deprecateRedirectUri(opts);
|
||||
return client.loginWithRedirect(opts);
|
||||
}, [client]);
|
||||
var loginWithPopup = useCallback(function (options, config) { return __awaiter(void 0, void 0, void 0, function () {
|
||||
var error_2, user;
|
||||
return __generator(this, function (_a) {
|
||||
switch (_a.label) {
|
||||
case 0:
|
||||
dispatch({ type: 'LOGIN_POPUP_STARTED' });
|
||||
_a.label = 1;
|
||||
case 1:
|
||||
_a.trys.push([1, 3, , 4]);
|
||||
return [4 /*yield*/, client.loginWithPopup(options, config)];
|
||||
case 2:
|
||||
_a.sent();
|
||||
return [3 /*break*/, 4];
|
||||
case 3:
|
||||
error_2 = _a.sent();
|
||||
handleError(loginError(error_2));
|
||||
return [2 /*return*/];
|
||||
case 4: return [4 /*yield*/, client.getUser()];
|
||||
case 5:
|
||||
user = _a.sent();
|
||||
dispatch({ type: 'LOGIN_POPUP_COMPLETE', user: user });
|
||||
return [2 /*return*/];
|
||||
}
|
||||
});
|
||||
}); }, [client, handleError]);
|
||||
var logout = useCallback(function () {
|
||||
var args_1 = [];
|
||||
for (var _i = 0; _i < arguments.length; _i++) {
|
||||
args_1[_i] = arguments[_i];
|
||||
}
|
||||
return __awaiter(void 0, __spreadArray([], args_1, true), void 0, function (opts) {
|
||||
if (opts === void 0) { opts = {}; }
|
||||
return __generator(this, function (_a) {
|
||||
switch (_a.label) {
|
||||
case 0: return [4 /*yield*/, client.logout(opts)];
|
||||
case 1:
|
||||
_a.sent();
|
||||
if (opts.openUrl || opts.openUrl === false) {
|
||||
dispatch({ type: 'LOGOUT' });
|
||||
}
|
||||
return [2 /*return*/];
|
||||
}
|
||||
});
|
||||
});
|
||||
}, [client]);
|
||||
var getAccessTokenSilently = useCallback(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
function (opts) { return __awaiter(void 0, void 0, void 0, function () {
|
||||
var token, error_3, _a;
|
||||
var _b;
|
||||
return __generator(this, function (_c) {
|
||||
switch (_c.label) {
|
||||
case 0:
|
||||
_c.trys.push([0, 2, 3, 5]);
|
||||
return [4 /*yield*/, client.getTokenSilently(opts)];
|
||||
case 1:
|
||||
token = _c.sent();
|
||||
return [3 /*break*/, 5];
|
||||
case 2:
|
||||
error_3 = _c.sent();
|
||||
throw tokenError(error_3);
|
||||
case 3:
|
||||
_a = dispatch;
|
||||
_b = {
|
||||
type: 'GET_ACCESS_TOKEN_COMPLETE'
|
||||
};
|
||||
return [4 /*yield*/, client.getUser()];
|
||||
case 4:
|
||||
_a.apply(void 0, [(_b.user = _c.sent(),
|
||||
_b)]);
|
||||
return [7 /*endfinally*/];
|
||||
case 5: return [2 /*return*/, token];
|
||||
}
|
||||
});
|
||||
}); }, [client]);
|
||||
var getAccessTokenWithPopup = useCallback(function (opts, config) { return __awaiter(void 0, void 0, void 0, function () {
|
||||
var token, error_4, _a;
|
||||
var _b;
|
||||
return __generator(this, function (_c) {
|
||||
switch (_c.label) {
|
||||
case 0:
|
||||
_c.trys.push([0, 2, 3, 5]);
|
||||
return [4 /*yield*/, client.getTokenWithPopup(opts, config)];
|
||||
case 1:
|
||||
token = _c.sent();
|
||||
return [3 /*break*/, 5];
|
||||
case 2:
|
||||
error_4 = _c.sent();
|
||||
throw tokenError(error_4);
|
||||
case 3:
|
||||
_a = dispatch;
|
||||
_b = {
|
||||
type: 'GET_ACCESS_TOKEN_COMPLETE'
|
||||
};
|
||||
return [4 /*yield*/, client.getUser()];
|
||||
case 4:
|
||||
_a.apply(void 0, [(_b.user = _c.sent(),
|
||||
_b)]);
|
||||
return [7 /*endfinally*/];
|
||||
case 5: return [2 /*return*/, token];
|
||||
}
|
||||
});
|
||||
}); }, [client]);
|
||||
var connectAccountWithRedirect = useCallback(function (options) {
|
||||
return client.connectAccountWithRedirect(options);
|
||||
}, [client]);
|
||||
var getIdTokenClaims = useCallback(function () { return client.getIdTokenClaims(); }, [client]);
|
||||
var handleRedirectCallback = useCallback(function (url) { return __awaiter(void 0, void 0, void 0, function () {
|
||||
var error_5, _a;
|
||||
var _b;
|
||||
return __generator(this, function (_c) {
|
||||
switch (_c.label) {
|
||||
case 0:
|
||||
_c.trys.push([0, 2, 3, 5]);
|
||||
return [4 /*yield*/, client.handleRedirectCallback(url)];
|
||||
case 1: return [2 /*return*/, _c.sent()];
|
||||
case 2:
|
||||
error_5 = _c.sent();
|
||||
throw tokenError(error_5);
|
||||
case 3:
|
||||
_a = dispatch;
|
||||
_b = {
|
||||
type: 'HANDLE_REDIRECT_COMPLETE'
|
||||
};
|
||||
return [4 /*yield*/, client.getUser()];
|
||||
case 4:
|
||||
_a.apply(void 0, [(_b.user = _c.sent(),
|
||||
_b)]);
|
||||
return [7 /*endfinally*/];
|
||||
case 5: return [2 /*return*/];
|
||||
}
|
||||
});
|
||||
}); }, [client]);
|
||||
var getDpopNonce = useCallback(function (id) { return client.getDpopNonce(id); }, [client]);
|
||||
var setDpopNonce = useCallback(function (nonce, id) { return client.setDpopNonce(nonce, id); }, [client]);
|
||||
var generateDpopProof = useCallback(function (params) { return client.generateDpopProof(params); }, [client]);
|
||||
var createFetcher = useCallback(function (config) { return client.createFetcher(config); }, [client]);
|
||||
var contextValue = useMemo(function () {
|
||||
return __assign(__assign({}, state), { getAccessTokenSilently: getAccessTokenSilently, getAccessTokenWithPopup: getAccessTokenWithPopup, getIdTokenClaims: getIdTokenClaims, loginWithRedirect: loginWithRedirect, loginWithPopup: loginWithPopup, connectAccountWithRedirect: connectAccountWithRedirect, logout: logout, handleRedirectCallback: handleRedirectCallback, getDpopNonce: getDpopNonce, setDpopNonce: setDpopNonce, generateDpopProof: generateDpopProof, createFetcher: createFetcher });
|
||||
}, [
|
||||
state,
|
||||
getAccessTokenSilently,
|
||||
getAccessTokenWithPopup,
|
||||
getIdTokenClaims,
|
||||
loginWithRedirect,
|
||||
loginWithPopup,
|
||||
connectAccountWithRedirect,
|
||||
logout,
|
||||
handleRedirectCallback,
|
||||
getDpopNonce,
|
||||
setDpopNonce,
|
||||
generateDpopProof,
|
||||
createFetcher,
|
||||
]);
|
||||
return React.createElement(context.Provider, { value: contextValue }, children);
|
||||
};
|
||||
|
||||
/**
|
||||
* ```js
|
||||
* const {
|
||||
* // Auth state:
|
||||
* error,
|
||||
* isAuthenticated,
|
||||
* isLoading,
|
||||
* user,
|
||||
* // Auth methods:
|
||||
* getAccessTokenSilently,
|
||||
* getAccessTokenWithPopup,
|
||||
* getIdTokenClaims,
|
||||
* loginWithRedirect,
|
||||
* loginWithPopup,
|
||||
* logout,
|
||||
* } = useAuth0<TUser>();
|
||||
* ```
|
||||
*
|
||||
* Use the `useAuth0` hook in your components to access the auth state and methods.
|
||||
*
|
||||
* TUser is an optional type param to provide a type to the `user` field.
|
||||
*/
|
||||
var useAuth0 = function (context) {
|
||||
if (context === void 0) { context = Auth0Context; }
|
||||
return useContext(context);
|
||||
};
|
||||
|
||||
/**
|
||||
* ```jsx
|
||||
* class MyComponent extends Component {
|
||||
* render() {
|
||||
* // Access the auth context from the `auth0` prop
|
||||
* const { user } = this.props.auth0;
|
||||
* return <div>Hello {user.name}!</div>
|
||||
* }
|
||||
* }
|
||||
* // Wrap your class component in withAuth0
|
||||
* export default withAuth0(MyComponent);
|
||||
* ```
|
||||
*
|
||||
* Wrap your class components in this Higher Order Component to give them access to the Auth0Context.
|
||||
*
|
||||
* Providing a context as the second argument allows you to configure the Auth0Provider the Auth0Context
|
||||
* should come from f you have multiple within your application.
|
||||
*/
|
||||
var withAuth0 = function (Component, context) {
|
||||
if (context === void 0) { context = Auth0Context; }
|
||||
return function WithAuth(props) {
|
||||
return (React.createElement(context.Consumer, null, function (auth) { return (React.createElement(Component, __assign({}, props, { auth0: auth }))); }));
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
var defaultOnRedirecting = function () { return React.createElement(React.Fragment, null); };
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
var defaultOnBeforeAuthentication = function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) {
|
||||
return [2 /*return*/];
|
||||
}); }); };
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
var defaultReturnTo = function () {
|
||||
return "".concat(window.location.pathname).concat(window.location.search);
|
||||
};
|
||||
/**
|
||||
* ```js
|
||||
* const MyProtectedComponent = withAuthenticationRequired(MyComponent);
|
||||
* ```
|
||||
*
|
||||
* When you wrap your components in this Higher Order Component and an anonymous user visits your component
|
||||
* they will be redirected to the login page; after login they will be returned to the page they were redirected from.
|
||||
*/
|
||||
var withAuthenticationRequired = function (Component, options) {
|
||||
if (options === void 0) { options = {}; }
|
||||
return function WithAuthenticationRequired(props) {
|
||||
var _this = this;
|
||||
var _a = options.returnTo, returnTo = _a === void 0 ? defaultReturnTo : _a, _b = options.onRedirecting, onRedirecting = _b === void 0 ? defaultOnRedirecting : _b, _c = options.onBeforeAuthentication, onBeforeAuthentication = _c === void 0 ? defaultOnBeforeAuthentication : _c, loginOptions = options.loginOptions, _d = options.context, context = _d === void 0 ? Auth0Context : _d;
|
||||
var _e = useAuth0(context), isAuthenticated = _e.isAuthenticated, isLoading = _e.isLoading, loginWithRedirect = _e.loginWithRedirect;
|
||||
useEffect(function () {
|
||||
if (isLoading || isAuthenticated) {
|
||||
return;
|
||||
}
|
||||
var opts = __assign(__assign({}, loginOptions), { appState: __assign(__assign({}, loginOptions === null || loginOptions === void 0 ? void 0 : loginOptions.appState), { returnTo: typeof returnTo === 'function' ? returnTo() : returnTo }) });
|
||||
void (function () { return __awaiter(_this, void 0, void 0, function () {
|
||||
return __generator(this, function (_a) {
|
||||
switch (_a.label) {
|
||||
case 0: return [4 /*yield*/, onBeforeAuthentication()];
|
||||
case 1:
|
||||
_a.sent();
|
||||
return [4 /*yield*/, loginWithRedirect(opts)];
|
||||
case 2:
|
||||
_a.sent();
|
||||
return [2 /*return*/];
|
||||
}
|
||||
});
|
||||
}); })();
|
||||
}, [
|
||||
isLoading,
|
||||
isAuthenticated,
|
||||
loginWithRedirect,
|
||||
onBeforeAuthentication,
|
||||
loginOptions,
|
||||
returnTo,
|
||||
]);
|
||||
return isAuthenticated ? React.createElement(Component, __assign({}, props)) : onRedirecting();
|
||||
};
|
||||
};
|
||||
|
||||
export { Auth0Context, Auth0Provider, d as AuthenticationError, h as ConnectError, u as GenericError, oe as InMemoryCache, ne as LocalStorageCache, f as MfaRequiredError, g as MissingRefreshTokenError, OAuthError, m as PopupCancelledError, p as PopupTimeoutError, ge as ResponseType, l as TimeoutError, w as UseDpopNonceError, ye as User, initialContext, useAuth0, withAuth0, withAuthenticationRequired };
|
||||
//# sourceMappingURL=auth0-react.esm.js.map
|
||||
Reference in new issue
Block a user