npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@iamjs/react

v2.0.19

Published

This package contains React components that can be used to easily integrate the authorization library into a React application.

Downloads

75

Readme

@iamjs/react

This package contains the react hook for iamjs a library for easy role and permissions management for your application.

Installation

npm install @iamjs/core @iamjs/react
# or
yarn add @iamjs/core @iamjs/react
# or
pnpm add @iamjs/core @iamjs/react
# or
bun add @iamjs/core @iamjs/react

Usage

Basic usage

This example demonstrates the usage of the @iamjs/core and @iamjs/react packages for role-based authorization.

  1. Import the necessary components and functions from the packages:
import { Role } from '@iamjs/core';
import { createSchema, useAuthorization } from '@iamjs/react';
  1. Create a schema using the createSchema function:
const schema = createSchema({
  user: new Role({
    name: 'user',
    description: 'User role',
    meta: {
      name: 'user'
    },
    config: {
      books: {
        base: 'crudl',
        custom: {
          upgrade: true,
          downgrade: false,
          sort: true
        }
      }
    }
  })
});

In this example, the schema is created with a single role named 'user'. The role has a description, meta data, and configuration for the 'books' resource. The 'books' resource has 'crudl' scopes (create, read, update, delete, list), and additional custom permissions such as 'upgrade', 'downgrade', and 'sort'.

  1. Use the useAuthorization hook to access the authorization methods:
const { can } = useAuthorization(schema);

The useAuthorization hook takes the schema as a parameter and returns an object that includes the can method to check permissions.

  1. Use the can method to check if the user has permission:
const canDo = can('user', 'books', 'create').toString(); // 'true'

The can method is called with the role name ('user'), the resource name ('books'), and the action ('create'). It returns a boolean value indicating whether the user with the 'user' role has permission to create books.

In summary, this example demonstrates how to create a schema with a role and its permissions using the @iamjs/core package. Then, the @iamjs/react package is used to access the useAuthorization hook and check permissions using the can method.

Build a role from its permissions

This example also demonstrates the usage of the build function for permissions based authorization.

import { Role } from "@iamjs/core";
import { createSchema, useAuthorization } from "@iamjs/react";
import { useEffect, useState } from "react";

// Create the initial schema with a default roles
const schema = createSchema({
  user: new Role({
    name: "user",
    description: "User role",
    meta: {
      name: "user",
    },
    config: {
      books: {
        base: "crudl",
        custom: {
          upgrade: true,
          downgrade: false,
          sort: true,
        },
      },
    },
  }),
});

// Custom hook to fetch user permissions and build the role
const useUser = () => {
  const { build } = useAuthorization(schema);
  const [userRole, setUserRole] = useState(null);

  useEffect(() => {
    // Call the API endpoint to fetch user permissions
    fetch("/permssions")
      .then((response) => response.json())
      .then((data) => {
        // Build the role based on the received permissions
        const builtRole = build(data);
        setUserRole(builtRole);
      })
      .catch((error) => {
        console.error("Error fetching user permissions:", error);
      });
  }, []);

  return userRole;
};

const Component = () => {
  const userRole = useUser();

  if (!userRole) {
    return <div>Loading...</div>;
  }

  const { can, Show } = userRole;

  return (
    <div>
      <div>{can("books", "create").toString()}</div>
      <Show resources="books" actions="create">
        <div>Rendered if user has 'create' permission for 'books'</div>
      </Show>
    </div>
  );
};

Show component based on permission

This example also demonstrates the usage of the Show component for conditional rendering based on the user's permssions.

  1. Import the necessary components and functions from the packages:
import { Role } from '@iamjs/core';
import { createSchema, useAuthorization } from '@iamjs/react';
  1. Create a schema using the createSchema function:
const schema = createSchema({
  user: new Role({
    name: 'user',
    description: 'User role',
    meta: {
      name: 'user'
    },
    config: {
      books: {
        base: 'crudl',
        custom: {
          upgrade: true,
          downgrade: false,
          sort: true
        }
      }
    }
  })
});

The schema is created in the same way as in the previous example, with a role named 'user' and its permissions for the 'books' resource.

  1. Use the useAuthorization hook to access the authorization components:
const { Show } = useAuthorization(schema);

The useAuthorization hook is used to access the authorization components. In this example, only the Show component is extracted from the returned object.

  1. Render the Show component with the appropriate props:
<Show role="user" resources="books" actions="create">
  <div>can show</div>
</Show>

The Show component is used to conditionally render the child components based on the user's role and permissions. It takes props specifying the role, resources, and actions, and renders the child components if the user has permission.

In summary, this example demonstrates how to use the Show component from the @iamjs/react package to conditionally render components based on the user's role and permissions. The component is rendered within the Show component's block if the user has the specified role, resources, and actions.