use-jwt-manager
Advanced tools
Comparing version 0.1.72 to 0.1.73
@@ -9,4 +9,3 @@ interface UserDetails { | ||
user?: UserDetails; | ||
access_token?: string; | ||
refresh_token?: string; | ||
token?: string; | ||
initialized?: boolean; | ||
@@ -17,4 +16,3 @@ authenticated?: boolean; | ||
interface TokenParams { | ||
access_token: string; | ||
refresh_token?: string; | ||
token: string; | ||
[x: string]: any; | ||
@@ -28,3 +26,2 @@ } | ||
TOKEN_KEY: string; | ||
REFRESH_TOKEN_KEY: string; | ||
}; | ||
@@ -31,0 +28,0 @@ } |
@@ -1,1 +0,1 @@ | ||
module.exports=(()=>{"use strict";var e={613:(e,t,r)=>{r.r(t),r.d(t,{default:()=>h});const a=require("react");var n=r.n(a);const o=require("lockr");var s=r.n(o);const c=require("axios");var i=r.n(c);const u=(e,t)=>{switch(t.type){case"LOGIN":return{...e,...t.payload,authenticated:!0,initialized:!0};case"LOGOUT":return{authenticated:!1,initialized:!0}}};class l extends Error{constructor(e,t){super(e),this.cause=t,this.name="JwtError"}}const d={initialized:!1,authenticated:!1},h=({refresh:e,me:t,login:r,config:o})=>{const[c,h]=n().useReducer(u,d),{TOKEN_KEY:f,REFRESH_TOKEN_KEY:y}=o,p=(0,a.useCallback)((()=>{const t=s().get(y);c.authenticated||!t?h({type:"LOGOUT"}):(i().defaults.headers.Authorization="Bearer "+t,e().then(g).catch((e=>{throw new l("An error occurred trying to refresh the token",e)})))}),[c.authenticated]);(0,a.useEffect)(p,[]);const g=(0,a.useCallback)((async({access_token:e,refresh_token:r})=>{let a=r;return s().set(f,e),a?s().set(y,a):a=s().get(y),i().defaults.headers.Authorization="Bearer "+e,await t().then((t=>(h({type:"LOGIN",payload:{user:t,access_token:e,refresh_token:a}}),t))).catch((e=>{throw new l("An error occurred retrieving the user information",e)}))}),[]),O=(0,a.useCallback)((async e=>await r(e).then(g).then((e=>e)).catch((e=>{throw new l("An error occurred trying to log in",e)}))),[]),b=(0,a.useCallback)((async()=>(s().rm(f),s().rm(y),i().defaults.headers.Authorization=null,h({type:"LOGOUT"}),await!0)),[]);return{...c,login:O,logout:b,refresh:p}}}},t={};function r(a){if(t[a])return t[a].exports;var n=t[a]={exports:{}};return e[a](n,n.exports,r),n.exports}return r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var a in t)r.o(t,a)&&!r.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,get:t[a]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r(613)})(); | ||
module.exports=(()=>{"use strict";var e={613:(e,t,r)=>{r.r(t),r.d(t,{default:()=>h});const a=require("react");var n=r.n(a);const o=require("lockr");var i=r.n(o);const c=require("axios");var s=r.n(c);const u=(e,t)=>{switch(t.type){case"LOGIN":return{...e,...t.payload,authenticated:!0,initialized:!0};case"LOGOUT":return{authenticated:!1,initialized:!0}}};class l extends Error{constructor(e,t){super(e),this.cause=t,this.name="JwtError"}}const d={initialized:!1,authenticated:!1},h=({refresh:e,me:t,login:r,config:o})=>{const[c,h]=n().useReducer(u,d),{TOKEN_KEY:f}=o,y=(0,a.useCallback)((()=>{const t=i().get(f);c.authenticated||!t?h({type:"LOGOUT"}):(s().defaults.headers.Authorization="Bearer "+t,e().then(p).catch((e=>{throw new l("An error occurred trying to refresh the token",e)})))}),[c.authenticated]);(0,a.useEffect)(y,[]);const p=(0,a.useCallback)((async({token:e})=>(i().set(f,e),s().defaults.headers.Authorization="Bearer "+e,await t().then((t=>(h({type:"LOGIN",payload:{user:t,token:e}}),t))).catch((e=>{throw new l("An error occurred retrieving the user information",e)})))),[]),g=(0,a.useCallback)((async e=>await r(e).then(p).then((e=>e)).catch((e=>{throw new l("An error occurred trying to log in",e)}))),[]),O=(0,a.useCallback)((async()=>(i().rm(f),s().defaults.headers.Authorization=null,h({type:"LOGOUT"}),await!0)),[]);return{...c,login:g,logout:O,refresh:y}}}},t={};function r(a){if(t[a])return t[a].exports;var n=t[a]={exports:{}};return e[a](n,n.exports,r),n.exports}return r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var a in t)r.o(t,a)&&!r.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,get:t[a]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r(613)})(); |
@@ -6,4 +6,3 @@ import { UserDetails, UserContextReducerParams } from './constants/types'; | ||
user: UserDetails; | ||
access_token: string; | ||
refresh_token: string; | ||
token: string; | ||
} | {}; | ||
@@ -10,0 +9,0 @@ } | { |
@@ -7,3 +7,3 @@ { | ||
}, | ||
"version": "0.1.72", | ||
"version": "0.1.73", | ||
"description": "hook for jwt auth", | ||
@@ -10,0 +10,0 @@ "repository": { |
@@ -5,2 +5,66 @@ # use-jwt-manager | ||
depends on Lockr and axios | ||
1)Create a context | ||
``` | ||
import React from 'react'; | ||
import { jwtManagerContext } from 'use-jwt-manager/dist/constants/types'; | ||
export const AuthConext = React.createContext<Partial<jwtManagerContext>>({}); | ||
``` | ||
2)Create an Interceptor (optional): | ||
``` | ||
import axios from 'axios'; | ||
import { useContext, useEffect } from 'react'; | ||
import { useHistory } from 'react-router-dom'; | ||
import{ AuthConext } from '../contexts'; | ||
const useInterceptor = (): void => { | ||
const context = useContext(AuthConext); | ||
const history = useHistory(); | ||
useEffect(() => { | ||
axios.interceptors.response.use( | ||
(response) => response , | ||
(error) => { | ||
const { status } = error.response; | ||
if (status == 401) { | ||
if (context.refresh_token) { | ||
//@ts-ignore | ||
context.refresh(); | ||
} else { | ||
//@ts-ignore | ||
context.logout().then( | ||
()=> history.push('/login') | ||
) | ||
} | ||
} | ||
return Promise.reject(error); | ||
} | ||
); | ||
}, []); | ||
}; | ||
export default useInterceptor; | ||
``` | ||
3)Wrap your application with the Context provider | ||
``` | ||
export const Root: React.FC<{}> = ({}) => { | ||
const config = { TOKEN_KEY, REFRESH_TOKEN_KEY }; | ||
const authContext = useJWT({ login, me, refresh, config }); | ||
useInterceptor(); | ||
return ( | ||
<AuthConext.Provider value={authContext}> | ||
<Router> | ||
<Switch> | ||
<Route path="/login" component={Login} exact /> | ||
<PrivateRoute path="/" component={Home} exact /> | ||
</Switch> | ||
</Router> | ||
</AuthConext.Provider> | ||
); | ||
}; | ||
``` |
@@ -10,4 +10,3 @@ interface UserDetails { | ||
user?: UserDetails; | ||
access_token?: string; | ||
refresh_token?: string; | ||
token?: string; | ||
initialized?: boolean; | ||
@@ -19,4 +18,3 @@ authenticated?: boolean; | ||
interface TokenParams { | ||
access_token: string; | ||
refresh_token?: string; | ||
token: string; | ||
[x: string]: any; | ||
@@ -29,3 +27,3 @@ } | ||
login: (user: UserDetails) => Promise<TokenParams>; | ||
config: { TOKEN_KEY: string; REFRESH_TOKEN_KEY: string }; | ||
config: { TOKEN_KEY: string }; | ||
} | ||
@@ -36,3 +34,3 @@ | ||
logout: () => Promise<boolean>; | ||
refresh: () => void | ||
refresh: () => void; | ||
} | ||
@@ -39,0 +37,0 @@ |
import { UserDetails, UserContextReducerParams } from './constants/types'; | ||
type Actions = | ||
| { type: 'LOGIN'; payload: { user: UserDetails; access_token: string; refresh_token: string } | {} } | ||
| { type: 'LOGOUT' }; | ||
type Actions = { type: 'LOGIN'; payload: { user: UserDetails; token: string } | {} } | { type: 'LOGOUT' }; | ||
@@ -7,0 +5,0 @@ const userContextReducer = (state: UserContextReducerParams, action: Actions): UserContextReducerParams => { |
@@ -8,9 +8,6 @@ import Lockr from 'lockr'; | ||
const TOKEN_KEY = 'BANANA'; | ||
const REFRESH_TOKEN_KEY = 'BANANA_ROTATE'; | ||
function refresh(forceFail = false) { | ||
return new Promise<TokenParams>((resolve, reject) => { | ||
forceFail | ||
? reject({ code: 'B4N4N41', description: 'refresh stuff' }) | ||
: resolve({ access_token: 'new_at1', refresh_token: 'new_rt1' }); | ||
forceFail ? reject({ code: 'B4N4N41', description: 'refresh stuff' }) : resolve({ token: 'new_at1' }); | ||
}); | ||
@@ -28,9 +25,9 @@ } | ||
if (user.username == 'finto') { | ||
resolve({ access_token: 'new_at2', refresh_token: 'new_rt2' }); | ||
resolve({ token: 'new_at2' }); | ||
} | ||
reject({ code: 'B4N4N43', description: 'login stuff' }); | ||
reject({ code: 'B4N4N43' }); | ||
}); | ||
} | ||
const config = { TOKEN_KEY, REFRESH_TOKEN_KEY }; | ||
const config = { TOKEN_KEY }; | ||
@@ -45,10 +42,8 @@ test('not authenticated if no jwt present in ls at start', () => { | ||
expect(Lockr.get(TOKEN_KEY)).toBe(undefined); | ||
expect(Lockr.get(REFRESH_TOKEN_KEY)).toBe(undefined); | ||
}); | ||
test('authenticated if jw present at start', async () => { | ||
Lockr.rm(TOKEN_KEY); | ||
Lockr.rm(REFRESH_TOKEN_KEY); | ||
Lockr.set(REFRESH_TOKEN_KEY, 'old_rt'); | ||
Lockr.set(TOKEN_KEY, 'old_token'); | ||
const { result, waitForNextUpdate } = renderHook(() => useJWT({ login, me, refresh, config })); | ||
console.log(result.current); | ||
await waitForNextUpdate(); | ||
@@ -59,7 +54,5 @@ // assert initial state | ||
expect(result.current.user).toEqual(USER); | ||
expect(result.current.access_token).toEqual('new_at1'); | ||
expect(result.current.refresh_token).toEqual('new_rt1'); | ||
expect(result.current.token).toEqual('new_at1'); | ||
expect(Lockr.get(TOKEN_KEY)).toEqual('new_at1'); | ||
expect(Lockr.get(REFRESH_TOKEN_KEY)).toEqual('new_rt1'); | ||
}); | ||
@@ -69,3 +62,2 @@ | ||
Lockr.rm(TOKEN_KEY); | ||
Lockr.rm(REFRESH_TOKEN_KEY); | ||
const { result, waitForNextUpdate } = renderHook(() => useJWT({ login, me, refresh, config })); | ||
@@ -86,6 +78,4 @@ | ||
expect(result.current.user).toEqual(USER); | ||
expect(result.current.access_token).toEqual('new_at2'); | ||
expect(result.current.refresh_token).toEqual('new_rt2'); | ||
expect(result.current.token).toEqual('new_at2'); | ||
expect(Lockr.get(TOKEN_KEY)).toEqual('new_at2'); | ||
expect(Lockr.get(REFRESH_TOKEN_KEY)).toEqual('new_rt2'); | ||
@@ -100,6 +90,4 @@ await act(async () => { | ||
expect(result.current.user).toBe(undefined); | ||
expect(result.current.access_token).toBe(undefined); | ||
expect(result.current.refresh_token).toBe(undefined); | ||
expect(result.current.token).toBe(undefined); | ||
expect(Lockr.get(TOKEN_KEY)).toBe(undefined); | ||
expect(Lockr.get(REFRESH_TOKEN_KEY)).toBe(undefined); | ||
}); | ||
@@ -109,3 +97,2 @@ | ||
Lockr.rm(TOKEN_KEY); | ||
Lockr.rm(REFRESH_TOKEN_KEY); | ||
const { result, waitForNextUpdate } = renderHook(() => useJWT({ login, me, refresh, config })); | ||
@@ -128,7 +115,5 @@ | ||
expect(result.current.user).toBe(undefined); | ||
expect(result.current.access_token).toBe(undefined); | ||
expect(result.current.refresh_token).toBe(undefined); | ||
expect(result.current.token).toBe(undefined); | ||
expect(Lockr.get(TOKEN_KEY)).toBe(undefined); | ||
expect(Lockr.get(REFRESH_TOKEN_KEY)).toBe(undefined); | ||
}); |
@@ -45,5 +45,4 @@ const path = require('path'); | ||
filename: 'index.js', | ||
// library: 'reactHookName', | ||
libraryTarget: 'commonjs2', | ||
}, | ||
}; |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
16904
14
70
338