This commit is contained in:
nucther committed 2025-12-01 23:23:05 +07:00
commit d282e2bcae
3481 files changed
+568488

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Auth0
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+185
View File
@@ -0,0 +1,185 @@
![Auth0 SDK for React Single Page Applications](https://cdn.auth0.com/website/sdks/banners/auth0-react-banner.png)
[![npm](https://img.shields.io/npm/v/@auth0/auth0-react.svg?style=flat)](https://www.npmjs.com/package/@auth0/auth0-react)
[![codecov](https://img.shields.io/codecov/c/github/auth0/auth0-react/main.svg?style=flat)](https://codecov.io/gh/auth0/auth0-react)
[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/auth0/auth0-react)
![Downloads](https://img.shields.io/npm/dw/@auth0/auth0-react)
[![License](https://img.shields.io/:license-mit-blue.svg?style=flat)](https://opensource.org/licenses/MIT)
[![CircleCI](https://img.shields.io/circleci/build/github/auth0/auth0-react.svg?branch=main&style=flat)](https://circleci.com/gh/auth0/auth0-react)
📚 [Documentation](#documentation) - 🚀 [Getting Started](#getting-started) - 💻 [API Reference](#api-reference) - 💬 [Feedback](#feedback)
## Documentation
- [Quickstart](https://auth0.com/docs/quickstart/spa/react) - our interactive guide for quickly adding login, logout and user information to a React app using Auth0.
- [Sample App](https://github.com/auth0-samples/auth0-react-samples/tree/master/Sample-01) - a full-fledged React application integrated with Auth0.
- [FAQs](https://github.com/auth0/auth0-react/blob/main/FAQ.md) - frequently asked questions about the auth0-react SDK.
- [Examples](https://github.com/auth0/auth0-react/blob/main/EXAMPLES.md) - code samples for common React authentication scenario's.
- [Docs site](https://www.auth0.com/docs) - explore our docs site and learn more about Auth0.
## Getting started
### Installation
Using [npm](https://npmjs.org/)
```bash
npm install @auth0/auth0-react
```
Using [yarn](https://yarnpkg.com/)
```bash
yarn add @auth0/auth0-react
```
### Configure Auth0
Create a **Single Page Application** in the [Auth0 Dashboard](https://manage.auth0.com/#/applications).
> **If you're using an existing application**, verify that you have configured the following settings in your Single Page Application:
>
> - Click on the "Settings" tab of your application's page.
> - Scroll down and click on the "Show Advanced Settings" link.
> - Under "Advanced Settings", click on the "OAuth" tab.
> - Ensure that "JsonWebToken Signature Algorithm" is set to `RS256` and that "OIDC Conformant" is enabled.
Next, configure the following URLs for your application under the "Application URIs" section of the "Settings" page:
- **Allowed Callback URLs**: `http://localhost:3000`
- **Allowed Logout URLs**: `http://localhost:3000`
- **Allowed Web Origins**: `http://localhost:3000`
> These URLs should reflect the origins that your application is running on. **Allowed Callback URLs** may also include a path, depending on where you're handling the callback.
Take note of the **Client ID** and **Domain** values under the "Basic Information" section. You'll need these values in the next step.
### Configure the SDK
Configure the SDK by wrapping your application in `Auth0Provider`:
```jsx
// src/index.js
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Auth0Provider } from '@auth0/auth0-react';
import App from './App';
const root = createRoot(document.getElementById('app'));
root.render(
<Auth0Provider
domain="YOUR_AUTH0_DOMAIN"
clientId="YOUR_AUTH0_CLIENT_ID"
authorizationParams={{
redirect_uri: window.location.origin,
}}
>
<App />
</Auth0Provider>
);
```
<details>
<summary>Instructions for React <18</summary>
<br>
```jsx
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Auth0Provider } from '@auth0/auth0-react';
import App from './App';
ReactDOM.render(
<Auth0Provider
domain="YOUR_AUTH0_DOMAIN"
clientId="YOUR_AUTH0_CLIENT_ID"
authorizationParams={{
redirect_uri: window.location.origin,
}}
>
<App />
</Auth0Provider>,
document.getElementById('app')
);
```
</details>
Use the `useAuth0` hook in your components to access authentication state (`isLoading`, `isAuthenticated` and `user`) and authentication methods (`loginWithRedirect` and `logout`):
```jsx
// src/App.js
import React from 'react';
import { useAuth0 } from '@auth0/auth0-react';
function App() {
const { isLoading, isAuthenticated, error, user, loginWithRedirect, logout } =
useAuth0();
if (isLoading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Oops... {error.message}</div>;
}
if (isAuthenticated) {
return (
<div>
Hello {user.name}{' '}
<button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })}>
Log out
</button>
</div>
);
} else {
return <button onClick={() => loginWithRedirect()}>Log in</button>;
}
}
export default App;
```
For more code samples on how to integrate **auth0-react** SDK in your **React** application, have a look at our [examples](https://github.com/auth0/auth0-react/blob/main/EXAMPLES.md).
## API reference
Explore public API's available in auth0-react.
- [Auth0Provider](https://auth0.github.io/auth0-react/functions/Auth0Provider.html)
- [Auth0ProviderOptions](https://auth0.github.io/auth0-react/interfaces/Auth0ProviderOptions.html)
- [useAuth0](https://auth0.github.io/auth0-react/functions/useAuth0.html)
- [withAuth0](https://auth0.github.io/auth0-react/functions/withAuth0.html)
- [withAuthenticationRequired](https://auth0.github.io/auth0-react/functions/withAuthenticationRequired.html)
## Feedback
### Contributing
We appreciate feedback and contribution to this repo! Before you get started, please see the following:
- [Auth0's general contribution guidelines](https://github.com/auth0/open-source-template/blob/master/GENERAL-CONTRIBUTING.md)
- [Auth0's code of conduct guidelines](https://github.com/auth0/open-source-template/blob/master/CODE-OF-CONDUCT.md)
- [This repo's contribution guide](https://github.com/auth0/auth0-react/blob/main/CONTRIBUTING.md)
### Raise an issue
To provide feedback or report a bug, please [raise an issue on our issue tracker](https://github.com/auth0/auth0-react/issues).
### Vulnerability Reporting
Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/responsible-disclosure-policy) details the procedure for disclosing security issues.
---
<p align="center">
<picture>
<source media="(prefers-color-scheme: light)" srcset="https://cdn.auth0.com/website/sdks/logos/auth0_light_mode.png" width="150">
<source media="(prefers-color-scheme: dark)" srcset="https://cdn.auth0.com/website/sdks/logos/auth0_dark_mode.png" width="150">
<img alt="Auth0 Logo" src="https://cdn.auth0.com/website/sdks/logos/auth0_light_mode.png" width="150">
</picture>
</p>
<p align="center">Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout <a href="https://auth0.com/why-auth0">Why Auth0?</a></p>
<p align="center">
This project is licensed under the MIT license. See the <a href="https://github.com/auth0/auth0-react/blob/main/LICENSE"> LICENSE</a> file for more info.</p>
+15
View File
@@ -0,0 +1,15 @@
import { User } from '@auth0/auth0-spa-js';
/**
* The auth state which, when combined with the auth methods, make up the return object of the `useAuth0` hook.
*/
export interface AuthState<TUser extends User = User> {
error: Error | undefined;
isAuthenticated: boolean;
isLoading: boolean;
user: TUser | undefined;
}
/**
* The initial auth state.
*/
export declare const initialAuthState: AuthState;
//# sourceMappingURL=auth-state.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"auth-state.d.ts","sourceRoot":"","sources":["../src/auth-state.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAE3C;;GAEG;AACH,MAAM,WAAW,SAAS,CAAC,KAAK,SAAS,IAAI,GAAG,IAAI;IAClD,KAAK,EAAE,KAAK,GAAG,SAAS,CAAC;IACzB,eAAe,EAAE,OAAO,CAAC;IACzB,SAAS,EAAE,OAAO,CAAC;IACnB,IAAI,EAAE,KAAK,GAAG,SAAS,CAAC;CACzB;AAED;;GAEG;AACH,eAAO,MAAM,gBAAgB,EAAE,SAK9B,CAAC"}
+200
View File
@@ -0,0 +1,200 @@
import { GetTokenSilentlyOptions, GetTokenWithPopupOptions, IdToken, LogoutOptions as SPALogoutOptions, PopupLoginOptions, PopupConfigOptions, RedirectLoginResult, User, GetTokenSilentlyVerboseResponse, RedirectLoginOptions as SPARedirectLoginOptions, type Auth0Client, RedirectConnectAccountOptions, ConnectAccountRedirectResult } from '@auth0/auth0-spa-js';
import { AuthState } from './auth-state';
import { AppState } from './auth0-provider';
export interface LogoutOptions extends Omit<SPALogoutOptions, 'onRedirect'> {
}
export interface RedirectLoginOptions<TAppState = AppState> extends Omit<SPARedirectLoginOptions<TAppState>, 'onRedirect'> {
}
/**
* Contains the authenticated state and authentication methods provided by the `useAuth0` hook.
*/
export interface Auth0ContextInterface<TUser extends User = User> extends AuthState<TUser> {
/**
* ```js
* const token = await getAccessTokenSilently(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.
*
* If refresh tokens are used, the token endpoint is called directly with the
* 'refresh_token' grant. If no refresh token is available to make this call,
* the SDK will only fall back to using an iframe to the '/authorize' URL if
* the `useRefreshTokensFallback` setting has been set to `true`. By default this
* setting is `false`.
*
* This method may use a web worker to perform the token call if the in-memory
* cache is used.
*
* If an `audience` value is given to this function, the SDK always falls
* back to using an iframe to make the token exchange.
*
* Note that in all cases, falling back to an iframe requires access to
* the `auth0` cookie.
*/
getAccessTokenSilently: {
(options: GetTokenSilentlyOptions & {
detailedResponse: true;
}): Promise<GetTokenSilentlyVerboseResponse>;
(options?: GetTokenSilentlyOptions): Promise<string>;
(options: GetTokenSilentlyOptions): Promise<GetTokenSilentlyVerboseResponse | string>;
};
/**
* ```js
* const token = await getTokenWithPopup(options, config);
* ```
*
* Get an access token interactively.
*
* 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.
*/
getAccessTokenWithPopup: (options?: GetTokenWithPopupOptions, config?: PopupConfigOptions) => Promise<string | undefined>;
/**
* ```js
* const claims = await getIdTokenClaims();
* ```
*
* Returns all claims from the id_token if available.
*/
getIdTokenClaims: () => Promise<IdToken | undefined>;
/**
* ```js
* await loginWithRedirect(options);
* ```
*
* Performs a redirect to `/authorize` using the parameters
* provided as arguments. Random and secure `state` and `nonce`
* parameters will be auto-generated.
*/
loginWithRedirect: (options?: RedirectLoginOptions<AppState>) => Promise<void>;
/**
* ```js
* await loginWithPopup(options, config);
* ```
*
* 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.
*/
loginWithPopup: (options?: PopupLoginOptions, config?: PopupConfigOptions) => Promise<void>;
/**
* ```js
* await connectAccountWithRedirect({
* connection: 'google-oauth2',
* scopes: ['openid', 'profile', 'email', 'https://www.googleapis.com/auth/drive.readonly'],
* authorization_params: {
* // additional authorization params to forward to the authorization server
* }
* });
* ```
*
* Redirects to the `/connect` URL using the parameters
* provided as arguments. This then redirects to the connection's login page
* where the user can authenticate and authorize the account to be connected.
*
* If connecting the account is successful `onRedirectCallback` will be called
* with the details of the connected account.
*/
connectAccountWithRedirect: (options: RedirectConnectAccountOptions) => Promise<void>;
/**
* ```js
* auth0.logout({ logoutParams: { returnTo: window.location.origin } });
* ```
*
* Clears the application session and performs a redirect to `/v2/logout`, using
* the parameters provided as arguments, to clear the Auth0 session.
* If the `logoutParams.federated` option is specified, it also clears the Identity Provider session.
* [Read more about how Logout works at Auth0](https://auth0.com/docs/logout).
*/
logout: (options?: LogoutOptions) => Promise<void>;
/**
* 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.
*
* @param url The URL to that should be used to retrieve the `state` and `code` values. Defaults to `window.location.href` if not given.
*/
handleRedirectCallback: (url?: string) => Promise<RedirectLoginResult | ConnectAccountRedirectResult>;
/**
* Returns the current DPoP nonce used for making requests to Auth0.
*
* It can return `undefined` because when starting fresh it will not
* be populated until after the first response from the server.
*
* It requires enabling the {@link Auth0ClientOptions.useDpop} option.
*
* @param nonce The nonce value.
* @param id The identifier of a nonce: if absent, it will get the nonce
* used for requests to Auth0. Otherwise, it will be used to
* select a specific non-Auth0 nonce.
*/
getDpopNonce: Auth0Client['getDpopNonce'];
/**
* Sets the current DPoP nonce used for making requests to Auth0.
*
* It requires enabling the {@link Auth0ClientOptions.useDpop} option.
*
* @param nonce The nonce value.
* @param id The identifier of a nonce: if absent, it will set the nonce
* used for requests to Auth0. Otherwise, it will be used to
* select a specific non-Auth0 nonce.
*/
setDpopNonce: Auth0Client['setDpopNonce'];
/**
* Returns a string to be used to demonstrate possession of the private
* key used to cryptographically bind access tokens with DPoP.
*
* It requires enabling the {@link Auth0ClientOptions.useDpop} option.
*/
generateDpopProof: Auth0Client['generateDpopProof'];
/**
* Returns a new `Fetcher` class that will contain a `fetchWithAuth()` method.
* This is a drop-in replacement for the Fetch API's `fetch()` method, but will
* handle certain authentication logic for you, like building the proper auth
* headers or managing DPoP nonces and retries automatically.
*
* Check the `EXAMPLES.md` file for a deeper look into this method.
*/
createFetcher: Auth0Client['createFetcher'];
}
/**
* @ignore
*/
export declare const initialContext: {
buildAuthorizeUrl: () => never;
buildLogoutUrl: () => never;
getAccessTokenSilently: () => never;
getAccessTokenWithPopup: () => never;
getIdTokenClaims: () => never;
loginWithRedirect: () => never;
loginWithPopup: () => never;
connectAccountWithRedirect: () => never;
logout: () => never;
handleRedirectCallback: () => never;
getDpopNonce: () => never;
setDpopNonce: () => never;
generateDpopProof: () => never;
createFetcher: () => never;
error: Error | undefined;
isAuthenticated: boolean;
isLoading: boolean;
user: User | undefined;
};
/**
* The Auth0 Context
*/
declare const Auth0Context: import("react").Context<Auth0ContextInterface<User>>;
export default Auth0Context;
//# sourceMappingURL=auth0-context.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"auth0-context.d.ts","sourceRoot":"","sources":["../src/auth0-context.tsx"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,wBAAwB,EACxB,OAAO,EACP,aAAa,IAAI,gBAAgB,EACjC,iBAAiB,EACjB,kBAAkB,EAClB,mBAAmB,EACnB,IAAI,EACJ,+BAA+B,EAC/B,oBAAoB,IAAI,uBAAuB,EAC/C,KAAK,WAAW,EAChB,6BAA6B,EAC7B,4BAA4B,EAC7B,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,SAAS,EAAoB,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAG5C,MAAM,WAAW,aAAc,SAAQ,IAAI,CAAC,gBAAgB,EAAE,YAAY,CAAC;CAAG;AAE9E,MAAM,WAAW,oBAAoB,CAAC,SAAS,GAAG,QAAQ,CACxD,SAAQ,IAAI,CAAC,uBAAuB,CAAC,SAAS,CAAC,EAAE,YAAY,CAAC;CAAG;AAEnE;;GAEG;AACH,MAAM,WAAW,qBAAqB,CAAC,KAAK,SAAS,IAAI,GAAG,IAAI,CAC9D,SAAQ,SAAS,CAAC,KAAK,CAAC;IACxB;;;;;;;;;;;;;;;;;;;;;;;;;OAyBG;IACH,sBAAsB,EAAE;QACtB,CACE,OAAO,EAAE,uBAAuB,GAAG;YAAE,gBAAgB,EAAE,IAAI,CAAA;SAAE,GAC5D,OAAO,CAAC,+BAA+B,CAAC,CAAC;QAC5C,CAAC,OAAO,CAAC,EAAE,uBAAuB,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;QACrD,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CACzC,+BAA+B,GAAG,MAAM,CACzC,CAAC;KACH,CAAC;IAEF;;;;;;;;;;;OAWG;IACH,uBAAuB,EAAE,CACvB,OAAO,CAAC,EAAE,wBAAwB,EAClC,MAAM,CAAC,EAAE,kBAAkB,KACxB,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAEjC;;;;;;OAMG;IACH,gBAAgB,EAAE,MAAM,OAAO,CAAC,OAAO,GAAG,SAAS,CAAC,CAAC;IAErD;;;;;;;;OAQG;IACH,iBAAiB,EAAE,CACjB,OAAO,CAAC,EAAE,oBAAoB,CAAC,QAAQ,CAAC,KACrC,OAAO,CAAC,IAAI,CAAC,CAAC;IAEnB;;;;;;;;;;;;;OAaG;IACH,cAAc,EAAE,CACd,OAAO,CAAC,EAAE,iBAAiB,EAC3B,MAAM,CAAC,EAAE,kBAAkB,KACxB,OAAO,CAAC,IAAI,CAAC,CAAC;IAEnB;;;;;;;;;;;;;;;;;OAiBG;IACH,0BAA0B,EAAE,CAC1B,OAAO,EAAE,6BAA6B,KACnC,OAAO,CAAC,IAAI,CAAC,CAAC;IAEnB;;;;;;;;;OASG;IACH,MAAM,EAAE,CAAC,OAAO,CAAC,EAAE,aAAa,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAEnD;;;;;;;OAOG;IACH,sBAAsB,EAAE,CAAC,GAAG,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,mBAAmB,GAAG,4BAA4B,CAAC,CAAC;IAEtG;;;;;;;;;;;;OAYG;IACH,YAAY,EAAE,WAAW,CAAC,cAAc,CAAC,CAAC;IAE1C;;;;;;;;;OASG;IACH,YAAY,EAAE,WAAW,CAAC,cAAc,CAAC,CAAC;IAE1C;;;;;OAKG;IACH,iBAAiB,EAAE,WAAW,CAAC,mBAAmB,CAAC,CAAC;IAEpD;;;;;;;OAOG;IACH,aAAa,EAAE,WAAW,CAAC,eAAe,CAAC,CAAC;CAC7C;AASD;;GAEG;AACH,eAAO,MAAM,cAAc;6BAPV,KAAK;0BAAL,KAAK;kCAAL,KAAK;mCAAL,KAAK;4BAAL,KAAK;6BAAL,KAAK;0BAAL,KAAK;sCAAL,KAAK;kBAAL,KAAK;kCAAL,KAAK;wBAAL,KAAK;wBAAL,KAAK;6BAAL,KAAK;yBAAL,KAAK;;;;;CAuBrB,CAAC;AAEF;;GAEG;AACH,QAAA,MAAM,YAAY,sDAAuD,CAAC;AAE1E,eAAe,YAAY,CAAC"}
+79
View File
@@ -0,0 +1,79 @@
import React from 'react';
import { Auth0ClientOptions, User, ConnectAccountRedirectResult, ResponseType } from '@auth0/auth0-spa-js';
import { Auth0ContextInterface } from './auth0-context';
/**
* The account that has been connected during the connect flow.
*/
export type ConnectedAccount = Omit<ConnectAccountRedirectResult, 'appState' | 'response_type'>;
/**
* The state of the application before the user was redirected to the login page
* and any account that the user may have connected to.
*/
export type AppState = {
returnTo?: string;
connectedAccount?: ConnectedAccount;
response_type?: ResponseType;
[key: string]: any;
};
/**
* The main configuration to instantiate the `Auth0Provider`.
*/
export interface Auth0ProviderOptions<TUser extends User = User> extends Auth0ClientOptions {
/**
* The child nodes your Provider has wrapped
*/
children?: React.ReactNode;
/**
* By default this removes the code and state parameters from the url when you are redirected from the authorize page.
* It uses `window.history` but you might want to overwrite this if you are using a custom router, like `react-router-dom`
* See the EXAMPLES.md for more info.
*/
onRedirectCallback?: (appState?: AppState, user?: TUser) => void;
/**
* By default, if the page url has code/state params, the SDK will treat them as Auth0's and attempt to exchange the
* code for a token. In some cases the code might be for something else (another OAuth SDK perhaps). In these
* instances you can instruct the client to ignore them eg
*
* ```jsx
* <Auth0Provider
* clientId={clientId}
* domain={domain}
* skipRedirectCallback={window.location.pathname === '/stripe-oauth-callback'}
* >
* ```
*/
skipRedirectCallback?: boolean;
/**
* Context to be used when creating the Auth0Provider, defaults to the internally created context.
*
* This allows multiple Auth0Providers to be nested within the same application, the context value can then be
* passed to useAuth0, withAuth0, or withAuthenticationRequired to use that specific Auth0Provider to access
* auth state and methods specifically tied to the provider that the context belongs to.
*
* When using multiple Auth0Providers in a single application you should do the following to ensure sessions are not
* overwritten:
*
* * Configure a different redirect_uri for each Auth0Provider, and set skipRedirectCallback for each provider to ignore
* the others redirect_uri
* * If using localstorage for both Auth0Providers, ensure that the audience and scope are different for so that the key
* used to store data is different
*
* For a sample on using multiple Auth0Providers review the [React Account Linking Sample](https://github.com/auth0-samples/auth0-link-accounts-sample/tree/react-variant)
*/
context?: React.Context<Auth0ContextInterface<TUser>>;
}
/**
* ```jsx
* <Auth0Provider
* domain={domain}
* clientId={clientId}
* authorizationParams={{ redirect_uri: window.location.origin }}>
* <MyApp />
* </Auth0Provider>
* ```
*
* Provides the Auth0Context to its child components.
*/
declare const Auth0Provider: <TUser extends User = User>(opts: Auth0ProviderOptions<TUser>) => React.JSX.Element;
export default Auth0Provider;
//# sourceMappingURL=auth0-provider.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"auth0-provider.d.ts","sourceRoot":"","sources":["../src/auth0-provider.tsx"],"names":[],"mappings":"AAAA,OAAO,KAON,MAAM,OAAO,CAAC;AACf,OAAO,EAEL,kBAAkB,EAMlB,IAAI,EAEJ,4BAA4B,EAC5B,YAAY,EACb,MAAM,qBAAqB,CAAC;AAC7B,OAAqB,EACnB,qBAAqB,EAGtB,MAAM,iBAAiB,CAAC;AAUzB;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,IAAI,CAAC,4BAA4B,EAAE,UAAU,GAAG,eAAe,CAAC,CAAC;AAEhG;;;GAGG;AACH,MAAM,MAAM,QAAQ,GAAG;IACrB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;IACpC,aAAa,CAAC,EAAE,YAAY,CAAC;IAC7B,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB,CAAC;AAEF;;GAEG;AACH,MAAM,WAAW,oBAAoB,CAAC,KAAK,SAAS,IAAI,GAAG,IAAI,CAAE,SAAQ,kBAAkB;IACzF;;OAEG;IACH,QAAQ,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC;IAC3B;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,CAAC,QAAQ,CAAC,EAAE,QAAQ,EAAE,IAAI,CAAC,EAAE,KAAK,KAAK,IAAI,CAAC;IACjE;;;;;;;;;;;;OAYG;IACH,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B;;;;;;;;;;;;;;;;OAgBG;IACH,OAAO,CAAC,EAAE,KAAK,CAAC,OAAO,CAAC,qBAAqB,CAAC,KAAK,CAAC,CAAC,CAAC;CACvD;AAoCD;;;;;;;;;;;GAWG;AACH,QAAA,MAAM,aAAa,GAAI,KAAK,SAAS,IAAI,GAAG,IAAI,EAAE,MAAM,oBAAoB,CAAC,KAAK,CAAC,sBA6MlF,CAAC;AAEF,eAAe,aAAa,CAAC"}
+608
View File
@@ -0,0 +1,608 @@
'use strict';
var React = require('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 = React.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 = React.useState(function () { return new Ue(toAuth0ClientOptions(clientOpts)); })[0];
var _c = React.useReducer((reducer), initialAuthState), state = _c[0], dispatch = _c[1];
var didInitialise = React.useRef(false);
var handleError = React.useCallback(function (error) {
dispatch({ type: 'ERROR', error: error });
return error;
}, []);
React.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 === exports.ResponseType.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 = React.useCallback(function (opts) {
deprecateRedirectUri(opts);
return client.loginWithRedirect(opts);
}, [client]);
var loginWithPopup = React.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 = React.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 = React.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 = React.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 = React.useCallback(function (options) {
return client.connectAccountWithRedirect(options);
}, [client]);
var getIdTokenClaims = React.useCallback(function () { return client.getIdTokenClaims(); }, [client]);
var handleRedirectCallback = React.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 = React.useCallback(function (id) { return client.getDpopNonce(id); }, [client]);
var setDpopNonce = React.useCallback(function (nonce, id) { return client.setDpopNonce(nonce, id); }, [client]);
var generateDpopProof = React.useCallback(function (params) { return client.generateDpopProof(params); }, [client]);
var createFetcher = React.useCallback(function (config) { return client.createFetcher(config); }, [client]);
var contextValue = React.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 React.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;
React.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();
};
};
exports.Auth0Context = Auth0Context;
exports.Auth0Provider = Auth0Provider;
exports.AuthenticationError = d;
exports.ConnectError = h;
exports.GenericError = u;
exports.InMemoryCache = oe;
exports.LocalStorageCache = ne;
exports.MfaRequiredError = f;
exports.MissingRefreshTokenError = g;
exports.OAuthError = OAuthError;
exports.PopupCancelledError = m;
exports.PopupTimeoutError = p;
exports.TimeoutError = l;
exports.UseDpopNonceError = w;
exports.User = ye;
exports.initialContext = initialContext;
exports.useAuth0 = useAuth0;
exports.withAuth0 = withAuth0;
exports.withAuthenticationRequired = withAuthenticationRequired;
//# sourceMappingURL=auth0-react.cjs.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"auth0-react.cjs.js","sources":["../node_modules/@auth0/auth0-spa-js/dist/auth0-spa-js.production.esm.js","../src/auth-state.tsx","../src/auth0-context.tsx","../src/errors.tsx","../src/utils.tsx","../src/reducer.tsx","../src/auth0-provider.tsx","../src/use-auth0.tsx","../src/with-auth0.tsx","../src/with-authentication-required.tsx"],"sourcesContent":["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.prototypeLine truncated
+588
View File
@@ -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
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"auth0-react.esm.js","sources":["../node_modules/@auth0/auth0-spa-js/dist/auth0-spa-js.production.esm.js","../src/auth-state.tsx","../src/auth0-context.tsx","../src/errors.tsx","../src/utils.tsx","../src/reducer.tsx","../src/auth0-provider.tsx","../src/use-auth0.tsx","../src/with-auth0.tsx","../src/with-authentication-required.tsx"],"sourcesContent":["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.prototypeLine truncated
+612
View File
@@ -0,0 +1,612 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.reactAuth0 = {}, global.React));
})(this, (function (exports, React) { 'use strict';
/******************************************************************************
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(Line 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 = React.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 = React.useState(function () { return new Ue(toAuth0ClientOptions(clientOpts)); })[0];
var _c = React.useReducer((reducer), initialAuthState), state = _c[0], dispatch = _c[1];
var didInitialise = React.useRef(false);
var handleError = React.useCallback(function (error) {
dispatch({ type: 'ERROR', error: error });
return error;
}, []);
React.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 === exports.ResponseType.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 = React.useCallback(function (opts) {
deprecateRedirectUri(opts);
return client.loginWithRedirect(opts);
}, [client]);
var loginWithPopup = React.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 = React.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 = React.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 = React.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 = React.useCallback(function (options) {
return client.connectAccountWithRedirect(options);
}, [client]);
var getIdTokenClaims = React.useCallback(function () { return client.getIdTokenClaims(); }, [client]);
var handleRedirectCallback = React.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 = React.useCallback(function (id) { return client.getDpopNonce(id); }, [client]);
var setDpopNonce = React.useCallback(function (nonce, id) { return client.setDpopNonce(nonce, id); }, [client]);
var generateDpopProof = React.useCallback(function (params) { return client.generateDpopProof(params); }, [client]);
var createFetcher = React.useCallback(function (config) { return client.createFetcher(config); }, [client]);
var contextValue = React.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 React.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;
React.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();
};
};
exports.Auth0Context = Auth0Context;
exports.Auth0Provider = Auth0Provider;
exports.AuthenticationError = d;
exports.ConnectError = h;
exports.GenericError = u;
exports.InMemoryCache = oe;
exports.LocalStorageCache = ne;
exports.MfaRequiredError = f;
exports.MissingRefreshTokenError = g;
exports.OAuthError = OAuthError;
exports.PopupCancelledError = m;
exports.PopupTimeoutError = p;
exports.TimeoutError = l;
exports.UseDpopNonceError = w;
exports.User = ye;
exports.initialContext = initialContext;
exports.useAuth0 = useAuth0;
exports.withAuth0 = withAuth0;
exports.withAuthenticationRequired = withAuthenticationRequired;
}));
//# sourceMappingURL=auth0-react.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"auth0-react.js","sources":["../node_modules/@auth0/auth0-spa-js/dist/auth0-spa-js.production.esm.js","../src/auth-state.tsx","../src/auth0-context.tsx","../src/errors.tsx","../src/utils.tsx","../src/reducer.tsx","../src/auth0-provider.tsx","../src/use-auth0.tsx","../src/with-auth0.tsx","../src/with-authentication-required.tsx"],"sourcesContent":["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.acqLine truncated
+2
View File
@@ -0,0 +1,2 @@
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).reactAuth0={},e.React)}(this,(function(e,t){"use strict";var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},n(e,t)};var o=function(){return o=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},o.apply(this,arguments)};function i(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 r(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){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((o=o.apply(e,t||[])).next())}))}function s(e,t){var n,o,i,r={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(r=0)),r;)try{if(n=1,o&&(i=2&a[0]?o.return:a[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,a[1])).done)return i;switch(o=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return r.label++,{value:a[1],done:!1};case 5:r.label++,o=a[1],a=[0];continue;case 7:a=r.ops.pop(),r.trys.pop();continue;default:if(!(i=r.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){r=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){r.label=a[1];break}if(6===a[0]&&r.label<i[1]){r.label=i[1],i=a;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(a);break}i[2]&&r.ops.pop(),r.trys.pop();continue}a=t.call(e,r)}catch(e){a=[6,e],o=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}function a(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,"function"==typeof SuppressedError&&SuppressedError;var c="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function u(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function d(e,t){return e(t={exports:{}},t.exports),t.exports}var l=d((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()}}));u(l);var h=u(d((function(e,t){var n=c&&c.__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())}))},o=c&&c.__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=(i=s.trys).leLine truncated
//# sourceMappingURL=auth0-react.min.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"auth0-react.min.js","sources":["../node_modules/@auth0/auth0-spa-js/dist/auth0-spa-js.production.esm.js","../src/auth-state.tsx","../src/auth0-context.tsx","../src/errors.tsx","../src/utils.tsx","../src/reducer.tsx","../src/auth0-provider.tsx","../src/use-auth0.tsx","../src/with-authentication-required.tsx","../src/with-auth0.tsx"],"sourcesContent":["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.prototypeLine truncated
+12
View File
@@ -0,0 +1,12 @@
/**
* 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
*/
export declare class OAuthError extends Error {
error: string;
error_description?: string | undefined;
constructor(error: string, error_description?: string | undefined);
}
//# sourceMappingURL=errors.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.tsx"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,qBAAa,UAAW,SAAQ,KAAK;IAChB,KAAK,EAAE,MAAM;IAAS,iBAAiB,CAAC,EAAE,MAAM;gBAAhD,KAAK,EAAE,MAAM,EAAS,iBAAiB,CAAC,EAAE,MAAM,YAAA;CAMpE"}
+8
View File
@@ -0,0 +1,8 @@
export { default as Auth0Provider, Auth0ProviderOptions, AppState, ConnectedAccount } from './auth0-provider';
export { default as useAuth0 } from './use-auth0';
export { default as withAuth0, WithAuth0Props } from './with-auth0';
export { default as withAuthenticationRequired, WithAuthenticationRequiredOptions, } from './with-authentication-required';
export { default as Auth0Context, Auth0ContextInterface, initialContext, LogoutOptions, RedirectLoginOptions, } from './auth0-context';
export { AuthorizationParams, PopupLoginOptions, PopupConfigOptions, GetTokenWithPopupOptions, LogoutUrlOptions, CacheLocation, GetTokenSilentlyOptions, IdToken, User, ICache, InMemoryCache, LocalStorageCache, Cacheable, TimeoutError, MfaRequiredError, PopupCancelledError, PopupTimeoutError, AuthenticationError, MissingRefreshTokenError, GenericError, UseDpopNonceError, type FetcherConfig, RedirectConnectAccountOptions, ConnectAccountRedirectResult, ResponseType, ConnectError } from '@auth0/auth0-spa-js';
export { OAuthError } from './errors';
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.tsx"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,IAAI,aAAa,EACxB,oBAAoB,EACpB,QAAQ,EACR,gBAAgB,EACjB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,OAAO,IAAI,QAAQ,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,OAAO,IAAI,SAAS,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AACpE,OAAO,EACL,OAAO,IAAI,0BAA0B,EACrC,iCAAiC,GAClC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,OAAO,IAAI,YAAY,EACvB,qBAAqB,EACrB,cAAc,EACd,aAAa,EACb,oBAAoB,GACrB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,kBAAkB,EAClB,wBAAwB,EACxB,gBAAgB,EAChB,aAAa,EACb,uBAAuB,EACvB,OAAO,EACP,IAAI,EACJ,MAAM,EACN,aAAa,EACb,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,gBAAgB,EAChB,mBAAmB,EACnB,iBAAiB,EACjB,mBAAmB,EACnB,wBAAwB,EACxB,YAAY,EACZ,iBAAiB,EACjB,KAAK,aAAa,EAClB,6BAA6B,EAC7B,4BAA4B,EAC5B,YAAY,EACZ,YAAY,EACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC"}
+19
View File
@@ -0,0 +1,19 @@
import { User } from '@auth0/auth0-spa-js';
import { AuthState } from './auth-state';
type Action = {
type: 'LOGIN_POPUP_STARTED';
} | {
type: 'INITIALISED' | 'LOGIN_POPUP_COMPLETE' | 'GET_ACCESS_TOKEN_COMPLETE' | 'HANDLE_REDIRECT_COMPLETE';
user: User | undefined;
} | {
type: 'LOGOUT';
} | {
type: 'ERROR';
error: Error;
};
/**
* Handles how that state changes in the `useAuth0` hook.
*/
export declare const reducer: <TUser extends User = User>(state: AuthState<TUser>, action: Action) => AuthState<TUser>;
export {};
//# sourceMappingURL=reducer.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"reducer.d.ts","sourceRoot":"","sources":["../src/reducer.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,KAAK,MAAM,GACP;IAAE,IAAI,EAAE,qBAAqB,CAAA;CAAE,GAC/B;IACE,IAAI,EACA,aAAa,GACb,sBAAsB,GACtB,2BAA2B,GAC3B,0BAA0B,CAAC;IAC/B,IAAI,EAAE,IAAI,GAAG,SAAS,CAAC;CACxB,GACD;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,GAClB;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,KAAK,CAAA;CAAE,CAAC;AAEpC;;GAEG;AACH,eAAO,MAAM,OAAO,GAAI,KAAK,SAAS,IAAI,GAAG,IAAI,EAAE,OAAO,SAAS,CAAC,KAAK,CAAC,EAAE,QAAQ,MAAM,KAAG,SAAS,CAAC,KAAK,CAuC3G,CAAC"}
+27
View File
@@ -0,0 +1,27 @@
import { User } from '@auth0/auth0-spa-js';
import { Auth0ContextInterface } from './auth0-context';
/**
* ```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.
*/
declare const useAuth0: <TUser extends User = User>(context?: import("react").Context<Auth0ContextInterface<User>>) => Auth0ContextInterface<TUser>;
export default useAuth0;
//# sourceMappingURL=use-auth0.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"use-auth0.d.ts","sourceRoot":"","sources":["../src/use-auth0.tsx"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAC3C,OAAqB,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAEtE;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,QAAA,MAAM,QAAQ,GAAI,KAAK,SAAS,IAAI,GAAG,IAAI,EACzC,8DAAsB,KACrB,qBAAqB,CAAC,KAAK,CACuB,CAAC;AAEtD,eAAe,QAAQ,CAAC"}
+10
View File
@@ -0,0 +1,10 @@
export declare const hasAuthParams: (searchParams?: string) => boolean;
export declare const loginError: (error: unknown) => Error;
export declare const tokenError: (error: unknown) => Error;
/**
* @ignore
* Helper function to map the v1 `redirectUri` option to the v2 `authorizationParams.redirect_uri`
* and log a warning.
*/
export declare const deprecateRedirectUri: (options?: any) => void;
//# sourceMappingURL=utils.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.tsx"],"names":[],"mappings":"AAeA,eAAO,MAAM,aAAa,GAAI,qBAAqC,KAAG,OAEzC,CAAC;AA4B9B,eAAO,MAAM,UAAU,UAxBb,OAAO,KAAG,KAwBsC,CAAC;AAE3D,eAAO,MAAM,UAAU,UA1Bb,OAAO,KAAG,KA0BiD,CAAC;AAEtE;;;;GAIG;AAEH,eAAO,MAAM,oBAAoB,GAAI,UAAU,GAAG,SAkBjD,CAAC"}
+29
View File
@@ -0,0 +1,29 @@
import React, { ComponentType } from 'react';
import { Auth0ContextInterface } from './auth0-context';
/**
* Components wrapped in `withAuth0` will have an additional `auth0` prop
*/
export interface WithAuth0Props {
auth0: Auth0ContextInterface;
}
/**
* ```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.
*/
declare const withAuth0: <P extends WithAuth0Props>(Component: ComponentType<P>, context?: React.Context<Auth0ContextInterface<import("@auth0/auth0-spa-js").User>>) => ComponentType<Omit<P, keyof WithAuth0Props>>;
export default withAuth0;
//# sourceMappingURL=with-auth0.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"with-auth0.d.ts","sourceRoot":"","sources":["../src/with-auth0.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAqB,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAEtE;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,qBAAqB,CAAC;CAC9B;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,QAAA,MAAM,SAAS,GAAI,CAAC,SAAS,cAAc,EACzC,WAAW,aAAa,CAAC,CAAC,CAAC,EAC3B,kFAAsB,KACrB,aAAa,CAAC,IAAI,CAAC,CAAC,EAAE,MAAM,cAAc,CAAC,CAU7C,CAAC;AAEF,eAAe,SAAS,CAAC"}
+77
View File
@@ -0,0 +1,77 @@
import React, { ComponentType, FC } from 'react';
import { Auth0ContextInterface, RedirectLoginOptions } from './auth0-context';
/**
* Options for the withAuthenticationRequired Higher Order Component
*/
export interface WithAuthenticationRequiredOptions {
/**
* ```js
* withAuthenticationRequired(Profile, {
* returnTo: '/profile'
* })
* ```
*
* or
*
* ```js
* withAuthenticationRequired(Profile, {
* returnTo: () => window.location.hash.substr(1)
* })
* ```
*
* Add a path for the `onRedirectCallback` handler to return the user to after login.
*/
returnTo?: string | (() => string);
/**
* ```js
* withAuthenticationRequired(Profile, {
* onRedirecting: () => <div>Redirecting you to the login...</div>
* })
* ```
*
* Render a message to show that the user is being redirected to the login.
*/
onRedirecting?: () => React.JSX.Element;
/**
* ```js
* withAuthenticationRequired(Profile, {
* onBeforeAuthentication: () => { analyticsLibrary.track('login_triggered'); }
* })
* ```
*
* Allows executing logic before the user is redirected to the login page.
*/
onBeforeAuthentication?: () => Promise<void>;
/**
* ```js
* withAuthenticationRequired(Profile, {
* loginOptions: {
* appState: {
* customProp: 'foo'
* }
* }
* })
* ```
*
* Pass additional login options, like extra `appState` to the login page.
* This will be merged with the `returnTo` option used by the `onRedirectCallback` handler.
*/
loginOptions?: RedirectLoginOptions;
/**
* The context to be used when calling useAuth0, this should only be provided if you are using multiple Auth0Providers
* within your application and you wish to tie a specific component to a Auth0Provider other than the Auth0Provider
* associated with the default Auth0Context.
*/
context?: React.Context<Auth0ContextInterface>;
}
/**
* ```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.
*/
declare const withAuthenticationRequired: <P extends object>(Component: ComponentType<P>, options?: WithAuthenticationRequiredOptions) => FC<P>;
export default withAuthenticationRequired;
//# sourceMappingURL=with-authentication-required.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"with-authentication-required.d.ts","sourceRoot":"","sources":["../src/with-authentication-required.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,aAAa,EAAa,EAAE,EAAE,MAAM,OAAO,CAAC;AAE5D,OAAqB,EACnB,qBAAqB,EACrB,oBAAoB,EACrB,MAAM,iBAAiB,CAAC;AAkBzB;;GAEG;AACH,MAAM,WAAW,iCAAiC;IAChD;;;;;;;;;;;;;;;;OAgBG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,CAAC,MAAM,MAAM,CAAC,CAAC;IACnC;;;;;;;;OAQG;IACH,aAAa,CAAC,EAAE,MAAM,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC;IACxC;;;;;;;;OAQG;IACH,sBAAsB,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7C;;;;;;;;;;;;;OAaG;IACH,YAAY,CAAC,EAAE,oBAAoB,CAAC;IACpC;;;;OAIG;IACH,OAAO,CAAC,EAAE,KAAK,CAAC,OAAO,CAAC,qBAAqB,CAAC,CAAC;CAChD;AAED;;;;;;;GAOG;AACH,QAAA,MAAM,0BAA0B,GAAI,CAAC,SAAS,MAAM,EAClD,WAAW,aAAa,CAAC,CAAC,CAAC,EAC3B,UAAS,iCAAsC,KAC9C,EAAE,CAAC,CAAC,CAuCN,CAAC;AAEF,eAAe,0BAA0B,CAAC"}
+100
View File
@@ -0,0 +1,100 @@
{
"author": "Auth0",
"name": "@auth0/auth0-react",
"version": "2.9.0",
"description": "Auth0 SDK for React Single Page Applications (SPA)",
"keywords": [
"auth0",
"login",
"Authorization Code Grant Flow",
"PKCE",
"Single Page Application authentication",
"SPA authentication",
"react"
],
"files": [
"src",
"dist"
],
"main": "dist/auth0-react.cjs.js",
"types": "dist/index.d.ts",
"module": "dist/auth0-react.esm.js",
"scripts": {
"build": "npm run lint && rollup -c --environment NODE_ENV:production",
"lint": "eslint --ext=tsx ./src ./__tests__",
"start": "rollup -cw",
"test": "jest --coverage",
"prepack": "npm run build",
"docs": "typedoc --options typedoc.js src",
"install:examples": "npm i --prefix=examples/cra-react-router --no-package-lock --legacy-peer-deps && npm i --prefix=examples/gatsby-app --no-package-lock --legacy-peer-deps && npm i --prefix=examples/nextjs-app --no-package-lock --legacy-peer-deps && npm ci --prefix=examples/users-api",
"start:cra": "npm start --prefix=examples/cra-react-router",
"start:gatsby": "npm start --prefix=examples/gatsby-app",
"start:nextjs": "npm run dev --prefix=examples/nextjs-app",
"start:api": "npm start --prefix=examples/users-api",
"test:cra": "start-server-and-test start:api 3001 start:cra http-get://127.0.0.1:3000 cypress:run",
"test:cra:watch": "start-server-and-test start:api 3001 start:cra 3000 cypress:open",
"test:gatsby": "start-server-and-test start:api 3001 start:gatsby http-get://localhost:3000 cypress:run",
"test:gatsby:watch": "start-server-and-test start:api 3001 start:gatsby 3000 cypress:open",
"test:nextjs": "start-server-and-test start:api 3001 start:nextjs 3000 cypress:run",
"test:nextjs:watch": "start-server-and-test start:api 3001 start:nextjs 3000 cypress:open",
"test:integration": "npm run test:cra && npm run test:gatsby && npm run test:nextjs",
"cypress:run": "cypress run --spec 'cypress/e2e/smoke.cy.ts'",
"cypress:open": "cypress open"
},
"repository": {
"type": "git",
"url": "git+https://github.com/auth0/auth0-react.git"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/auth0/auth0-react/issues"
},
"homepage": "https://github.com/auth0/auth0-react#readme",
"devDependencies": {
"@rollup/plugin-node-resolve": "^15.0.1",
"@rollup/plugin-replace": "^5.0.1",
"@rollup/plugin-terser": "^0.4.3",
"@testing-library/dom": "^10.4.0",
"@testing-library/jest-dom": "6.8.0",
"@testing-library/react": "16.3.0",
"@types/jest": "^29.5.14",
"@types/react": "19.1.8",
"@types/react-dom": "19.1.6",
"@typescript-eslint/eslint-plugin": "^8.36.0",
"@typescript-eslint/parser": "^8.36.0",
"browserstack-cypress-cli": "^1.19.1",
"cypress": "^13.1.0",
"eslint": "^8.28.0",
"eslint-plugin-react": "^7.31.11",
"eslint-plugin-react-hooks": "^4.6.0",
"husky": "^8.0.3",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.3.1",
"jest-junit": "^15.0.0",
"oidc-provider": "^8.8.1",
"prettier": "^2.8.1",
"pretty-quick": "^3.1.3",
"react": "19.1.0",
"react-dom": "19.1.0",
"rollup": "^3.7.0",
"rollup-plugin-analyzer": "^4.0.0",
"rollup-plugin-delete": "^2.0.0",
"rollup-plugin-dev": "^1.1.3",
"rollup-plugin-livereload": "^2.0.5",
"rollup-plugin-peer-deps-external": "^2.2.4",
"rollup-plugin-serve": "^2.0.2",
"rollup-plugin-typescript2": "^0.36.0",
"start-server-and-test": "^2.0",
"ts-jest": "^29.4.0",
"tslib": "^2.8.1",
"typedoc": "^0.28.7",
"typescript": "^5.8.3"
},
"peerDependencies": {
"react": "^16.11.0 || ^17 || ^18 || ^19",
"react-dom": "^16.11.0 || ^17 || ^18 || ^19"
},
"dependencies": {
"@auth0/auth0-spa-js": "^2.9.0"
}
}
+21
View File
@@ -0,0 +1,21 @@
import { User } from '@auth0/auth0-spa-js';
/**
* The auth state which, when combined with the auth methods, make up the return object of the `useAuth0` hook.
*/
export interface AuthState<TUser extends User = User> {
error: Error | undefined;
isAuthenticated: boolean;
isLoading: boolean;
user: TUser | undefined;
}
/**
* The initial auth state.
*/
export const initialAuthState: AuthState = {
isAuthenticated: false,
isLoading: true,
error: undefined,
user: undefined,
};
+248
View File
@@ -0,0 +1,248 @@
import {
GetTokenSilentlyOptions,
GetTokenWithPopupOptions,
IdToken,
LogoutOptions as SPALogoutOptions,
PopupLoginOptions,
PopupConfigOptions,
RedirectLoginResult,
User,
GetTokenSilentlyVerboseResponse,
RedirectLoginOptions as SPARedirectLoginOptions,
type Auth0Client,
RedirectConnectAccountOptions,
ConnectAccountRedirectResult
} from '@auth0/auth0-spa-js';
import { createContext } from 'react';
import { AuthState, initialAuthState } from './auth-state';
import { AppState } from './auth0-provider';
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
export interface LogoutOptions extends Omit<SPALogoutOptions, 'onRedirect'> {}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
export interface RedirectLoginOptions<TAppState = AppState>
extends Omit<SPARedirectLoginOptions<TAppState>, 'onRedirect'> {}
/**
* Contains the authenticated state and authentication methods provided by the `useAuth0` hook.
*/
export interface Auth0ContextInterface<TUser extends User = User>
extends AuthState<TUser> {
/**
* ```js
* const token = await getAccessTokenSilently(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.
*
* If refresh tokens are used, the token endpoint is called directly with the
* 'refresh_token' grant. If no refresh token is available to make this call,
* the SDK will only fall back to using an iframe to the '/authorize' URL if
* the `useRefreshTokensFallback` setting has been set to `true`. By default this
* setting is `false`.
*
* This method may use a web worker to perform the token call if the in-memory
* cache is used.
*
* If an `audience` value is given to this function, the SDK always falls
* back to using an iframe to make the token exchange.
*
* Note that in all cases, falling back to an iframe requires access to
* the `auth0` cookie.
*/
getAccessTokenSilently: {
(
options: GetTokenSilentlyOptions & { detailedResponse: true }
): Promise<GetTokenSilentlyVerboseResponse>;
(options?: GetTokenSilentlyOptions): Promise<string>;
(options: GetTokenSilentlyOptions): Promise<
GetTokenSilentlyVerboseResponse | string
>;
};
/**
* ```js
* const token = await getTokenWithPopup(options, config);
* ```
*
* Get an access token interactively.
*
* 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.
*/
getAccessTokenWithPopup: (
options?: GetTokenWithPopupOptions,
config?: PopupConfigOptions
) => Promise<string | undefined>;
/**
* ```js
* const claims = await getIdTokenClaims();
* ```
*
* Returns all claims from the id_token if available.
*/
getIdTokenClaims: () => Promise<IdToken | undefined>;
/**
* ```js
* await loginWithRedirect(options);
* ```
*
* Performs a redirect to `/authorize` using the parameters
* provided as arguments. Random and secure `state` and `nonce`
* parameters will be auto-generated.
*/
loginWithRedirect: (
options?: RedirectLoginOptions<AppState>
) => Promise<void>;
/**
* ```js
* await loginWithPopup(options, config);
* ```
*
* 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.
*/
loginWithPopup: (
options?: PopupLoginOptions,
config?: PopupConfigOptions
) => Promise<void>;
/**
* ```js
* await connectAccountWithRedirect({
* connection: 'google-oauth2',
* scopes: ['openid', 'profile', 'email', 'https://www.googleapis.com/auth/drive.readonly'],
* authorization_params: {
* // additional authorization params to forward to the authorization server
* }
* });
* ```
*
* Redirects to the `/connect` URL using the parameters
* provided as arguments. This then redirects to the connection's login page
* where the user can authenticate and authorize the account to be connected.
*
* If connecting the account is successful `onRedirectCallback` will be called
* with the details of the connected account.
*/
connectAccountWithRedirect: (
options: RedirectConnectAccountOptions
) => Promise<void>;
/**
* ```js
* auth0.logout({ logoutParams: { returnTo: window.location.origin } });
* ```
*
* Clears the application session and performs a redirect to `/v2/logout`, using
* the parameters provided as arguments, to clear the Auth0 session.
* If the `logoutParams.federated` option is specified, it also clears the Identity Provider session.
* [Read more about how Logout works at Auth0](https://auth0.com/docs/logout).
*/
logout: (options?: LogoutOptions) => Promise<void>;
/**
* 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.
*
* @param url The URL to that should be used to retrieve the `state` and `code` values. Defaults to `window.location.href` if not given.
*/
handleRedirectCallback: (url?: string) => Promise<RedirectLoginResult | ConnectAccountRedirectResult>;
/**
* Returns the current DPoP nonce used for making requests to Auth0.
*
* It can return `undefined` because when starting fresh it will not
* be populated until after the first response from the server.
*
* It requires enabling the {@link Auth0ClientOptions.useDpop} option.
*
* @param nonce The nonce value.
* @param id The identifier of a nonce: if absent, it will get the nonce
* used for requests to Auth0. Otherwise, it will be used to
* select a specific non-Auth0 nonce.
*/
getDpopNonce: Auth0Client['getDpopNonce'];
/**
* Sets the current DPoP nonce used for making requests to Auth0.
*
* It requires enabling the {@link Auth0ClientOptions.useDpop} option.
*
* @param nonce The nonce value.
* @param id The identifier of a nonce: if absent, it will set the nonce
* used for requests to Auth0. Otherwise, it will be used to
* select a specific non-Auth0 nonce.
*/
setDpopNonce: Auth0Client['setDpopNonce'];
/**
* Returns a string to be used to demonstrate possession of the private
* key used to cryptographically bind access tokens with DPoP.
*
* It requires enabling the {@link Auth0ClientOptions.useDpop} option.
*/
generateDpopProof: Auth0Client['generateDpopProof'];
/**
* Returns a new `Fetcher` class that will contain a `fetchWithAuth()` method.
* This is a drop-in replacement for the Fetch API's `fetch()` method, but will
* handle certain authentication logic for you, like building the proper auth
* headers or managing DPoP nonces and retries automatically.
*
* Check the `EXAMPLES.md` file for a deeper look into this method.
*/
createFetcher: Auth0Client['createFetcher'];
}
/**
* @ignore
*/
const stub = (): never => {
throw new Error('You forgot to wrap your component in <Auth0Provider>.');
};
/**
* @ignore
*/
export const initialContext = {
...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
*/
const Auth0Context = createContext<Auth0ContextInterface>(initialContext);
export default Auth0Context;
+353
View File
@@ -0,0 +1,353 @@
import React, {
useCallback,
useEffect,
useMemo,
useReducer,
useRef,
useState,
} from 'react';
import {
Auth0Client,
Auth0ClientOptions,
PopupLoginOptions,
PopupConfigOptions,
GetTokenWithPopupOptions,
RedirectLoginResult,
GetTokenSilentlyOptions,
User,
RedirectConnectAccountOptions,
ConnectAccountRedirectResult,
ResponseType
} from '@auth0/auth0-spa-js';
import Auth0Context, {
Auth0ContextInterface,
LogoutOptions,
RedirectLoginOptions,
} from './auth0-context';
import {
hasAuthParams,
loginError,
tokenError,
deprecateRedirectUri,
} from './utils';
import { reducer } from './reducer';
import { initialAuthState, type AuthState } from './auth-state';
/**
* The account that has been connected during the connect flow.
*/
export type ConnectedAccount = Omit<ConnectAccountRedirectResult, 'appState' | 'response_type'>;
/**
* The state of the application before the user was redirected to the login page
* and any account that the user may have connected to.
*/
export type AppState = {
returnTo?: string;
connectedAccount?: ConnectedAccount;
response_type?: ResponseType;
[key: string]: any; // eslint-disable-line @typescript-eslint/no-explicit-any
};
/**
* The main configuration to instantiate the `Auth0Provider`.
*/
export interface Auth0ProviderOptions<TUser extends User = User> extends Auth0ClientOptions {
/**
* The child nodes your Provider has wrapped
*/
children?: React.ReactNode;
/**
* By default this removes the code and state parameters from the url when you are redirected from the authorize page.
* It uses `window.history` but you might want to overwrite this if you are using a custom router, like `react-router-dom`
* See the EXAMPLES.md for more info.
*/
onRedirectCallback?: (appState?: AppState, user?: TUser) => void;
/**
* By default, if the page url has code/state params, the SDK will treat them as Auth0's and attempt to exchange the
* code for a token. In some cases the code might be for something else (another OAuth SDK perhaps). In these
* instances you can instruct the client to ignore them eg
*
* ```jsx
* <Auth0Provider
* clientId={clientId}
* domain={domain}
* skipRedirectCallback={window.location.pathname === '/stripe-oauth-callback'}
* >
* ```
*/
skipRedirectCallback?: boolean;
/**
* Context to be used when creating the Auth0Provider, defaults to the internally created context.
*
* This allows multiple Auth0Providers to be nested within the same application, the context value can then be
* passed to useAuth0, withAuth0, or withAuthenticationRequired to use that specific Auth0Provider to access
* auth state and methods specifically tied to the provider that the context belongs to.
*
* When using multiple Auth0Providers in a single application you should do the following to ensure sessions are not
* overwritten:
*
* * Configure a different redirect_uri for each Auth0Provider, and set skipRedirectCallback for each provider to ignore
* the others redirect_uri
* * If using localstorage for both Auth0Providers, ensure that the audience and scope are different for so that the key
* used to store data is different
*
* For a sample on using multiple Auth0Providers review the [React Account Linking Sample](https://github.com/auth0-samples/auth0-link-accounts-sample/tree/react-variant)
*/
context?: React.Context<Auth0ContextInterface<TUser>>;
}
/**
* Replaced by the package version at build time.
* @ignore
*/
declare const __VERSION__: string;
/**
* @ignore
*/
const toAuth0ClientOptions = (
opts: Auth0ProviderOptions
): Auth0ClientOptions => {
deprecateRedirectUri(opts);
return {
...opts,
auth0Client: {
name: 'auth0-react',
version: __VERSION__,
},
};
};
/**
* @ignore
*/
const defaultOnRedirectCallback = (appState?: AppState): void => {
window.history.replaceState(
{},
document.title,
appState!.returnTo ?? window.location.pathname
);
};
/**
* ```jsx
* <Auth0Provider
* domain={domain}
* clientId={clientId}
* authorizationParams={{ redirect_uri: window.location.origin }}>
* <MyApp />
* </Auth0Provider>
* ```
*
* Provides the Auth0Context to its child components.
*/
const Auth0Provider = <TUser extends User = User>(opts: Auth0ProviderOptions<TUser>) => {
const {
children,
skipRedirectCallback,
onRedirectCallback = defaultOnRedirectCallback,
context = Auth0Context,
...clientOpts
} = opts;
const [client] = useState(
() => new Auth0Client(toAuth0ClientOptions(clientOpts))
);
const [state, dispatch] = useReducer(reducer<TUser>, initialAuthState as AuthState<TUser>);
const didInitialise = useRef(false);
const handleError = useCallback((error: Error) => {
dispatch({ type: 'ERROR', error });
return error;
}, []);
useEffect(() => {
if (didInitialise.current) {
return;
}
didInitialise.current = true;
(async (): Promise<void> => {
try {
let user: TUser | undefined;
if (hasAuthParams() && !skipRedirectCallback) {
const { appState = {}, response_type, ...result } = await client.handleRedirectCallback();
user = await client.getUser();
appState.response_type = response_type;
if (response_type === ResponseType.ConnectCode) {
appState.connectedAccount = result as ConnectedAccount;
}
onRedirectCallback(appState, user);
} else {
await client.checkSession();
user = await client.getUser();
}
dispatch({ type: 'INITIALISED', user });
} catch (error) {
handleError(loginError(error));
}
})();
}, [client, onRedirectCallback, skipRedirectCallback, handleError]);
const loginWithRedirect = useCallback(
(opts?: RedirectLoginOptions): Promise<void> => {
deprecateRedirectUri(opts);
return client.loginWithRedirect(opts);
},
[client]
);
const loginWithPopup = useCallback(
async (
options?: PopupLoginOptions,
config?: PopupConfigOptions
): Promise<void> => {
dispatch({ type: 'LOGIN_POPUP_STARTED' });
try {
await client.loginWithPopup(options, config);
} catch (error) {
handleError(loginError(error));
return;
}
const user = await client.getUser();
dispatch({ type: 'LOGIN_POPUP_COMPLETE', user });
},
[client, handleError]
);
const logout = useCallback(
async (opts: LogoutOptions = {}): Promise<void> => {
await client.logout(opts);
if (opts.openUrl || opts.openUrl === false) {
dispatch({ type: 'LOGOUT' });
}
},
[client]
);
const getAccessTokenSilently = useCallback(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async (opts?: GetTokenSilentlyOptions): Promise<any> => {
let token;
try {
token = await client.getTokenSilently(opts);
} catch (error) {
throw tokenError(error);
} finally {
dispatch({
type: 'GET_ACCESS_TOKEN_COMPLETE',
user: await client.getUser(),
});
}
return token;
},
[client]
);
const getAccessTokenWithPopup = useCallback(
async (
opts?: GetTokenWithPopupOptions,
config?: PopupConfigOptions
): Promise<string | undefined> => {
let token;
try {
token = await client.getTokenWithPopup(opts, config);
} catch (error) {
throw tokenError(error);
} finally {
dispatch({
type: 'GET_ACCESS_TOKEN_COMPLETE',
user: await client.getUser(),
});
}
return token;
},
[client]
);
const connectAccountWithRedirect = useCallback(
(options: RedirectConnectAccountOptions) =>
client.connectAccountWithRedirect(options),
[client]
);
const getIdTokenClaims = useCallback(
() => client.getIdTokenClaims(),
[client]
);
const handleRedirectCallback = useCallback(
async (
url?: string
): Promise<RedirectLoginResult | ConnectAccountRedirectResult> => {
try {
return await client.handleRedirectCallback(url);
} catch (error) {
throw tokenError(error);
} finally {
dispatch({
type: 'HANDLE_REDIRECT_COMPLETE',
user: await client.getUser(),
});
}
},
[client]
);
const getDpopNonce = useCallback<Auth0Client['getDpopNonce']>(
(id) => client.getDpopNonce(id),
[client]
);
const setDpopNonce = useCallback<Auth0Client['setDpopNonce']>(
(nonce, id) => client.setDpopNonce(nonce, id),
[client]
);
const generateDpopProof = useCallback<Auth0Client['generateDpopProof']>(
(params) => client.generateDpopProof(params),
[client]
);
const createFetcher = useCallback<Auth0Client['createFetcher']>(
(config) => client.createFetcher(config),
[client]
);
const contextValue = useMemo<Auth0ContextInterface<TUser>>(() => {
return {
...state,
getAccessTokenSilently,
getAccessTokenWithPopup,
getIdTokenClaims,
loginWithRedirect,
loginWithPopup,
connectAccountWithRedirect,
logout,
handleRedirectCallback,
getDpopNonce,
setDpopNonce,
generateDpopProof,
createFetcher,
};
}, [
state,
getAccessTokenSilently,
getAccessTokenWithPopup,
getIdTokenClaims,
loginWithRedirect,
loginWithPopup,
connectAccountWithRedirect,
logout,
handleRedirectCallback,
getDpopNonce,
setDpopNonce,
generateDpopProof,
createFetcher,
]);
return <context.Provider value={contextValue}>{children}</context.Provider>;
};
export default Auth0Provider;
+14
View File
@@ -0,0 +1,14 @@
/**
* 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
*/
export class OAuthError extends Error {
constructor(public error: string, public error_description?: string) {
super(error_description ?? error);
// 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);
}
}
+48
View File
@@ -0,0 +1,48 @@
export {
default as Auth0Provider,
Auth0ProviderOptions,
AppState,
ConnectedAccount
} from './auth0-provider';
export { default as useAuth0 } from './use-auth0';
export { default as withAuth0, WithAuth0Props } from './with-auth0';
export {
default as withAuthenticationRequired,
WithAuthenticationRequiredOptions,
} from './with-authentication-required';
export {
default as Auth0Context,
Auth0ContextInterface,
initialContext,
LogoutOptions,
RedirectLoginOptions,
} from './auth0-context';
export {
AuthorizationParams,
PopupLoginOptions,
PopupConfigOptions,
GetTokenWithPopupOptions,
LogoutUrlOptions,
CacheLocation,
GetTokenSilentlyOptions,
IdToken,
User,
ICache,
InMemoryCache,
LocalStorageCache,
Cacheable,
TimeoutError,
MfaRequiredError,
PopupCancelledError,
PopupTimeoutError,
AuthenticationError,
MissingRefreshTokenError,
GenericError,
UseDpopNonceError,
type FetcherConfig,
RedirectConnectAccountOptions,
ConnectAccountRedirectResult,
ResponseType,
ConnectError
} from '@auth0/auth0-spa-js';
export { OAuthError } from './errors';
+59
View File
@@ -0,0 +1,59 @@
import { User } from '@auth0/auth0-spa-js';
import { AuthState } from './auth-state';
type Action =
| { type: 'LOGIN_POPUP_STARTED' }
| {
type:
| 'INITIALISED'
| 'LOGIN_POPUP_COMPLETE'
| 'GET_ACCESS_TOKEN_COMPLETE'
| 'HANDLE_REDIRECT_COMPLETE';
user: User | undefined;
}
| { type: 'LOGOUT' }
| { type: 'ERROR'; error: Error };
/**
* Handles how that state changes in the `useAuth0` hook.
*/
export const reducer = <TUser extends User = User>(state: AuthState<TUser>, action: Action): AuthState<TUser> => {
switch (action.type) {
case 'LOGIN_POPUP_STARTED':
return {
...state,
isLoading: true,
};
case 'LOGIN_POPUP_COMPLETE':
case 'INITIALISED':
return {
...state,
isAuthenticated: !!action.user,
user: action.user as TUser | undefined,
isLoading: false,
error: undefined,
};
case 'HANDLE_REDIRECT_COMPLETE':
case 'GET_ACCESS_TOKEN_COMPLETE':
if (state.user === action.user) {
return state;
}
return {
...state,
isAuthenticated: !!action.user,
user: action.user as TUser | undefined,
};
case 'LOGOUT':
return {
...state,
isAuthenticated: false,
user: undefined,
};
case 'ERROR':
return {
...state,
isLoading: false,
error: action.error,
};
}
};
+32
View File
@@ -0,0 +1,32 @@
import { useContext } from 'react';
import { User } from '@auth0/auth0-spa-js';
import Auth0Context, { Auth0ContextInterface } from './auth0-context';
/**
* ```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.
*/
const useAuth0 = <TUser extends User = User>(
context = Auth0Context
): Auth0ContextInterface<TUser> =>
useContext(context) as Auth0ContextInterface<TUser>;
export default useAuth0;
+74
View File
@@ -0,0 +1,74 @@
import { OAuthError } from './errors';
const CODE_RE = /[?&](?:connect_)?code=[^&]+/;
const STATE_RE = /[?&]state=[^&]+/;
const ERROR_RE = /[?&]error=[^&]+/;
interface WithError {
error: string;
}
interface WithErrorAndDescription {
error: string;
error_description: string;
}
export const hasAuthParams = (searchParams = window.location.search): boolean =>
(CODE_RE.test(searchParams) || ERROR_RE.test(searchParams)) &&
STATE_RE.test(searchParams);
const normalizeErrorFn =
(fallbackMessage: string) =>
(error: unknown): 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 as WithError).error === 'string'
) {
if (
'error_description' in error &&
typeof (error as WithErrorAndDescription).error_description === 'string'
) {
const e = error as WithErrorAndDescription;
return new OAuthError(e.error, e.error_description);
}
const e = error as WithError;
return new OAuthError(e.error);
}
return new Error(fallbackMessage);
};
export const loginError = normalizeErrorFn('Login failed');
export const 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
export const deprecateRedirectUri = (options?: any) => {
if (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 = options.authorizationParams ?? {};
options.authorizationParams.redirect_uri = options.redirectUri;
delete options.redirectUri;
}
if (options?.authorizationParams?.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;
}
};
+44
View File
@@ -0,0 +1,44 @@
import React, { ComponentType } from 'react';
import Auth0Context, { Auth0ContextInterface } from './auth0-context';
/**
* Components wrapped in `withAuth0` will have an additional `auth0` prop
*/
export interface WithAuth0Props {
auth0: Auth0ContextInterface;
}
/**
* ```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.
*/
const withAuth0 = <P extends WithAuth0Props>(
Component: ComponentType<P>,
context = Auth0Context
): ComponentType<Omit<P, keyof WithAuth0Props>> => {
return function WithAuth(props): React.JSX.Element {
return (
<context.Consumer>
{(auth: Auth0ContextInterface): React.JSX.Element => (
<Component {...(props as P)} auth0={auth} />
)}
</context.Consumer>
);
};
};
export default withAuth0;
+141
View File
@@ -0,0 +1,141 @@
import React, { ComponentType, useEffect, FC } from 'react';
import useAuth0 from './use-auth0';
import Auth0Context, {
Auth0ContextInterface,
RedirectLoginOptions,
} from './auth0-context';
/**
* @ignore
*/
const defaultOnRedirecting = (): React.JSX.Element => <></>;
/**
* @ignore
*/
const defaultOnBeforeAuthentication = async (): Promise<void> => {/* noop */ };
/**
* @ignore
*/
const defaultReturnTo = (): string =>
`${window.location.pathname}${window.location.search}`;
/**
* Options for the withAuthenticationRequired Higher Order Component
*/
export interface WithAuthenticationRequiredOptions {
/**
* ```js
* withAuthenticationRequired(Profile, {
* returnTo: '/profile'
* })
* ```
*
* or
*
* ```js
* withAuthenticationRequired(Profile, {
* returnTo: () => window.location.hash.substr(1)
* })
* ```
*
* Add a path for the `onRedirectCallback` handler to return the user to after login.
*/
returnTo?: string | (() => string);
/**
* ```js
* withAuthenticationRequired(Profile, {
* onRedirecting: () => <div>Redirecting you to the login...</div>
* })
* ```
*
* Render a message to show that the user is being redirected to the login.
*/
onRedirecting?: () => React.JSX.Element;
/**
* ```js
* withAuthenticationRequired(Profile, {
* onBeforeAuthentication: () => { analyticsLibrary.track('login_triggered'); }
* })
* ```
*
* Allows executing logic before the user is redirected to the login page.
*/
onBeforeAuthentication?: () => Promise<void>;
/**
* ```js
* withAuthenticationRequired(Profile, {
* loginOptions: {
* appState: {
* customProp: 'foo'
* }
* }
* })
* ```
*
* Pass additional login options, like extra `appState` to the login page.
* This will be merged with the `returnTo` option used by the `onRedirectCallback` handler.
*/
loginOptions?: RedirectLoginOptions;
/**
* The context to be used when calling useAuth0, this should only be provided if you are using multiple Auth0Providers
* within your application and you wish to tie a specific component to a Auth0Provider other than the Auth0Provider
* associated with the default Auth0Context.
*/
context?: React.Context<Auth0ContextInterface>;
}
/**
* ```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.
*/
const withAuthenticationRequired = <P extends object>(
Component: ComponentType<P>,
options: WithAuthenticationRequiredOptions = {}
): FC<P> => {
return function WithAuthenticationRequired(props: P): React.JSX.Element {
const {
returnTo = defaultReturnTo,
onRedirecting = defaultOnRedirecting,
onBeforeAuthentication = defaultOnBeforeAuthentication,
loginOptions,
context = Auth0Context,
} = options;
const { isAuthenticated, isLoading, loginWithRedirect } =
useAuth0(context);
useEffect(() => {
if (isLoading || isAuthenticated) {
return;
}
const opts = {
...loginOptions,
appState: {
...loginOptions?.appState,
returnTo: typeof returnTo === 'function' ? returnTo() : returnTo,
},
};
void (async (): Promise<void> => {
await onBeforeAuthentication();
await loginWithRedirect(opts);
})();
}, [
isLoading,
isAuthenticated,
loginWithRedirect,
onBeforeAuthentication,
loginOptions,
returnTo,
]);
return isAuthenticated ? <Component {...props} /> : onRedirecting();
};
};
export default withAuthenticationRequired;