@postinumero/react-auth

User roles and rights based rendering.

Usage no npm install needed!

<script type="module">
  import postinumeroReactAuth from 'https://cdn.skypack.dev/@postinumero/react-auth';
</script>

README

@postinumero/react-auth

User roles and rights based rendering.

API

<Auth>

Wraps components with the auth context. Other components and hooks are available in the children.

import { Auth } from '@postinumero/react-auth';

function App() {
  return <Auth>…</Auth>;
}

withAuth(Component)

Wraps the application with the auth context. Other components and hooks are available in the wrapped component and in the children.

import { withAuth } from '@postinumero/react-auth';

function App() {
  // …
}

withAuth(App);

<IsAuthenticated>

Renders the content only for authenticated users. Optionally renders the fallback UI for non-authenticated users.

fallback: element (optional)

import { IsAuthenticated } from '@postinumero/react-auth';
// …
<IsAuthenticated fallback={<LoggedOut />}>
  <LoggedIn />
</IsAuthenticated>;

<HasRole>

Renders the content only for users with the given roles. Optionally renders the fallback UI for other users.

role: string | string[]

fallback: element (optional)

import { HasRole } from '@postinumero/react-auth';
// …
<HasRole role="admin" fallback={<Forbidden />}>
  <AdminPanel />
</HasRole>;

<IsAllowed>

Renders the content only for users with the given rights. Optionally renders the fallback UI for other users.

right: string | string[]

fallback: element (optional)

import { IsAllowed } from '@postinumero/react-auth';
// …
<IsAllowed right="admin" fallback={<Forbidden />}>
  <AdminPanel />
</IsAllowed>;

useCurrentUser()

Get the current user.

import { useCurrentUser } from '@postinumero/react-auth';

function UserInfo() {
  const currentUser = useCurrentUser();
  <div>{currentUser.name}</div>;
}

useSetCurrentUser()

Set the current user. User may have optional properties roles: string[] and rights: string[].

import { useSetCurrentUser } from '@postinumero/react-auth';

function Login() {
  const setCurrentUser = useSetCurrentUser();
  return (
    <button
      onClick={async () => {
        // Get user
        const user = await login(/*…*/);
        // And
        setCurrentUser(user);
      }}
    >
      Login
    </button>
  );
}

useIsAuthenticated()

Hook to detect if user is logged in.

import { useIsAuthenticated } from '@postinumero/react-auth';
// …
const isAuthenticated = useIsAuthenticated();

useHasRole(role: string | string[])

Hook to detect if user has any of allowed roles.

import { useHasRole } from '@postinumero/react-auth';
// …
const isAdmin = useHasRole('admin');

useIsAllowed(right: string | string[])

Hook to detect if user has any of allowed rights.

import { useIsAllowed } from '@postinumero/react-auth';
// …
const isAllowedEdit = useIsAllowed('edit');