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

@deriv-com/auth-client

v1.3.7

Published

[![Coverage Status](https://coveralls.io/repos/github/deriv-com/auth-client/badge.svg?branch=master)](https://coveralls.io/github/deriv-com/auth-client?branch=master) [![Coveralls](https://github.com/deriv-com/auth-client/actions/workflows/coveralls.yml/b

Downloads

10,565

Readme

Auth Client Project

Coverage Status Coveralls Build and Test Release

This project is designed to handle authentication using OAuth2 with Hydra and OIDC. The project is divided into two phases:

  1. Phase 1: OAuth2 with Hydra
  2. Phase 2: OIDC Public Client (coming soon)

Table of Contents

Getting Started

Prerequisites

  • Node.js (>= 14.x)
  • npm (>= 6.x)

Installation

  1. Clone the repository:

    git clone https://github.com/your-username/auth-client.git
    cd auth-client
  2. Install dependencies:

    npm install
  3. Start the development server:

    npm run dev

Phase 1: OAuth2 with Hydra

In this phase, we use OAuth2 with Hydra for authentication.

Setting Up Hydra

  1. Follow the Hydra documentation to set up Hydra in QA box environment.
  2. Configure your OAuth2 settings in the project.

Using the OAuth2 Hook

Use the useOAuth2 hook within your components.

import React from 'react';
import { useOAuth2, TOAuth2EnabledAppList } from '@deriv-com/auth-client';

const YourComponent = () => {
     const [OAuth2EnabledApps, OAuth2EnabledAppsInitialised] = useGrowthbookGetFeatureValue<TOAuth2EnabledAppList>({
        featureFlag: 'hydra_be',
    });

    const { logout } = useAuthData(); // Your custom hook or function to handle logout

    const OAuth2GrowthBookConfig = {
       OAuth2EnabledApps,
       OAuth2EnabledAppsInitialised
    };

    const WSLogoutAndRedirect = async () => {
        await logout();
        // Redirect or perform any additional actions here
    };

    const { OAuth2Logout } = useOAuth2(OAuth2GrowthBookConfig, WSLogoutAndRedirect);

    return (
        <div>
            <button onClick={OAuth2Logout}>Logout</button>
        </div>
    );
};

export default YourComponent;

Phase 2: OIDC Public Client

At Deriv, we are implementing Hydra and OpenID Connect (OIDC) to modernize and enhance our authentication and authorization mechanisms. This transition is crucial for ensuring secure, scalable, and standards-compliant access management for our applications and users.

Implementation Details

Most of the setup and implementation is already done in this library in the background. Just need to import a few things are you're good to go.

Login Flow

  • Login button component
import {requestOidcAuthentication } from '@deriv-com/auth-client';

 const handleLogin = async () => {
      await requestOidcAuthentication({
        redirectCallbackUri: `${window.location.origin}/callback`,
      });
  };

<button onClick={handleLogin}>Login</button>

Callback Page

You would need to create a new route and page for this section in your app. This page will handle the legacy token issuance to the consumer apps.

import React from 'react';
import { Callback } from '@deriv-com/auth-client';
import { transformAccountsFromResponseBody } from '@site/src/utils';
import useAuthContext from '@site/src/hooks/useAuthContext';

const CallbackPage = () => {
  const { updateLoginAccounts } = useAuthContext();

  return (
    <Callback
      onSignInSuccess={(tokens) => {
        const accounts = transformAccountsFromResponseBody(tokens);

        updateLoginAccounts(accounts);

        window.location.href = '/';
      }}
    />
  );
};

export default CallbackPage;

The tokens returned from the onSignInSuccess will be of this format:

{
  acct1: 'CR123123',
  curr1: 'USD',
  token1: 'a1-zxcnzxchzxc1'
  acct2: 'CR998989',
  curr2: 'EUR',
  token2: 'a1-fidifdf0991',
  ...
}

You need to convert the tokens into a format that your app understands and works with. Once that’s done, save them securely in localStorage or sessionStorage.

Most of the apps are already set up to look for things like client-accounts or accountsList in storage. If it finds them, it will automatically authorize the user in. Therefore after transforming the tokens and storing them its very crucial to redirect to the main page of your app, so the app can authorize successfully.

Once the legacy tokens are sent to the consumer apps, the library assumes that the user is logged in therefore it sets a cookie called logged_state to true. This will be helpful for the silent login and single logout feature.

Note : The callback page does NOT handle authorize calls. Its sole purpose is to do the access token exchange and return back the legacy tokens to the consumer apps.

Logout Flow

This logout process combines two parts: clearing OAuth session cookies through the OAuth2Logout function and running custom cleanup logic specific to your app (like clearing user accounts or tokens). Let’s break it down step-by-step:

  1. This function is provided by the @deriv-com/auth-client library. It uses an iframe to redirect the user to the end session endpoint of the OAuth provider. The main job of OAuth2Logout is to clear any cookies set by the OAuth system during the login session. Your App's Custom Logout Logic.

  2. In addition to clearing OAuth cookies, your app needs to handle its own logout tasks, such as: Logging the user out from the backend (via API or WebSocket calls). Clearing stored user data (like tokens or account information) from localStorage or sessionStorage.

  3. Combining Both The OAuth2Logout function allows you to pass your custom logout logic (called the consumer logout function) as a parameter. Once the OAuth session cookies are cleared, the consumer logout function runs to ensure the user is fully logged out from both the backend (BE) and frontend (FE).

  4. Once the logout is completed, the cookie logged_state will be set to false.

import { OAuth2Logout } from '@deriv-com/auth-client';

// we clean up everything related to the user here, for now it's just user's account
// later on we should clear user tokens as well
const logout = useCallback(async () => {
    await apiManager.logout();
    updateLoginAccounts([]);
    updateCurrentLoginAccount({
      name: '',
      token: '',
      currency: '',
    });
}, [updateCurrentLoginAccount, updateLoginAccounts]);

const handleLogout = () => {
    OAuth2Logout(logout);
};

// In your button
<button onClick={handleLogout}>Logout</button>