React authentication manager 🔑
react-authmanager is a highly-configurable manager for react. It manages users authentication with JWT in your app and provides guards HOCs to secure components in a flexible and simple way.
1 - Getting started
npm install --save react-authmanager
, then you have to configure the package.
To manage configuration, you need to import the default Authmanager.
You need to configure the manager before starting to use, so your highest component file is the best place (by example, it's the App.js
file with a create-react-app instance !)
You can also create a new manager instance.
; const customManager = Authmanager;
react-authmanager needs:
- to know how to login the user from the server and get a token back (
fetchToken
) - to know how to get the current logged user informations from the server (
fetchUser
)
you will need:
- to include the current token in your requests headers authorization (
getToken
)
Minimal configuration for the manager
; // how to login the user from the server and get a token backAuthmanagerconfigfetchToken = async { ... // login user with an ajax call to the server and return the given token return token;} // how to get the current logged user informations from the serverAuthmanagerconfigfetchUser = async { ... // get current logged user informations from the server with an ajax call and return any data you will need return user;}
Authorize your requests
// include the current token in your requests headers authorization;
For more configurations, please read the Authmanager section below.
2 - Authenticate users
withAuth HOC injects in your component helpers to manage authentication: login, logout and auth.
login and logout are functions to log users. auth is an object that contains a state of operations.
prop | default | description |
---|---|---|
login | function send credentials to the server to get a token back |
|
logout | function remove the stored token |
|
auth: | object informations about the current state of operations |
|
-- loading | false | bool is authentication (login or logout) currently loading |
; Component { const credentials = email: 'hello@example.com' password: 'ThisIsASecret' ; // or whatever data you want to send to the server (see the getToken configuration in the Minimal configuration section above) thisprops } { if thispropsauthloading return <MyLoadingComponent />; return ... ; } ... ; // or customManager.withAuth(LoginComponent); ... Component { thisprops } ... ; // or customManager.withAuth(LogoutComponent);
You can also call the login and logout methods anywhere on the manager with Authmanager.login()
and Authmanager.logout()
3 - Access user informations
withUser HOC will automatically injects an user object in your component props.
This object contains informations about the current user:
prop | default | description |
---|---|---|
user: | object containing current user informations |
|
-- loading | false | bool is user currently loaded from the server |
-- logged | false | bool is the current user logged in (setted by isUserLogged ) |
-- ... | null | any informations about the user sent by the server (setted by getUser ) |
; Component { if thispropsuserlogged ; else ; } ... ;
4 - Secure components
withGuard HOC helps you protect your components in a flexible way. By example, you can render a login form instead of a component if no user is logged in.
It needs a guard as parameter. A guard is just a function that returns a component, so you can easily create your own guards.
A guard function has parameters:
prop | description |
---|---|
user | object the current user object |
next | function a function that returns the current Component |
props | object the current component props |
; const loggedGuard = { if userloading return <MyLoadingComponent />; // render a loading component if user is currently fetched from the server if userlogged return ; // render the component if user is not loading and is logged return <MyLoginComponent />; // render a login component by default (if user is fetched from the server but not logged)} Component { return <div>This message is visible only for logged users !</div> } ... MyComponent;
You can inject data in your rendered component props through the next function
const guardThatInjects = { return ;} Component { console; // true return <div>This message is visible only for logged users !</div> } ... MyComponent;
You can also configure you guards from outside the component file with the addGuard
Authmanager function :
Authmanager; ... Component { return <div>This message is visible only for logged users !</div> } ... MyComponent;
5 - Authmanager
Authmanager.config
5.1 - To edit the configuration of react-authmanageryour manager, you have to override the config object:
; // will change the way how the manager will login the user and get a token back, see belowAuthmanager {}
fetchToken([credentials]) [async]
Get an authentication token when an user tries to login. fetchToken
is called when the auth login function is executed to store the token in localStorage.
Parameters
- [
credentials
] (Object
) Argument given by the login function. (when you callAuthmanager.login(credentials)
)
Return (String
)
Need to return a token that will be stored
default
fetchToken = null;
example with axios
AuthmanagerconfigfetchToken = async { const data = await axios; return datatoken;}
fetchUser() [async]
Get the current authenticated user. fetchUser
is called when the manager initialize its store and after an user login.
Return (Object
)
Need to return informations about the current logged user
default
fetchUser = null;
example with axios
AuthmanagerconfigfetchUser = async { const data = await axios; return data;}
isUserLogged([user]) [async]
Define if the current user (returned by getUser
) is logged. isUserLogged
is called after each user state change. The result is set in user.logged
.
Parameters
- [
user
] (Object
) Object returned by thegetUser
function.
Return (Boolean
)
Need to return a boolean that tell if the current user (returned by `getUser`) is logged.
default
!!userData && Objectlength > 0;
By default, isUserLogged
returns true if fetchUser
returns a non-empty object
Authmanager
utils
5.2 - react-authmanager also provides some utilities to manage the manager from your app:
; // will return the current stored token, or null, see belowconst token = Authmanager
getToken()
Returns the current stored token (in localStorage). You should use getToken
to authorize your requests to the server
Return (String
)
Returns the token stored after the `fetchToken` call
example with axios
axiosdefaultstransformRequest;
setToken([token])
Manually set a token. You can call the setToken
if you want to implements your own login function.
Parameters
- [
token
] (String
) String token that will be returned by thefetchToken
function.
Return utils (Object
)
Need to return a boolean that tell if the current user (returned by `getUser`) is logged.
example
Authmanager;Authmanager;
addGuard([guard])
Create a guard at the manager level, you will be able to reuse the guard just by giving its name
Parameters
- [
guard
] (Function
) A function that returns a component or call the next function to render the default component.
Return Component | next()
Need to return a valid React component or call the next function given in parameters.
example
Authmanager;
getUser()
Call the fetchUser
function and update the redux store. You can use this function to refresh the current logged user from the server
Return utils (Object
)
Returns a promise that resolves the new user data
🚀