@ayetu/context
TypeScript icon, indicating that this package has built-in type declarations

1.0.26 • Public • Published

Ayetu Context

A context provider for managing user authentication, device registration, and WebSocket communication in React and React Native applications.

Installation

To install the package, use npm:

npm install @ayetu/context

Usage

1. Wrap Your Application with the Provider

To use the context, you need to wrap your main application component with the `AyetuContextProvider`. This makes the context available throughout your application.

Example in React (Web or Native)

// App.tsx

import React from "react";
import { AyetuContextProvider } from "@ayetu/context";
import MyComponent from "./MyComponent";

const App: React.FC = () => {
  return (
    <AyetuContextProvider>
      <MyComponent />
    </AyetuContextProvider>
  );
};

export default App;

2. Use the Custom Hook

You can use the `useAyetu` hook to access the context values and functions in any component.

Example Usage

// MyComponent.tsx

import React from "react";
import { useAyetu } from "@ayetu/context";

const MyComponent: React.FC = () => {
  const {
    auth: {
      socialSignIn,
      createAccount,
      registerDevice,
      requestOTP,
      signIn,
      refreshAccessToken,
      connectSocket,
    },
    state: { isConnected },
    sendMsg,
  } = useAyetu();

  const handleSocialSignIn = async () => {
    // Step 1: Start social sign-in process
    const result = await socialSignIn("google", "https://your-return-url.com");
    if (result.success) {
      window.location.href = result.data.redirectUrl;
    } else {
      console.error("Social sign-in failed:", result.error);
    }
  };

  const handleCreateAccount = async (
    socialToken: string,
    name: string,
    handle: string
  ) => {
    // Step 2: Create an account
    const accountResult = await createAccount(
      handle,
      name,
      "+1",
      "1234567890",
      "password123",
      socialToken
    );
    if (accountResult.success) {
      console.log("Account created:", accountResult.data);
    } else {
      console.error("Account creation failed:", accountResult.error);
    }
  };

  const handleRegisterDevice = async () => {
    // Step 3: Register a device
    const deviceResult = await registerDevice("My Device");
    if (deviceResult.success) {
      console.log("Device registered:", deviceResult.data);
      // Store device details securely here
    } else {
      console.error("Device registration failed:", deviceResult.error);
    }
  };

  const handleRequestOTP = async () => {
    // Step 4: Request an OTP
    const otpResult = await requestOTP("+1", "1234567890");
    if (otpResult.success) {
      console.log("OTP sent:", otpResult.data.otpSent);
    } else {
      console.error("OTP request failed:", otpResult.error);
    }
  };

  const handleSignIn = async (otp: string, device: any) => {
    // Step 5: Sign in using OTP and device
    const signInResult = await signIn(
      "+1",
      "1234567890",
      "password123",
      otp,
      device
    );
    if (signInResult.success) {
      console.log("Signed in successfully:", signInResult.data);
      // Store accessToken and refreshToken securely
      // Automatically connect WebSocket upon successful sign-in
    } else {
      console.error("Sign in failed:", signInResult.error);
    }
  };

  const handleWebSocketConnection = () => {
    // Manually connect to WebSocket if needed
    connectSocket("your-access-token");
  };

  const handleSendMessage = (action: string, data: any) => {
    // Step 7: Send WebSocket message
    if (isConnected) {
      sendMsg(action, data);
    } else {
      console.error("Cannot send message: WebSocket is not connected.");
    }
  };

  return (
    <div>
      <button onClick={handleSocialSignIn}>Social Sign In</button>
      <button
        onClick={() => handleCreateAccount("socialToken", "John Doe", "@john")}
      >
        Create Account
      </button>
      <button onClick={handleRegisterDevice}>Register Device</button>
      <button onClick={handleRequestOTP}>Request OTP</button>
      <button
        onClick={() =>
          handleSignIn("123456", {
            /* device object */
          })
        }
      >
        Sign In
      </button>
      <button onClick={handleWebSocketConnection}>Connect WebSocket</button>
      {/* Add UI for sending messages via WebSocket */}
    </div>
  );
};

export default MyComponent;

Step-by-Step Guide

  1. Social Sign-In: Use `socialSignIn(provider, returnUrl)` to initiate a social sign-in process. You will receive a `redirectUrl` that will redirect the user to complete the sign-in. The `returnUrl` is the URL the user will be redirected back to after successful authentication, along with the `socialToken`, `name`, and `handle`.

  2. Create an Account: If the user does not have an account, call `createAccount(handle, name, telephoneCountryCode, telephoneNumber, password, socialToken)` to create one. This returns a `userId` and an `otpSent` boolean indicating whether an OTP was sent.

  3. Register a Device: Use `registerDevice(deviceName)` to register a new device. This returns an object containing device information, which should be stored securely.

  4. Request OTP: Call `requestOTP(telephoneCountryCode, telephoneNumber)` to request an OTP for the given phone number. This function will return an `otpSent` boolean indicating whether the OTP was successfully sent.

  5. Sign In: After receiving the OTP, use `signIn(telephoneCountryCode, telephoneNumber, password, otp, device)` to sign in the user. This will return the `deviceId`, `accessToken`, and `refreshToken`. The `refreshToken` should be stored securely for future use. Note: Upon successful sign-in, `connectSocket(accessToken)` is called automatically to establish a WebSocket connection.

  6. Connect WebSocket: While the WebSocket connection is established automatically upon sign-in, you can also manually call `connectSocket(accessToken)` to reconnect if the connection is lost or needs to be reestablished.

  7. Send WebSocket Message: After a successful WebSocket connection, use `sendMsg(action, data)` to send messages to the server and listen for state updates.

License

MIT

Contributions

Contributions are welcome! Please open an issue or submit a pull request.

Package Sidebar

Install

npm i @ayetu/context

Weekly Downloads

26

Version

1.0.26

License

MIT

Unpacked Size

22.3 kB

Total Files

17

Last publish

Collaborators

  • ayetu-devs