fetch-auth-manager
Manage authentication in a stateless and simple manner, both in NodeJs and React, using Axios or GraphQL as transporters.
Usage
Install the latest version of fetch-auth-manager:
yarn add fetch-auth-manager
// or
npm install fetch-auth-manager
NodeJs
Inside NodeJs, you have access to three functions:
const manageAuth authenticate deauthenticate } = "fetch-auth-manager/server";
manageAuth(options): ExpressMiddleware
The manageAuth
function returns a middleware that verifies the authorization header using the JWT_SECRET
environment variable and injects the decoded payload in req.user
. If there is no token, this will simply set req.user
to null
. It's up to you to disallow unauthenticated requests!
Usage:
const app = ;const manageAuth = ; const authManager = ; app;
authenticate(response, tokenData, options)
The authenticate
function expects the Express Response object, any data you want present inside the token and some options. Call it when you want to set or update the user's JWT token.
const authenticate = ; const options = secret: processenvJWT_SECRET // default lifespan: processenvJWT_LIFESPAN // jwt ttl in seconds; { // your login logic ;}
deauthenticate(response)
The deauthenticate
function expects the Express Response object. It will remove the user's token.
const deauthenticate = ; { // your logout logic ;}
Browser
Utility methods
You can call these functions anywhere in your code to control/get auth state:
;
logout()
Will log the user out and update all connected providers.
hasAuth()
Returns a boolean value telling if the user has auth.
subscribe(fn): unsubscribeFn
Registers a callback that will get called everytime the auth state changes. This function returns a unsubscribe function that cancels the subscription when called.
React
At or near the root of your application, apply the AuthProvider
component.
; default { return <AuthProvider> <YourApp /> </AuthProvider> ;}
Then, whenever you need access to auth state, decorate any component with the withAuth
HOC.
; { // hasAuth is a boolean flag // decoded contains all the token payload return <div />;} AnyComponent;
Transports
Transports are interfaces that connect the frontend code with the server. There are two transports, GraphQL and Axios.
GraphQL
The GraphQL transport has support for both http
and ws
links.
Http Transport
;;;; const httpLink = ; const client = link: ApolloLink;
WS Transport
To use the WS transport, you need to prepare your backend. In your Apollo Setup:
const parseWSAuth from 'fetch-auth-manager/server'; const apolloServer = // ...your Config subscriptions: onConnect:
Then, just decorate the WSLink options
;;; const wsLink = uri: "ws://backend.com/graphql" options: ; const client = link: wsLink;
Axios
To use the Axios transport, add the interceptors to your Axios instance.
;; const axios = Axios; axiosinterceptorsrequest;axiosinterceptorsresponse;
Copyright e Licença
Copyright (c) 2019 Marcel de Oliveira Coelho sob a Licença MIT. Go Crazy. 🚀