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

identity-react

v1.1.4

Published

Reclaim Identity React Client

Downloads

279

Readme

Reclaim Identity for React

Reclaim Identity is a React-based authentication module that provides an easy-to-use interface for authenticating users with the Reclaim Protocol. It manages the OAuth 2.0 flow, handling user sign-in, token management, and user data retrieval within your React application.

Features

  • React-friendly authentication flow
  • OAuth 2.0 authentication with popup window
  • Automatic token management
  • User data retrieval and caching
  • Event-based auth state changes
  • TypeScript support
  • CSRF protection with state validation
  • Session-based authentication

Installation

You can install the Reclaim Identity package using npm:

npm i identity-react

Or using yarn:

yarn add identity-react

Usage

Initializing ReclaimAuth

In your React application, typically in a context provider or a top-level component:

import getReclaimAuth from 'identity-react';

const clientId = 'your-client-id';
const clientSecret = 'your-client-secret'
const redirectUri = 'your-redirect-uri';
const auth = getReclaimAuth(clientId, clientSecret, redirectUri);

function App() {
  // Your app code
}

Using ReclaimAuth in a Component

import React, { useState, useEffect } from 'react';
import getReclaimAuth, { type ReclaimUser } from 'identity-react';

const clientId = 'your-client-id';
const clientSecret = 'your-client-secret'
const redirectUri = 'your-redirect-uri';

function AuthComponent() {
  const [user, setUser] = useState<ReclaimUser | null>(null);
  const auth = getReclaimAuth(clientId, clientSecret, redirectUri);

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((newUser) => {
      setUser(newUser);
    });

    return () => unsubscribe();
  }, []);

  const handleSignIn = async () => {
    try {
      const user = await auth.signIn();
      console.log('Signed in user:', user);
    } catch (error) {
      console.error('Sign in failed:', error);
    }
  };

  const handleSignOut = async () => {
    try {
      await auth.signOut();
    } catch (error) {
      console.error('Sign out failed:', error);
    }
  };

  return (
    <div>
      {user ? (
        <>
          <p>Welcome, {user.id}</p>
          <button onClick={handleSignOut}>Sign Out</button>
        </>
      ) : (
        <button onClick={handleSignIn}>Sign In</button>
      )}
    </div>
  );
}

Creating a Custom Hook

You can create a custom hook to simplify the use of ReclaimAuth across your React components:

import { useState, useEffect } from 'react';
import getReclaimAuth, { type ReclaimUser } from 'identity-react';

const clientId = 'your-client-id';
const clientSecret = 'your-client-secret'
const redirectUri = 'your-redirect-uri';

export function useReclaimAuth() {
  const [user, setUser] = useState<ReclaimUser | null>(null);
  const auth = getReclaimAuth(clientId, clientSecret, redirectUri);

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged(setUser);
    return () => unsubscribe();
  }, []);

  return {
    user,
    signIn: () => auth.signIn(),
    signOut: () => auth.signOut(),
    getCurrentUser: () => auth.getCurrentUser(),
  };
}

API Reference

getReclaimAuth(clientId: string, clientSecret: string, redirectUri: string): ReclaimAuth

Returns the singleton instance of ReclaimAuth. Both parameters are required on first initialization.

signIn(): Promise<ReclaimUser>

Initiates the sign-in process by opening a popup window for authentication. Returns a Promise that resolves with the user data once the authentication flow is complete.

getCurrentUser(): ReclaimUser | null

Returns the current authenticated user object, or null if no user is signed in.

onAuthStateChanged(callback: (user: ReclaimUser | null) => void): () => void

Sets up a listener for changes in authentication state. Returns an unsubscribe function to remove the listener.

signOut(): Promise<void>

Signs out the current user and clears all authentication data.

Types

ReclaimUser

interface ReclaimUser {
    id: string;
    userData: { [key: string]: string };
    additionalData: { [key: string]: string }[];
}

Configuration

The ReclaimAuth module requires the following configuration:

  • clientId: Your Reclaim Protocol application ID (required)
  • clientSecret: Your Reclaim Protocol application secret (required)
  • redirectUri: The URI where your application will handle the OAuth callback (required)
  • apiBaseUrl: Defaults to 'https://identity.reclaimprotocol.org'
  • env: Defaults to 'production'

Security Features

  • CSRF protection using state parameter validation
  • Secure cookie handling with httpOnly flag
  • Origin validation for popup message handling
  • Credentials included in API requests
  • Secure popup window management

Browser Requirements

  • Modern browsers with support for:
    • Promises
    • Fetch API
    • Web Crypto API
    • PostMessage API
    • Cookies
    • ES6+ features

Error Handling

The SDK includes comprehensive error handling for:

  • Popup blocking
  • Authentication failures
  • Network errors
  • CSRF attempts
  • Token exchange failures
  • User data fetch failures

Example error handling:

try {
  await auth.signIn();
} catch (error) {
  if (error.message.includes('popup')) {
    // Handle popup blocked
  } else if (error.message.includes('code')) {
    // Handle authorization code error
  } else if (error.message.includes('token')) {
    // Handle token exchange error
  } else {
    // Handle other errors
  }
}

Best Practices

  1. Always clean up auth state listeners using the unsubscribe function
  2. Handle authentication errors appropriately
  3. Use HTTPS in production
  4. Store sensitive configuration in environment variables
  5. Implement proper error boundaries in your React components

Troubleshooting

Common issues and solutions:

  1. Popup Blocked

    • Ensure signIn() is called in response to a user action
    • Check browser popup settings
  2. Authentication Failures

    • Verify clientId and redirectUri are correct
    • Check API endpoint accessibility
    • Validate cookie settings
  3. Session Issues

    • Clear browser cookies
    • Check for proper credential inclusion
    • Verify CORS settings
  4. Integration Issues

    • Ensure proper initialization
    • Check for proper event handling
    • Verify proper TypeScript types usage

For additional support, please refer to the Reclaim Protocol documentation or reach out to the support team.