npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ayetu/context

v1.0.14

Published

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

Downloads

785

Readme

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.