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

adonis-lucid-permission

v1.1.3

Published

Addon for Associate models with roles and permissions AdonisJS Lucid ORM

Downloads

90

Readme

adonis-lucid-permission

Source Code Npm Node Version Support Latest Version Software License Build Status Total Downloads

Library for associate adonisjs lucid ORM models with roles and permissions

Requisites

Requires @adonisjs/core >= 6.5.0 and @adonisjs/lucid >= 20.5.1;

Installation

NPM

npm i adonis-lucid-permission

YARN

yarn add adonis-lucid-permission

PNPM

pnpm add adonis-lucid-permission

After install call configure:

node ace configure adonis-lucid-permission

Usage

After install and configure, apply HasAuthorizable to a Model

import { compose } from '@adonisjs/core/helpers';
import { BaseModel } from '@adonisjs/lucid/orm';
import { withAuthorizable } from 'adonis-lucid-permission';

const HasAuthorizable = withAuthorizable({
  rolesPivotTable: 'user_has_roles',
  permissionsPivotTable: 'user_has_permissions',
});

export default class User extends compose(BaseModel, HasAuthorizable) {
  // ...columns and props
}

And create the pivot-table migration file with:

node ace permissions:pivot-table

And ready. User model can all methods for associate roles and permissions

Role and Permission model

Roles and Permissions are just Lucid models that can be directly managed like any other model

import { Permission } from 'adonis-lucid-permission/services/permission';
import { Role } from 'adonis-lucid-permission/services/role';

const role = await Role.create({ name: 'writer' });
const permission = await Permission.create({ name: 'edit-posts' });

Managing permissions

You can manage permissions for roles and models using the same methods

// Assigning permissions
await role.givePermissionTo('do-things');

// Removing permissions
await user.revokePermissionTo('do-things');

// Synchronize permissions
await role.syncPermissions('do-things', 'try-things');

Checking for permissions

// Checking permissions
await role.hasPermissionTo('do-things'); // returns true or false
await user.checkPermissionTo('do-things'); // returns true or throws

// Returns true if the model has any of the given permissions
await role.hasAnyPermission('do-things', 'try-things');

// Returns true if the model has all of the given permissions
await user.hasAllPermissions('do-things', 'try-things');

// Returns all permission names
await user.getPermissionNames();

Managing Roles

You can manage roles for models using the withAuthorizable mixin

// Assign role
await user.assignRole('admin');

// Revoke role
await user.revokeRole('admin');

// Synchronize roles
await user.syncRoles('admin', 'writer', role);

Checking for roles

Generally you should be checking against permissions vs checking for roles, but if you want to check against a role instead use one of the following methods

await user.hasRole('admin');

// Returns true if the model has any of the given permissions
await role.hasAnyRoles('admin', 'writer');

// Returns true if the model has all of the given permissions
await user.hasAllRoles('admin', 'writer');

// Returns all role names
await user.getRoleNames();

Accessing direct and role permissions

// Check if the model has the permission directly
await user.hasDirectPermission('do-things');

// Check if the model has the permission via role
await user.hasPermissionViaRole('do-things');

// Get all direct permissions
await user.getDirectPermissions();

// Get all permissions via roles
await user.getPermissionsViaRoles();

// Get all permissions combined
await user.getAllPermissions();

// Check if the model has the permission directly or via role
await user.withPermissionTo('do-things');

// Returns true if the model has any of the given permissions directly or via role
await user.canAnyPermission('do-things', 'try-things');

Protect routes with middlewares

After version 1.1.0 added middlewares for protect routes using roles, permissions, or roles and permissions. Please check your start/kernel.ts file and middleware router named register like:

export const middleware = router.named({
  //...
  role: () => import('adonis-lucid-permission/role_middleware'),
  permission: () => import('adonis-lucid-permission/permission_middleware'),
  roleOrPermission: () => import('adonis-lucid-permission/role_or_permission_middleware'),
  //...
});

And in your router file, use after middleware.auth(), example:

import router from '@adonisjs/core/services/router';
import { middleware } from '#start/kernel';

router
  .post('projects', async ({ auth }) => {
    console.log(auth.user); // User
  })
  .use([
    middleware.auth(),
    middleware.permission({ permissions: ['publish projects', 'edit projects'] }),
  ]);

router
  .post('posts', async ({ auth }) => {
    console.log(auth.user); // User
  })
  .use([middleware.auth(), middleware.role({ roles: ['editor', 'administrator', 'publisher'] })]);

router
  .post('projects', async ({ auth }) => {
    console.log(auth.user); // User
  })
  .use([
    middleware.auth(),
    middleware.roleOrPermission({ roleOrPermission: ['administrator', 'publish projects'] }),
  ]);

Copyright and License

The adonis-lucid-permission library is licensed for use under the MIT License (MIT). Please see LICENSE for more information.