2.0.19 • Published 6 months ago

diditsdktest v2.0.19

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

Didit-SDK

The easiest way to connect to Didit protocol(https://docs.didit.me/)

Didit-SDK is a React library that makes it easy to add wallet connection to your dapp.

  • Didit User Authentication flow
  • 🔥 Out-of-the-box wallet management
  • ✅ Easily customizable
  • 🦄 Built on top of rainbowkit, wagmi and viem

Try it out

You can use the CodeSandbox links below try out Didit Sdk:

Examples

The following examples are provided in the examples folder of this repo.

  • with-vite-react The example contains a first view 'localhost:3000' where you can test the ConnetButton and a second view 'localhost:3000/status' where you can login, logout and check the auth status from with you own buttons and hooks!

  • with-create-react-app this one contains only connection button on home page

Running examples

To run an example locally, install dependencies.

pnpm install

Then go into an example directory, eg: with-vite-react.

cd examples/with-vite-react

Then run the dev script.

pnpm run dev

Installation

Integrate didit-sdk into your project

install didit-sdk and its peer dependencies, wagmi and viem.

npm install didit-sdk wagmi viem

Note: RainbowKit is a React library.

Import

Import didit-sdk and `wagmi.

All the components, providers, hooks and utils are exported from the main didit-sdk package.

import 'didit-sdk/styles.css';

import { DiditAuthProvider, DiditLoginButton, DiditAuthMethod, ... } from 'didit-sdk';

Configure

Configure Didit provider
  1. Set up the DiditAuthProvider with minimum configurable props:
  • clientId: Your Didit client id
  • redirectUri: The redirect URI of your app. This is where the user will be redirected after authentication. It must be registered in your Didit client configuration and should be a valid page in your app.
import { DiditAuthProvider} from 'didit-sdk';

...

      <DiditAuthProvider
        clientId="676573"
        redirectUri="http://your-app.com/login/callback"
      >
        {children}
      </DiditAuthProvider>
  1. Didit supports multiple authentication methods. You can configure the DiditAuthProvider with the authentication methods you want to enable for your users. There are email base methods and wallet method, which can be configured with the following props:

Additionally you can configure your Didit connection with more custom props:

  • authMethods: The authentication methods you want to enable for your users (Default: ['google', 'apple', 'wallet'])
  • authBaseUrl: The base URL of a custom backend with Didit auth for email based authentication methods and token revalidation (Default: https://apx.didit.me/auth)
  • walletAuthBaseUrl: The base URL of your custom backend with Didit auth for wallet auth method (Default: https://apx.didit.me/auth)
  • emailAuthMode: The mode of the email based authentication methods. It can be either popup or redirect (Default: popup)
  • walletAuthorizationPath: Custom path for wallet authorization endpoint (Default: /v2/wallet-authorization/)
  • tokenAuthorizationPath: Custom path for token endpoint (Default: /v2/token/)
  • claims: The claims you want to request from your users (Default: "read:email")
  • scope: The scopes you want to request from your users (Default: "openid")
  1. Additionally you can configure the DiditAuthProvider with the some callbacks to customize your authentication flow:
  • onError: A callback function that will be called when an error occurs during the authentication process
  • onLogin: A callback function that will be called when the user successfully logs in
  • onLogout: A callback function that will be called when the user successfully logs out
import { DiditAuthProvider, DiditAuthMethod,  } from 'didit-sdk';

...
      <DiditAuthProvider
        authMethods={[DiditAuthMethod.APPLE, DiditAuthMethod.GOOGLE]}
        authBaseUrl="https://apx.staging.didit.me/auth"
        walletAuthBaseUrl="https://my.didit.app/auth/wallet"
        clientId="676573"
        claims="read:email read:blockchain"
        scope="openid"
        emailAuthMode={DiditEmailAuthMode.REDIRECT}
        walletAuthorizationPath="/wallet-authorization/"
        tokenAuthorizationPath="/token/"
        onLogin={(_authMethod?: DiditAuthMethod) =>
          console.log('Logged in Didit with', _authMethod)
        }
        onLogout={() => console.log('Logged out Didit')}
        onError={(_error: string) => console.error('Didit error: ', _error)}
      >
Configure Wagmi

In case you want to use the wallet authentication method, You will also need to configure your desired chains, generate the required connectors and setup a wagmi config

Note: Every dApp that relies on WalletConnect now needs to obtain a projectId from WalletConnect Cloud. This is absolutely free and only takes a few minutes.

...
import { getDefaultWallets } from 'didit-sdk';
import { configureChains, createConfig, WagmiConfig } from 'wagmi';
import { mainnet, polygon, optimism, arbitrum, base, zora } from 'wagmi/chains';
import { alchemyProvider } from 'wagmi/providers/alchemy';
import { publicProvider } from 'wagmi/providers/public';

const { chains, publicClient } = configureChains(
  [mainnet, polygon, optimism, arbitrum, base, zora],
  [
    alchemyProvider({ apiKey: process.env.ALCHEMY_ID }),
    publicProvider()
  ]
);

const { connectors } = getDefaultWallets({
  appName: 'App with Didit',
  projectId: 'YOUR_WALLET_CONNECT_PROJECT_ID',
  chains
});

const wagmiConfig = createConfig({
  autoConnect: true,
  connectors,
  publicClient
})

Read more about configuring chains & providers with wagmi.

  1. Set up WagmiConfig:

Pass the next parameters to the DiditAuthProvider provider:

  • chains: Wagmi config of the requested chain i.e: wagmiConfig.chains
  • theme: theme function to customize RainbowKit UI to match your branding. there are 3 built-in theme functions:
<WagmiConfig
  config={wagmiConfig} // The one that was configured before for Wagmi
>
  <DiditAuthProvider clientId="676573" chains={chains} theme={lightTheme()}>
    {children}
  </DiditAuthProvider>
</WagmiConfig>
Wrap all providers

Wrap your application with WagmiConfig and DiditAuthProvider providers in the following order and way:

const App = () => {
  return (
    <WagmiConfig
      config={wagmiConfig} // The one that was configured before for Wagmi
    >
      <DiditAuthProvider clientId="676573" chains={chains} theme={lightTheme()}>
        {children}
      </DiditAuthProvider>
    </WagmiConfig>
  );
};

Manage authentication

Add default Didit login and logout components
  1. Add the DiditLoginButton component to your app using a authentication method:
import { DiditLoginButton, DiditAuthMethod } from 'didit-sdk';

...

  <DiditLoginButton
    label="Connect with Didit"
    authMethod={DiditAuthMethod.GOOGLE}
  />
  1. Add the DiditLogoutButton component to your app:
import { DiditLogoutButton } from 'didit-sdk';

...

  <DiditLogoutButton
    label="Logout from Didit"
  />
  1. Additionally you can use the DiditLogin component to provide multiple authentication methods. You can also configure it with:
  • mode: The mode of the login component (modal or embedded) (default: modal)
  • title: the title of the login dialog (string) (default: Sign in with Didit)
  • description: the description of the login dialog (string) (default: <empty string>)
import { DiditLogin, DiditLoginMode } from 'didit-sdk';

...

  <DiditLogin
    mode={ DiditLoginMode.MODAL }
    isModalOpen={isLoginModalOpen}
    onModalClose={() => setIsLoginModalOpen(false)}
  />
import { DiditLogin } from 'didit-sdk';

...

  <DiditLogin mode={ DiditLoginMode.EMBEDDED } />

The DiditLogin is automatically configured with the authentication methods you provided to the DiditAuthProvider provider.

Retrieve the authentication status

You can use the useDiditAuth hook to retrieve the authentication status and current connection;

  • authMethod: The current authentication method being used

    import { DiditAuthMethod } from 'didit-sdk';
  • status: The current authentication status ('loading', 'authenticated', 'unauthenticated')

    import { DiditAuthStatus } from 'didit-sdk';
  • accessToken: The current Didit access token

  • refreshToken: The current Didit refresh token
  • isAuthenticated: Whether the user is authenticated or not
  • walletAddress: The current user's wallet address if connected by the wallet auth method
  • error: The current error in authentication process if any
  • user : { identifier: <email | walletAddress>, identifierType: <"email" | "wallet" }: the user identifier based on the user login method
import { useDiditAuth } from 'didit-sdk';

...
  const { authMethod, status, accessToken, isAuthenticated, walletAddress, error } = useDiditAuth();

  return (
    <div>
      <p>Auth method: {authMethod}</p>
      <p>Status: {status}</p>
      <p>Token: {accessToken}</p>
      <p>Is authenticated: {isAuthenticated}</p>
      <p>Address: {walletAddress}</p>
      <p>Error: {error}</p>
    </div>
  );
Customize the authentication flow

Additonally you can customize the Didit authentication flow by also using rest of the values returned by the useDiditAuth hook:

import { useDiditAuth } from 'didit-sdk';

...

const {
    authMethod,
    availableAuthMethods,
    error,
    hasError,
    isAuthenticated,
    isLoading,
    login,
    loginWithApple,
    loginWithEmail,
    loginWithGoogle,
    loginWithSocial,
    loginWithWallet,
    logout,
    status,
    token,
    tokenData,
    user,
    walletAddress, // if the user is connected with wallet method
} = useDiditAuth({
  onError: (error: string) => console.error('Didit error: ', error),
  onLogin: (authMethod?: string) => console.log('Logged in Didit with', authMethod),
  onLogout: () => console.log('Logged out Didit')
});

return (
  <button
    id="custom-Didit-login-button"
    onClick={() => {
      if (isAuthenticated) {
        logout();
      } else {
        loginWithWallet();
      }
    }}
    disabled={ isAuthenticating === undefined }
  >
    {isAuthenticated ? 'Logout' : 'Login'}
  </button>
  <div>
    <p>Auth method: {authMethod}</p>
    <p>Status: {status}</p>
    <p>Token: {token}</p>
    <p>Is authenticated: {isAuthenticated}</p>
    <p>User identifier: {user?.identifier}</p>
    <p>Identifier type: {user?.identifierType}</p>
  </div>
)
Special cases
App with localized routing

In case you have localized routing in your app there are two possible ways to configure the redirectUri prop in the DiditAuthProvider:

  1. You create a single page and route withouth localization and use the redirectUri prop as usual:
import { DiditAuthProvider } from 'didit-sdk';

...

  <DiditAuthProvider
    clientId="676573"
    redirectUri="http://your-app.com/no-locale-login/callback"
  >
    {children}
  </DiditAuthProvider>
  1. You can use a dynamic redirectUri prop based on the current language or locale:
import { DiditAuthProvider } from 'didit-sdk';

...

  <DiditAuthProvider
    clientId="676573"
    redirectUri={`http://your-app.com/${locale}/login/callback`}
  >
    {children}
  </DiditAuthProvider>

Note: In case you use the second option, you will need to add each of the redirectUri to your Didit client configuration for each language or locale to support all the possible routes.

2.0.3

7 months ago

2.0.2

7 months ago

2.0.5

7 months ago

2.0.4

7 months ago

2.0.7

6 months ago

2.0.6

7 months ago

2.0.9

6 months ago

2.0.8

6 months ago

2.0.1

7 months ago

2.0.0

7 months ago

0.0.30

7 months ago

0.0.31

7 months ago

0.0.32

7 months ago

0.0.26

10 months ago

0.0.27

10 months ago

0.0.28

10 months ago

0.0.29

10 months ago

2.0.15

6 months ago

2.0.16

6 months ago

2.0.13

6 months ago

2.0.14

6 months ago

2.0.11

6 months ago

2.0.10

6 months ago

2.0.19

6 months ago

2.0.17

6 months ago

2.0.18

6 months ago

0.0.24

11 months ago

0.0.25

11 months ago

0.0.20

11 months ago

0.0.22

11 months ago

0.0.23

11 months ago

0.0.16

12 months ago

0.0.17

12 months ago

0.0.18

12 months ago

0.0.19

12 months ago

0.0.10

1 year ago

0.0.11

1 year ago

0.0.12

1 year ago

0.0.13

1 year ago

0.0.14

1 year ago

0.0.15

1 year ago

0.0.9

1 year ago

0.0.8

1 year ago

0.0.7

1 year ago

0.0.6

1 year ago

0.0.5

1 year ago

0.0.4

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago