Skip to main content

Types

AuthInfo

The authentication information of a user.

Properties

NameTypeDescription
tokenstringThe User Info Token.
orgIDstringThe user’s organization ID.
userIDstringThe user ID.
(Optional) actionstringThe current operation type. You can ignore this parameter.

MfaListItem

The information about a multi-factor authentication (MFA) method that will be displayed in the UI.

Properties

NameTypeDescription
mfaMethodstringThe MFA method type. The possible values are as follows:
  • google_auth: Google Authenticator.
  • cobo_guard: Cobo Guard.
  • security_key: Security keys.
For more details, refer to Set up multi-factor authentication (MFA) methods.
mfaStatusstringThe active status of the MFA method. The possible values are as follows:
  • Active: The MFA method will be displayed as enabled in the UI.
  • Inactive(default): The MFA method will be displayed as disabled in the UI.
Any other values will be treated as Inactive.

Enums

locale

The language setting.
  • en-US: English.
  • zh-CN: Chinese.

Hooks

useMFA

const useMFA: () => (mfaMethods: MfaListItem[]) => Promise<string>;
This hook manages multi-factor authentication (MFA) methods within your application. It provides a function to send MFA method data to Cobo for processing.

Returns

This hook returns a function sendMfaMethods that sends an array of MFA methods to Cobo’s backend. The sendMfaMethodsfunction has the following parameter:
NameTypeDescription
mfaMethodsMfaListItem []An array of MfaListItem objects. Each object represents an MFA method that will be displayed in the UI.
The sendMfaMethods function returns a Promise that resolves to a request ID of string type, which should be sent to Cobo Portal for processing.

Sample code

The following example defines an array of MFA methods, sends them using sendMfaMethods, and handles the response or any errors.
import React, { useEffect } from 'react';
import { useMFA } from '@cobo/cobo-ui-toolkit';

const MyComponent = () => {
 const { sendMfaMethods } = useMFA();
 const testMFA = async () => {
  const mfaMethods = [
   { mfaMethod: "google_auth", mfaStatus: "Active" },
   { mfaMethod: "cobo_guard", mfaStatus: "Active" },
   { mfaMethod: "security_key", mfaStatus: "Active" },
  ];
  try {
   const requestId = await sendMfaMethods(mfaMethods);
   console.log('Request ID:', requestId);
  } catch (error) {
   console.error('Error sending MFA methods:', error);
  }
 };

 useEffect(() => {
  testMFA();
 }, []);
 return <div>Check console for request ID.</div>;
};

export default MyComponent;

useTrackingScript

const useTrackingScript: (env: "production") => void;
This hook injects a tracking script into the DOM, which collects data for app analytics, and ensures proper cleanup when the component unmounts. This data will be accessible on Developer Console in the future.

Parameters

NameTypeDescription
envstringThe type of environment in which your app runs. For more details, refer to environments.
Currently, this parameter value must be production, regardless of whether your app runs in the production environment or development environment.

Sample code

The following example loads a tracking script in both the production and development environments.
import React from 'react';
import { useTrackingScript } from '@cobo/cobo-ui-toolkit';

const MyApp = () => {
  useTrackingScript('production');
  return <h1>Hello world</h1>;
};

export default MyApp;

Notes

To enable effective tracking, each clickable element in your app needs a unique tracking attribute named data-track-id or dtid. This attribute serves as the primary identifier for tracking interactions on specific buttons or elements, enabling consistent and accurate analytics collection. Each data-track-id or dtid attribute value must be lowercase words separated by underscores in the format {PAGE_IDENTIFIER}_{COMPONENT_IDENTIFIER}_{ELEMENT_IDENTIFIER} that follow the following rules:
  • Page identifier: Identifying the page or module’s feature, including home, login, and profile.
  • Component identifier: Identifies the specific UI component within the page, including form, navbar, modal, search_bar, button, banner, icon_button, tab, switch_button, checkbox, radio, sidebar, footer, header, and link.
  • Element identifier: Identifies the button or interactive element, including submit, register, and next_step.
For example, the attribute value for a submit button on the home page can be home_form_submit. When an element contains child elements, avoid using event-blocking methods such as stopPropagation() and preventDefault() because they can interfere with effective click tracking. In typical cases, you only need to apply the data-track-id or dtid attribute to the parent element, as child elements will automatically inherit it for tracking purposes. The following example shows how to implement this:
<button data-track-id="home_form_submit">
  <span>Child Element 1</span>
</button>
However, if using the event-blocking methods is necessary, ensure that each child element within the parent has the same tracking attribute to maintain accurate tracking. Input field collection rules For input fields with a data-track-id, the user input and the value of data-track-id will be collected for analyzing user behavior. In the following example, the keywords entered by the user and the value of home_search_bar_wallet will be collected.
<input type="text" data-track-id="home_search_bar_wallet" placeholder="Enter keywords" />
For sensitive information such as passwords and personal identification information, you can mark an input field as containing sensitive information by using data-track-sensitive="true", which will tell the tracking script to automatically ignore the data and not collect it. In the following example, the password entered by the user will not be collected by the tracking script.
<input type="password" data-track-id="login_form_password" data-track-sensitive="true" placeholder="Enter your password" />
If an input field is nested within other components (such as a form), the parent data-track-id will not override or replace the input field’s own data-track-id. In the following example, the data-track-id of the input field is login_form_email, not login_form.
<form data-track-id="login_form">
   <input type="text" data-track-id="login_form_email" placeholder="Email" />
</form>

useAddUidToBody

const useAddUidToBody: (userId: string) => void;
This hook converts a specified user ID from string to Base64 format and adds it as a uid attribute to the <body> tag of the HTML document. It is useful in scenarios where a user ID needs to be incorporated into the document structure for global tracking or analytics.

Parameters

NameTypeDescription
userIdstringThe user ID to be added to the <body> tag.

Sample code

The following example uses the useAddUidToBody function to add a uid attribute to the <body> tag with the user ID. When the user ID changes, the value of the uid attribute is updated accordingly.
import React from 'react';
import { useAddUidToBody } from '@cobo/cobo-ui-toolkit';

const UserProfile = () => {
  const userId = 'user123';

  useAddUidToBody(userId);

  return (
    <div>
      <h1>Hello,user {userId}</h1>
    </div>
  );
};

export default UserProfile;

Functions

getAuthInfo

type AuthInfo = {
    token: string;
    orgID: string;
    userID?: string;
};
const getAuthInfo: () => Promise<AuthInfo | undefined>;
This asynchronous function retrieves user authentication information from Cobo Portal.

Returns

  • Promise<[AuthInfo]>: For more details, refer to AuthInfo.
  • undefined: The authentication information is unavailable or the request fails.

Sample code

The following example retrieves user authentication information using the getAuthInfo function when the component mounts and displays that information.
import React, { useEffect, useState } from 'react';
import { getAuthInfo } from '@cobo/cobo-ui-toolkit';

const UserProfile = () => {
  const [authInfo, setAuthInfo] = useState<AuthInfo | undefined>(undefined);

  useEffect(() => {
    const fetchAuthInfo = async () => {
      const info = await getAuthInfo();
      setAuthInfo(info);
    };

    fetchAuthInfo();
  }, []);

  if (!authInfo) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>User Information</h1>
      <p>Token: {authInfo.token}</p>
      <p>Organization ID: {authInfo.orgID}</p>
      {authInfo.userID && <p>User ID: {authInfo.userID}</p>}
    </div>
  );
};

export default UserProfile;

parseJwtToken

const parseJwtToken: (token: string) => any;
This function parses a JSON Web Token (JWT) and returns the payload as a JSON object. Use this function to extract user information, permissions, and other related information in a JWT. You can use this function to parse the User Info Token, which contains the information of a Cobo Portal App user.

Parameters

NameTypeDescription
tokenstringThe JWT string to be parsed. It must be in the header.payload.signature format.

Returns

If the token is a valid JWT, the function returns the payload as a JSON object.

Errors

If the token format is incorrect or cannot be parsed, the function throws an error with messages such as:
  • Invalid Base64 encoding: The payload part of the token is not properly Base64 encoded.
  • Invalid token format: There is an issue parsing the token, for example, incorrect structure or failure to decode.

Sample code

The following example uses the parseJwtToken function to parse a User Info Token and logs the decoded payload to the console.
import { parseJwtToken } from '@cobo/cobo-ui-toolkit';

const token =
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';

try {
  const payload = parseJwtToken(token);
  console.log(payload);
} catch (error) {
  console.error(error.message);
}

verifyJwtToken

const verifyJwtToken: (token: string, publicKeySet: any) => Promise<boolean>;
This function verifies a JSON Web Token (JWT) using the specified public keys, ensuring that the token has not been tampered with and is valid. You can use this function to verify a Cobo Portal App user’s identity. Refer to User Info Tokens for more information.

Parameters

NameTypeDescription
tokenstringThe JWT to be verified. It must be in the header.payload.signature format.
publicKeySetanyA set of public keys used to verify the JWT signature. Each public key should have a kid attribute, which matches the kid attribute in the JWT header.

Returns

  • true: The JWT is valid.
  • false: The JWT is invalid.

Sample code

The following example verifies a User Info Token with the public key set retrieved from the specified URL. If the verification is successful, it extracts the information from the User Info Token and sets the information as the user’s information.
import { parseJwtToken, verifyJwtToken } from '@cobo/cobo-ui-toolkit';

get('https://api.dev.cobo.com/v2/oauth/authorize/jwks.json').then(async (res) => {
  const verified = await verifyJwtToken(token, res);
  if (!verified) return;
  const jwtInfo = parseJwtToken(token);
  setUserInfo({
    email: jwtInfo.email,
    roleNames: jwtInfo.role_names,
    roles: jwtInfo.roles,
    sub: jwtInfo.sub,
  });
});

getPortalLocale

type Locale = {

  locale: 'en-US' | 'zh-CN';

};
const getPortalLocale: (callback: (data: Locale) => void) => void;
This function listens for the current locale data of Cobo Portal and executes a callback when the locale data updates.
Call removeGetLocaleListener to clean up the listener when it is no longer needed, especially in components that may unmount.

Parameters

NameTypeDescription
callbackfunctionA function that takes a locale object as an argument.

Returns

void

Errors

Failed to get locale: The locale data is undefined.

Sample code

The following example listens for the locale data of Cobo Portal and logs it to the console when the data updates.
import { getPortalLocale } from '@cobo/cobo-ui-toolkit';

useEffect(() => {
  getPortalLocale((locale) => {
    console.log("locale", locale);
  });
}, []);

removeGetLocaleListener

const removeGetLocaleListener: () => void;
This function removes the listener for the current locale data of Cobo Portal. After you call getPortalLocale to listen to the locale data, use this function to clean up the listener when it is no longer needed, especially in components that may unmount.