1.0.2 • Published 6 months ago

react-auth-lib v1.0.2

Weekly downloads
-
License
-
Repository
-
Last release
6 months ago

React Auth Library

React Authentication Library for handling access/refresh tokens from identity server

Version

1.0.2

Documentation

Documentation

Installation

Install react-auth-lib with npm

  npm install react-auth-lib
  cd my-project

Install react-auth-lib with yarn

  yarn add react-auth-lib
  cd my-project

Install react-auth-lib with yarn workspaces

  yarn workspace your-workspace add react-auth-lib
  cd my-project\your-workspace

Roadmap

  • Limit retry to a max retry count

  • Add Unit Test cases for Axios Interceptors

Running Tests

To run tests, run the following command

  npx pnpm run test

Usage/Examples

import React, { useContext } from 'react'
import { AuthProvider, AuthContext, http } from 'react-auth-lib'

/* sample app that demos the auth library usage */

function App () {
  return (
    <AuthProvider
      baseUrl='<YOUR-API-BASE-URL>'
      accessTokenUrl='<ACCESS-T0KEN-ENDPOINT>'
      refreshTokenUrl='<REFRESH-TOKEN-ENDPOINT>'
      clientId='<CLIENT-ID>'
    >
      <div className='App'>
        <header className='App-header'>
          <Content />
        </header>
      </div>
    </AuthProvider>
  )
}

function Content () {

  const auth = useContext(AuthContext)
  const handleLogin = async () => {
    try {
      await auth?.login('USERNAME', 'PASSWORD')
      // After successful login, the access token will be available.
    } catch (error) {
      console.error('Login failed:', error)
    }
  }

  /* GET TEST API CALL */
  const handleTestAPI = async (): Promise<any> => {
    try {
      const response = await http.get('/v1.2/API/TEST');
      // If the request is successful, you can handle the response here.
      return response.data;
    } catch (errorDetails: any) {
      // Handle the error details, including status code and error response
      if (errorDetails) {
        const { status, response } = errorDetails;

        console.error(`API request failed with status code ${status}`);
        if (response) {
          // Handle the error response, e.g., show an error message or log it.
          console.error('Error Response:', response);
        }
      }
      // You can rethrow the error or handle it as needed.
      throw errorDetails;
    }
  };
  

  return (
    <div>
      {auth?.accessToken ? (
        <>
          <div>
            <p>Welcome, you are authenticated!</p>
            <p>Access Token: {auth?.accessToken}</p>
          </div>
          <div>
            <p>Test API Request</p>
            <button onClick={handleTestAPI}>Login</button>
          </div>
        </>
      ) : (
        <div>
          <p>You are not authenticated.</p>
          <button onClick={handleLogin}>Login</button>
        </div>
      )}
    </div>
  )
}

export default App
1.0.2

6 months ago

1.0.1

7 months ago

1.0.0

7 months ago

0.0.0

7 months ago