0.0.3 • Published 9 months ago

@saascannon/spa-react v0.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

@saascannon/spa-react

React Wrapper for the @saascannon/spa package. It provides a context-based solution to integrate authentication and authorization functionalities provided by Saascannon into your React application. By using the SaascannonProvider component, you can manage authentication flows and access Saascannon's APIs through React hooks.

Installation

Install the package via npm:

npm i @saascannon/spa-react

Usage

  1. Wrap your Application with SaascannonProvider

    First, wrap your application with SaascannonProvider. This component initializes the Saascannon client, manages loading states, and passes the client methods to the context for consumption within your React components.

    import React from "react";
    import ReactDOM from "react-dom";
    import { SaascannonProvider } from "@saascannon/spa-react";
    import App from "./App";
    import { apiClient } from "./utils/api"
    
    const saascannonConfig = {
        domain: "your-tenant.region.saascannon.app",
        clientId: "your-client-id",
        redirectUri: "http://localhost:3000/callback",
    };
    
    ReactDOM.render(
        <SaascannonProvider 
            config={saascannonConfig} 
            loading={<div>Loading...</div>}
            clientInitialised={(client) => {
                try {
                    apiClient.config.TOKEN = async () => {
                    const accessToken = await client.getAccessToken();
    
                    if (accessToken === null) {
                        throw "Invalid access token";
                    }
    
                    return accessToken;
                    };
                } finally {
                    setLoadingAuthState(false);
                }
            }}
        >
            <App />
        </SaascannonProvider>,
        document.getElementById("root"),
    );

    The SaascannonProvider component takes the following props:

    • config (required): An object containing configuration options (see type Options for details).
    • loading (optional): A React node that will be displayed while the Saascannon client is loading.
    • clientInitialised (optional): A callback function that will be invoked once the client is initialized. This is useful for setting up any global usage of the saascannon methods (like shown in the example for setting up access token middleware) as you have direct access to the underlying client during this function call.
  1. Access Saascannon Client Methods via useSaascannon Hook

    Inside any child component, you can access the Saascannon client and call its methods by using the useSaascannon hook.

    import React, { useEffect } from "react";
    import { useSaascannon } from "@saascannon/spa-react";
    
    const MyComponent = () => {
        const {
            user,
            loginViaRedirect,
            signupViaRedirect,
            logoutViaRedirect,
            getAccessToken,
            hasPermissions,
            accountManagement,
            shopManagement,
        } = useSaascannon();
    
        return (
            <div>
                {user ? (
                    <>
                        <h2>Welcome, {user.name}!</h2>
                        <button onClick={() => logoutViaRedirect()}>Logout</button>
                    </>
                ) : (
                    <>
                        <button onClick={() => loginViaRedirect()}>Login</button>
                        <button onClick={() => signupViaRedirect()}>Sign Up</button>
                    </>
                )}
                <div>
                    {hasPermissions("admin") ? (
                        <p>You have admin access</p>
                    ) : (
                        <p>You do not have admin access</p>
                    )}
                </div>
            </div>
        );
    };
    
    export default MyComponent;

Saascannon Methods Available through useSaascannon

The following methods are available from the useSaascannon hook:

MethodDescription
userCurrent authenticated user object, or null if not authenticated.
loginViaRedirectInitiates a login flow redirect.
signupViaRedirectInitiates a signup flow redirect.
logoutViaRedirectLogs out the user and redirects them as configured.
getAccessTokenReturns an access token if the user is authenticated.
hasPermissionsChecks if the user has specific permissions.
accountManagementProvides access to account management functions.
shopManagementProvides access to shop management functions.

Configuration Options

The config object passed to SaascannonProvider includes:

OptionTypeRequiredDescription
domainstringYesYour Saascannon domain.
clientIdstringYesThe Client ID associated with your application.
redirectUristringYesThe URI Saascannon redirects to after authentication.
afterCallbackfunctionNoA callback that runs after authentication callback handling.
oAuthErrorHandlerfunctionNoA handler function for OAuth errors.
uiBaseUrlstringNoBase URL for your Saascannon UI, if different from the domain.

Example

Here’s how you could use the SaascannonProvider and useSaascannon in a simple app:

import React from "react";
import { SaascannonProvider, useSaascannon } from "@saascannon/spa-react";

const saascannonConfig = {
  domain: "your-tenant.region.saascannon.app",
  clientId: "your-client-id",
  redirectUri: "http://localhost:3000/callback",
};

const Profile = () => {
  const { user, logoutViaRedirect, loginViaRedirect, shopManagement } = useSaascannon();

  return (
    <div>
      <h1>Welcome {user?.name || "Guest"}</h1>
      {user 
        ? <>
            <button onClick={() => logoutViaRedirect()}>Logout</button>
            <button onClick={() => shopManagement.open()}>Manage My Subscriptions</button>
          <>
        : <button onClick={() => loginViaRedirect()}>Login</button>
      }
    </div>
  );
};

const App = () => (
  <SaascannonProvider config={saascannonConfig} loading={<div>Loading...</div>}>
    <Profile />
  </SaascannonProvider>
);

export default App;
0.0.3

9 months ago

0.0.2

9 months ago

0.0.1

2 years ago