Giter Site home page Giter Site logo

pundit's Introduction

Pundit.js

Minimal and tiny authorisation library that uses a plain old JavaScript object (POJO).

  • No dependencies
  • Written in TypeScript
  • Small bundle size
  • React/Preact support

Adapted from the Pundit Ruby gem.

Introduction

Similar to the Pundit gem's simple PORO (plain old Ruby object) architecture, this library maintains a small, user/record interface that is designed to be easy to use, flexible for evolving needs, and simple to test. Authorisation is an important part of applications, and is often overly coupled with business logic.

With Pundit.js, we attempt to address some of that coupling by wrapping authorisation logic and providing components to keep your logic concise and readable where it's used.

Installation

npm install --save pundit
# yarn add pundit
# pnpm add pundit

Usage

In order to use Pundit.js, you can initialise a policy by setting up an object of functions/methods called actions. Actions typically map to permissions or routes in your application.

Client-side permissions should not replace a proper authorisation system in your backend.

Creating a policy

A policy accepts a user, often the current user of your session, and the resource you wish to authorise against, referred to as a record.

Policies can be defined by extending the Policy class. Add a constructor that accepts the user and record objects as parameters, also calling this.setup.apply(this) to initialise the actions defined in the class.

import { Policy } from 'pundit'

export default class PostPolicy extends Policy {
  constructor(user, record) {
    super(user, record)
    this.setup.apply(this)
  }

  edit() {
    return this.user.id === this.record.userId
  }

  destroy() {
    return this.user.isAdmin
  }
}

Actions are defined as methods belonging to the extended Policy class. Each action method should return true or false depending on whether the specified user/record combination is permitted for that action.

You can then instantiate the class and use the can method to check if the action is authorised.

import PostPolicy from 'src/policies/post.policy.js'

const user = { id: 1, isAdmin: false }
const post = { id: 11, userId: 1 }
const postPolicy = new PostPolicy(user, post)

postPolicy.can('edit') // Returns true
postPolicy.can('destroy') // Returns false

Since the role of Pundit.js is to reuse authorisation logic, for real world use we recommend that you define policy classes in a centralised folder in your application such as src/policies. The policies can then be imported into each file that needs to check the authorisation rules for the resource type.

Actions can also be added to an instantiated policy by using the add method which accepts a plain function with user and record parameters. The following is equivalent logic to defining policy actions by extending the Policy class:

import { Policy } from 'pundit'

const user = { id: 1, isAdmin: false }
const post = { id: 11, userId: 1 }
const postPolicy = new Policy(user, post)

postPolicy.add('edit', (user, record) => user.id === record.userId)
postPolicy.add('destroy', (user) => user.isAdmin)

postPolicy.can('edit') // Returns true
postPolicy.can('destroy') // Returns false

Using with React

You can determine what is shown based on what a user is authorised to see by using the When component.

import { When } from 'pundit'
import PostPolicy from 'src/policies/post.policy.js'

// ...

return (
  <When can="edit" policy={postPolicy} user={user} record={post}>
    <EditButton />
  </When>
)

The user and record attributes are not required if these passed into the policy's contructor when instantiating it. The following acts as a shorthand:

return (
  <When can="edit" policy={new PostPolicy(user, post)}>
    <EditButton />
  </When>
)

In order to avoid passing user/policy/record props to every usage of the When component you can use the PunditProvider.

import { PunditProvider, When } from 'pundit'
import PostPolicy from 'src/policies/post.policy.js'

// ...

return (
  <PunditProvider policy={postPolicy} user={user} record={post}>
    <When can="view">
      <Link />
    </When>
    <When can="fork">
      <ForkButton />
    </When>
    <When can="edit">
      <EditButton />
    </When>
    <When can="destroy">
      <DeleteButton />
    </When>
  </PunditProvider>
)

As with the When component, you can pass the user and record attributes via the policy's constructor with PunditProvider. You can also override these attributes for particular usages of When within the provider, for example to check if an alternative user or record is authorised.

return (
  <PunditProvider policy={new PostPolicy(user, post)}>
    <When can="view">
      <Link>View Post</Link>
    </When>
    <When can="view" user={masqueradeUser}>
      <Link>View Post Masquerading as {masqueradeUser.name}</Link>
    </When>
    <When can="view" record={nextPost}>
      <Link>View Next Post</Link>
    </When>
  </PunditProvider>
)

Testing

Policies can be unit tested, for example with Jest/Vitest:

import PostPolicy from 'src/policies/post.policy.js'

describe('post policy, edit action', () => {
  const user = { id: 1 }

  it('grants access if post is authored by user', () => {
    const post = { userId: user.id }
    expect(new PostPolicy(user, post).can('edit')).toBe(true)
  })

  it('denies access if post is not authored by user', () => {
    const differentUser = { id: 2 }
    const post = { userId: differentUser.id }
    expect(new PostPolicy(user, post).can('edit')).toBe(false)
  })
})

License

MIT

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Authors

Built by johno (@4lpine) and Chris Alley.

pundit's People

Contributors

chrisalley avatar dependabot[bot] avatar johno avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Forkers

jstacoder

pundit's Issues

I'm interested in maintaining this package

Hi @johno,

Chris Alley, author of the Pundit Matchers gem here. I'm a TypeScript developer who is reviewing options for creating "Pundit for JavaScript" that would be used in at least one production application. Rather than creating more fragmentation on npm, I'm interested in adopting or helping to maintain this package.

Some ideas that I have to improve the project include:

  • Modernise development dependencies (in progress)
  • Add React tests (in progress)
  • Add further tests for policy.ts
  • Host the repo on the Pundit Community GitHub organisation, with multiple maintainers who can come and go.
  • Split the React code into a seperate package, for example @pundit/react. This would give us the option to create other integrations for Svelte, Vue, etc without increasing the size of the package.
  • Convert the project to a monorepo, for example managed via pnpm workspaces.
  • Create Jest/Vitest matchers, similar to Pundit Matchers.
  • Investigate recreating other parts of Pundit (policy scopes, permitted attributes).
  • Investigate alternative policy syntax using class methods for policy actions.

Please let me know what your thoughts are. Would this be a welcome future for the project, or better suited to a seperate project?

Require 2FA to publish package

Currently, the pundit package does not require 2FA to publish:

Screenshot 2023-08-30 at 8 39 59 PM

I suggest we change this to the highest level of security, "Require two-factor authentication and disallow tokens". Do you concur @johno?

Allow multiple JSX elements to be used inside <When /> without wrapping in fragment

Currently to include multiple JSX elements inside of a When block it requires us to wrap the elements inside of a React fragment:

<When can="edit">
  <>
    <button type="button">Edit</button>
    <button type="button">Publish</button>
  </>
</When>

It would be cleaner to nest these within <When /> directly, e.g.

<When can="edit">
  <button type="button">Edit</button>
  <button type="button">Publish</button>
</When>

Allow policy actions to be defined via class methods only

Following the discussion in #41, it would be simpler to be able to define actions without explicitly defining an actions map, e.g.

class PostPolicy extends Policy {
  user: AuthorisableUser
  record: AuthorisablePost

  constructor(user: AuthorisableUser, record: AuthorisablePost) {
    super(user, record)
  }

  view(): boolean {
    return true
  }

  publish(): boolean {
    return this.user.id === this.record.userId
  }

  destroy(): boolean {
    return this.user.isAdmin
  }
}

Add Jest/Vitest matchers for testing policy actions

In order to make policy tests less verbose, it would be useful to include some Jest matchers, similar to what we have in Pundit Matchers.

I don't think we need to reproduce the whole Pundit Matchers API, which follows a "There's more than one way to do it" / TMTOWTDI approach. A subset of permitOnlyActions, permitAllActions, and permitActions to begin with would cover most scenarios.

Initially I could add some matchers to the existing codebase/package, with the intent to split them into a seperate package once we've moved to pnpm workspaces.

@johno any thoughts here?

For some reason, it doesn't work for me

Hi @johno, want to use your solution in my project, but for some reason, it doesn't work.

What I did:

import React, { useEffect } from "react";
...
import { Policy, When } from "pundit";

export default function Landing() {
  const { user } = useAuth()
  const landingPolicy = new Policy();

  useEffect(() => {
    if(user) {
      landingPolicy.add("create", (user, record) => user.pioneer);
    }
  }, [user]);

  return(
    <When can="create" user={user} policy={landingPolicy} record={"landing"}>
      <div>
        <Link to="/create">Create</Link>
      </div>
    </When>
  );
}

It doesn't show me my link. Even if I replace user.pioneer with true

Maybe you see an issue with my setup. We can later improve README, so others will understand how to use it with React.

v0.1.0

Allow importing directly from pundit package

Currently we're including too much code in the package itself, including both dist and src directories. The way the node_modules subfolder is structured means that we cannot import from the pundit package directly.

  • An index.js should be included in the root of the package
  • We shouldn't include uncompiled TypeScript code in the package
  • import { Policy, When, PunditProvider } from 'pundit/dist/pundit.mjs' should become import { Policy, When, PunditProvider } from 'pundit'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.