1.0.0 • Published 2 years ago

@tourmalinecore/react-tc-auth v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

Tourmaline Core jwt authentication package

A simple provider, that will allow you easily implement athentication flow in your app.

Instalation

The package can be installed via npm:

npm install @tourmalinecore/react-tc-auth --save

Or via yarn:

yarn add @tourmalinecore/react-tc-auth

Configuration

import { createAuthService } from '@tourmalinecore/react-tc-auth';

const authService = createAuthService({
  authApiRoot: 'https://example.com/auth',
  authType: 'ls',
  tokenAccessor: 'accessToken',
  refreshTokenAccessor: 'refreshToken',
  tokenValueAccessor: 'value',
  tokenExpireAccessor: 'expiresInUtc',
})

createAuthService params

NameDescription
authApiRootAPI root for authentication, e.g.: yourdomain/api/auth
authTypeImplementation type of the authentication, not just storage usage. Accepts 'ls' or 'cookies'
tokenAccessorName of the property of the response object representing access token
refreshTokenAccessorName of the property of the response object representing refresh token
tokenValueAccessorName of the property of the token objects representing the token value
tokenExpireAccessorName of the property of the token objects representing the expiration time of the token in UTC
customGetFingerprintCustom fingerprint generator. Should return promise (async function)

Usage

createAuthService creates an authService object, which provides next functionality:

NameDescription
getAuthTokenGet the token value from the storage
getAuthTokenOrRefreshAsync function, gets the token from the storage, refreshes if expired
refreshTokenAsync function, calls the API to refresh the token
loginCallFetch the login data with axios
logoutCallFetch the logout data with axios
setLoggedInSets the token to the storage
setLoggedOutRemoves the token from the storage
subscribeOnTokenChangeAdds listener for token change
unsubscribeOnTokenChangeRemoves listener for token change
AuthContextReact auth context
AuthProviderReact context provider
withPrivateRouteReact HOC for the private routes
useAuthHook for the custom react auth context provider

Login

function login() {
    authService
      .loginCall({
        login: 'login',
        password: 'password',
      })
      .then((response) => authService.setLoggedIn(response.data));
  }

You can use it as is just by adding await getAuthTokenOrRefresh() to your API calls to get actual access token.

Use Token

function getData() {
    const token = await authProvider.getAuthTokenOrRefresh();

    return axios({
      url: 'https://example.com/data',
      method: 'GET',
      headers: {
        'Authentication': `Bearer ${token}`,
      },
    });
  }

Or you can add an error interceptor for Axios and call await refreshToken() inside it. Do not forget to change the logged state after it (setLoggedOut, setLoggedIn), these calls will notify the storage observers:

import axios from 'axios';

export const api = axios.create({
 baseURL: 'https://example.com',
});

api.interceptors.request.use((config) => {
 const token = authService.getAuthToken();

 config.headers.Authorization = token ? `Bearer ${token}` : '';

 return config;
}, () => {});

api.interceptors.response.use(() => {}, async (error) => {
 if (
   (error.response && error.response.status === 401)
   || (error.response && error.response.status === 403)
 ) {
   await authService.refreshToken();

   return api.request(error.config);
 }

 return Promise.reject(error);
});
1.0.0

2 years ago

0.2.1-alpha.0

2 years ago

0.2.0

2 years ago

0.1.2

3 years ago

0.1.0

3 years ago

0.1.1

3 years ago

0.0.7

3 years ago

0.0.6

3 years ago

0.0.5

3 years ago

0.0.4

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago