react-generic-user
v0.0.3
Published
Generic user session handling (redux or react context based) and login components.
Maintainers
Readme
Project status
Use case
Generic user session handling based on redux or a react context together with components to protect content and to log in. The library is independent of a concrete routing library.
Installation
You can install via package manager or simply download the compiled version as zip file here and inject:
npm install react-generic-userExample
Create a redux based session by providing how to authenticate, log in and log out:
import {useLocation} from 'react-router'
import sessionFactory from 'react-generic-user/redux'
export const {slice, useIsAdmin, useUser} = sessionFactory(
{
authenticate: async () => (await api.getSession()).user,
login: async ({login, password}) => await api.login(login, password),
logout: async () => (await api.logout()).ok
},
// Optional: Remembers initially requested locations.
{useLocation}
)
const store = configureStore({reducer: {user: slice.reducer}})Alternatively a react context based session can be used:
import sessionFactory from 'react-generic-user/context'
const {UserProvider, useUser} = sessionFactory({authenticate, login, logout})Create components to protect content and to log in by integrating your routing library:
import {Navigate, useLocation} from 'react-router'
import componentFactory from 'react-generic-user/components'
import 'react-generic-user/components.css'
const {Authenticated, Login} =
componentFactory(useUser, {Redirect: Navigate, useLocation})
const Application = () => <Routes>
<Route path="/login" element={<Login onSuccess={redirectBack} />} />
<Route
path="*"
element={
<Authenticated fallbackLocation="/login">
<Protected />
</Authenticated>
}
/>
</Routes>End-to-end tests can interact with the login form via its harness:
import loginHarness from 'react-generic-user/harness'
const {stable: {loginButton, nameInput, passwordInput}} = loginHarness(page)
await nameInput.fill('name')
await passwordInput.fill('password')
await loginButton.main.click()