Skip to content

betawafflem/AlbertFazullini

Repository files navigation

JWT XHR hook

Build Status Coverage Status

XHR hook to save JWT into localStorage and inject it to request. Suppose to work even in browser using <script> tag. Но это не точно.

Installation

yarn add fs-jwt-xhr-hook

or npm i --save fs-jwt-xhr-hook if you are still using npm

Usage

Simple import TokenHook using default export.

import TokenHook, { catchToken, injectToken } from 'fs-jwt-xhr-hook';

import { loginUrl, usersUrl } from './actions/urls';

const hook = new TokenHook();

hook.installHook(loginUrl, catchToken);
hook.installHook(usersUrl, injectToken);

JWT XHR hook contains 2 built-in callbacks:

const defaultCatchOpts = {
  tokens: [
    {
      name: 'authToken',
      path: ['token', 'auth_token'],
    },
    {
      name: 'refreshToken',
      path: ['token', 'refresh_token'],
    },
  ],
  saveToken: (key, token) => {
    localStorage.setItem(key, token);
  },
};

export const catchToken = (xhr, options = defaultCatchOpts) => {
  const { tokens, saveToken } = options;
  if (xhr.readyState === 4 && xhr.status === 200) {
    let res;
    if (xhr.responseType === 'json') {
      res = xhr.response;
    } else if (xhr.responseType === '' || xhr.responseType === 'text') {
      res = JSON.parse(xhr.response);
    }
    if (res) {
      tokens.forEach(({ name, path }) => {
        const resToken = path.reduce((prev, key) => {
          return prev[key];
        }, res);
        saveToken(name, resToken);
      });
    }
  }
};

export const injectToken = (xhr, token = 'authToken') => {
  const localToken = localStorage.getItem(token);
  if (xhr.readyState === 1 && localToken) {
    xhr.setRequestHeader('Authorization', `Bearer ${localToken}`);
  }
};

Own inject/catch callbacks

hook.installHook(loginUrl, (xhr, [options, token]) => {
	// do something
});

where xhr is a default XMLHttpRequest object

Contributing

PR's are welcome 👍

Credits

Maintained by Albert Fazullin.

Twitter: @hex22a

Written by Flatstack.

About

XHR hook to save JWT into localStorage and inject it to request

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published