@bithero/simple-react-auth
v1.0.1
Published
A set of react components for authorization
Downloads
12
Maintainers
Readme
simple-react-auth
A set of react components for authorization
License
This project is licensed under AGPL-3.0-or-later. See the LICENSE
file for more informations.
Usage
For a detailed example, see the example
folder.
AuthProvider
To use this library, you first need to wrap your app with an custom auth provider:
import { AuthProvider } from '@bithero/simple-react-auth';
const MyAuthProvider = ({ children }) => {
return (
<AuthProvider client={...} onRedirect={...}>
{children}
</AuthProvider>
);
};
// As you see, with this lib you even can wrap the browserrouter with the auth provider!
root.render(
<MyAuthProvider>
<BrowserRouter>
<App/>
</BrowserRouter>
</MyAuthProvider>
);
Next, you have to implement & supply a instance of IAuthClient<TUser>
. This is a type that will be called to do the actual login/logout actions, check the user's session (i.e. localstorage and similar technologies) and get the user data. The generic argument (TUser
) is used to specify the type the userdata a client produces has.
Here's an example:
import { IAuthClient } from '@bithero/simple-react-auth';
type MockUser = { name: string; };
class MockClient implements IAuthClient<MockUser> {
private user: MockUser | null = null;
async login(params: any): Promise<void> {
// Handles the login.
// The parameters are the one provided by your application.
// This method should fill in the user field above
// and throw if any issue arieses.
}
async logout(): Promise<void> {
// Handles the logout.
// You should cleanup all cached data from a login here.
}
async checkSession(): Promise<void> {
// Called on app startup to determine if already logged in.
// In other words: it checks a users "session". Effectivly
// the client should after this be the same state as after
// a call to '.login()'.
}
async getUser(): Promise<MockUser | null> {
// Simple accessor to the user object.
// Can be as complex or simple as you need it.
return this.user;
}
}
Next we also need to supply a redirect callback which is called when the library needs to take the user to the login page.
It can either be a normal lambda such as
const onRedirect = () => {
window.location = "/login";
};
but to use things as navigate()
from react-router, you need to use a bit more complicated syntax:
import { useNavigate } from 'react-router-dom';
import { createHookAware } from '@bithero/react-helpers';
const onRedirect = createHookAware(
// This is a object which maps a name to the hook it should call;
// Here it makes 'navigate' an alias to the result of `useNavigate`.
{ 'navigate': useNavigate, },
// This NEEDS to be a function; a arrow function will NOT work!
// It gets `this` set to a object where all keys / members are
// the names declared in the object above, with the result of the
// specified hooks as value.
function() {
// 2 second timeout before redirecting to the login.
setTimeout(() => {
this.navigate('/login');
}, 2000);
}
);
For more informations, see the @bithero/react-helpers
package.
useAuth
With this, you can finish configuring <AuthProvider>
. Now in it's children you can use useAuth
to get the auth object:
import { useAuth } from '@bithero/simple-react-auth';
function HomePage() {
const auth = useAuth();
// Auth gives access to all functions of the library:
// auth.login(...) starts a login
// auth.logout() starts a logout
// auth.refreshUser() refreshes the user object
// (by calling client.getUser one time) and notifying
// all consumers.
// auth.error contains the last error
// auth.isAuthenticated is a flag that, when true,
// expresses that a user is authenticated.
// auth.user is the user object as returned by client.getUser
};
withAuth
A simple higher order component, which wraps the provided component in a consumer for the auth context, and additionally providing the current auth to it as parameter (same return type as if you'd use useAuth
).
import { withAuth } from '@bithero/simple-react-auth';
const HomePage = withAuth(({ auth }) => {
const { user } = auth;
return <pre>{JSON.stringify(user)}</pre>;
});
withAuthRequired
A higher order component, which requires a authenticated user to render the provided component. If there is no authenticated user, it will call the optionally supplied IAuthRequiredOpts.onRedirect
to render a alternative text and runs the onRedirect
hook provided to the <AuthProvider>
to redirect the user to the login page.
import { withAuthRequired } from '@bithero/simple-react-auth';
const authRequiredOpts: IAuthRequiredOpts = {
onRedirect() {
return <div>Youre being redirected to the login now.</div>;
}
};
const Protected = withAuthRequired(() => {
return <>...</>;
}, authRequiredOpts);
function AppRoutes() {
return <Routes>
<Route path="/plugin"/>
<Route path="/protected" element={<Protected/>}/>
</Routes>;
}