Giter Site home page Giter Site logo

vyuldashev / nova-permission Goto Github PK

View Code? Open in Web Editor NEW
411.0 15.0 214.0 1.16 MB

A Laravel Nova tool for Spatie's laravel-permission library

Home Page: https://novapackages.com/packages/vyuldashev/nova-permission

PHP 100.00%
laravel nova spatie permission acl php secure

nova-permission's Introduction

A Laravel Nova tool for Spatie's laravel-permission library

Latest Version on Packagist Total Downloads

screenshot 1

Installation

You can install the package in to a Laravel app that uses Nova via composer:

composer require vyuldashev/nova-permission

Go through the Installation section in order to setup laravel-permission.

Next up, you must register the tool with Nova. This is typically done in the tools method of the NovaServiceProvider.

// in app/Providers/NovaServiceProvider.php

// ...

public function tools()
{
    return [
        // ...
        \Vyuldashev\NovaPermission\NovaPermissionTool::make(),
    ];
}

Next, add middleware to config/nova.php

// in config/nova.php
'middleware' => [
    // ...
    \Vyuldashev\NovaPermission\ForgetCachedPermissions::class,
],

Finally, add MorphToMany fields to you app/Nova/User resource:

// ...
use Laravel\Nova\Fields\MorphToMany;

public function fields(Request $request)
{
    return [
        // ...
        MorphToMany::make('Roles', 'roles', \Vyuldashev\NovaPermission\Role::class),
        MorphToMany::make('Permissions', 'permissions', \Vyuldashev\NovaPermission\Permission::class),
    ];
}

Or if you want to attach multiple permissions at once, use RoleBooleanGroup and PermissionBooleanGroup fields (requires at least Nova 2.6.0):

// ...
use Vyuldashev\NovaPermission\PermissionBooleanGroup;
use Vyuldashev\NovaPermission\RoleBooleanGroup;

public function fields(Request $request)
{
    return [
        // ...
        RoleBooleanGroup::make('Roles'),
        PermissionBooleanGroup::make('Permissions'),
    ];
}

If your User could have a single role at any given time, you can use RoleSelect field. This field will render a standard select where you can pick a single role from.

// ...
use Vyuldashev\NovaPermission\PermissionBooleanGroup;
use Vyuldashev\NovaPermission\RoleSelect;

public function fields(Request $request)
{
    return [
        // ...
        RoleSelect::make('Role', 'roles'),
    ];
}

Customization

If you want to use custom resource classes you can define them when you register a tool:

// in app/Providers/NovaServiceProvider.php

// ...

public function tools()
{
    return [
        // ...
        \Vyuldashev\NovaPermission\NovaPermissionTool::make()
            ->roleResource(CustomRole::class)
            ->permissionResource(CustomPermission::class),
    ];
}

If you want to show your roles and policies with a custom label, you can set $labelAttribute when instantiating your fields:

// ...
use Vyuldashev\NovaPermission\PermissionBooleanGroup;
use Vyuldashev\NovaPermission\RoleSelect;

public function fields(Request $request)
{
    return [
        // ...
        RoleBooleanGroup::make('Roles', 'roles', null, 'description'),
        PermissionBooleanGroup::make('Permissions', 'permissions', null, 'description'),
        RoleSelect::make('Role', 'roles', null, 'description'),
    ];
}

Define Policies

// in app/Providers/NovaServiceProvider.php

// ...

public function tools()
{
    return [
        // ...
        \Vyuldashev\NovaPermission\NovaPermissionTool::make()
            ->rolePolicy(RolePolicy::class)
            ->permissionPolicy(PermissionPolicy::class),
    ];
}

Usage

A new menu item called "Permissions & Roles" will appear in your Nova app after installing this package.

nova-permission's People

Contributors

astalpaert avatar dercodercom avatar dividy avatar dnwjn avatar drbyte avatar erhansogut avatar f-liva avatar fkeloks avatar gnanakeethan avatar igedeon avatar johnpaulmedina avatar letrams avatar lloricode avatar lucascolette avatar marcorivm avatar melvintehu avatar nalingia avatar nero2k avatar pabloguerrez avatar philipgunther avatar reflow1319 avatar rvxlab avatar sadeghpm avatar shalawani avatar siebeve avatar sp4r74cus avatar stylecibot avatar tyler-rehm avatar vincenzoraco avatar vyuldashev avatar

Stargazers

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

Watchers

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

nova-permission's Issues

attach{Model} methods not working

According to the manual:

https://nova.laravel.com/docs/1.0/resources/authorization.html#policies

In RolePolicy.php, all others methods are working.

These two methods are not working.

public function attachPermission(User $user, Role $role, Permission $permission)
{
    return false;
}    

public function attachUser(User $user, Role $role)
{
    return false;
}       

Any clue? Thank you.

Update

I wrote a attachRole method in UserPolicy.php. The button Attach Role on the User view page still appears, but, if I click on the button and try to attach a Role, the combo-box (select) is empty. When I change to return true, the roles are listed on the combo-box.

public function attachRole(User $user, User $user2, Role $role)
{
    return false;
}  

User edit page, permissions and roles not visible

The title says it all. When i edit a user there are extra fields.
image

image

My code is like the docs. Added it to the tools array in the serviceProivder. Added MorphToMany fields to the users fields. Added middleware in config file and still no luck.

Am i missing something here?

How to setup RolePolicy?

Originally posted by @vyuldashev in #27 (comment)

After php artisan make:policy RolePolicy --model=Role:

<?php

namespace App\Policies;

use App\User;
use Vyuldashev\NovaPermission\Role;
use Illuminate\Auth\Access\HandlesAuthorization;

class RolePolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view any company.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function viewAny(User $user)
    {
        return false;
    }

    /**
     * Determine whether the user can view the role.
     *
     * @param  \App\User  $user
     * @param  \App\Role  $role
     * @return mixed
     */
    public function view(User $user, Role $role)
    {
        //
    }

    ...

and update AuthServiceProvider:

<?php

namespace App\Providers;

use App\Company;
use Vyuldashev\NovaPermission\Role;
use Vyuldashev\NovaPermission\Permission;

use App\Policies\CompanyPolicy;
use App\Policies\RolePolicy;
use App\Policies\PermissionPolicy;

use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
        Company::class => CompanyPolicy::class,
        Role::class => RolePolicy::class,
        Permission::class => PermissionPolicy::class,
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        //
    }
}

There is no effect. View, edit and delete icons are still there:

roles

Did I get the vyuldashev Role model namespace wrong?

Undefined method when going to an individual user.

Hi everyone,

I'm getting an undefined method error when going to an individual user.

I've followed the spatie permissions installation, included the line in my Nova Provider. I can create and edit roles & permissions, but as soon as I view the details of a user I get these errors down below. Did anyone experience these errors as well? Or did I just miss a step?

schermafbeelding 2018-10-23 om 17 53 52

Happy to hear suggestions!

Users can give themselves any role?

My Nova package is open to admin and users and I am restricting access to resources via this package. However, I cannot restrict access to the page where I grant roles and permissions to users, which gives them access to this tool and thus, access to anything.

How can I restrict access to this tool to certain roles/permissions?

Permissions and Roles policies. How to?

On my app, only the Admin role should be able to see and change the Permissions and Roles via Nova.

I see that under vendor/vyuldashev/nova-permission/src there are Policy files included. I could set up my logic here, but this file will not be uploaded to my GitHub repo, and when I deploy or update the package, I will have to set up everything again. Is there something I am missing?

Thank you!

Class name must be a valid object or a string

I followed the tutorial to add the package in Nova. When I try to access the menu I get the message.

I looked at the logs, and the error happens in the following files:

Log: Class name must be a valid object or a string {"userId":1,"exception":"[object] (Symfony\Component\Debug\Exception\FatalThrowableError(code: 0)...

Permission:
/vendor/vyuldashev/nova-permission/src/Permission.php:97)
Role:
/vyuldashev/nova-permission/src/Role.php:91

composer.json:
"laravel/framework": "5.8.*",
"vyuldashev/nova-permission": "^1.4",
"spatie/laravel-permission": "^2.34",

App\Role not found

Hi all,

When adding:

            MorphToMany::make('Roles', 'roles', \Vyuldashev\NovaPermission\Role::class),
            MorphToMany::make('Permissions', 'permissions', \Vyuldashev\NovaPermission\Permission::class),

to my app\Nova\User.php class, I get the following error:
App\Role not found

Error when assigning role or permission to a user

Hi,

I get the following error when I try to assign a role or permission to a user. I am using postgreSQL with laravel 5.7:

[10:26:09] LOG.error: SQLSTATE[42703]: Undefined column: 7 ERROR: column "id" does not exist
LINE 1: ... "role_id", "model_type") values ($1, $2, $3) returning "id" ^ (SQL: insert into "model_has_roles" ("model_id", "role_id", "model_type")
values
(546794875465, 1, App\Models\User\User) returning "id") {"userId":546794875465,"email":"[email protected]","exception":{"errorInfo":["42703",7,"ERROR: column "id" does not exist\nLINE 1: ... "role_id", "model_type") values ($1, $2, $3) returning "id"\n ^"]}}

Cache not invalidated on attaching a role or permission to user

After attaching a role or permission to a user, the cache is not invalidated.

If you refer the assignRole or givePermissionTo methods on the HasRoles or HasPermissions traits with the spatie permission package, you can see that at the end of the method, the package invalidates the cache.

Now that Nova is attaching the role/permission, the cache is not invalidated and so any new role/permission attachment fails currently!

canSeeWhen() without wished effect

I added the NovaPermissionTool inside the NovaServiceProvider with:
NovaPermissionTool::make()->canSeeWhen('userAdmin')
only my own defined super admin can see the links now - but not the userAdmin.
without canSeeWhen() it's visible for all other backend users.

not able to attach anything when using postgres.

whenever i try to attach a permission to a role, a permission to a user or a role to user ( basically all use cases ) it throws an error collumn 'id' not found as below.

image

havent had the time to research the problem yet so this could also be a nova issue.
but i guess it sure helps to be aware the problem exists.

Consider renaming the tool

Hi,

thank you for creating this tool and using our permissions package to power it.

Something I don't like though is the use of our company name in the name of the tool. Some people might think that Spatie made this tool which is not the case.

Could you rename it to nova-permission or something similar? I'd be more than happy to add a link to this tool in the readme of spatie/laravel-permission.

Thanks!

Translations inside the /resources/vendor/ instead of vendor/../resources

Hi vyuldashev,

Very nice package! Congratulations for that :)

Still, I had to add a new translation folder for "pt" inside your vendor package and logically when I got your last update it got deleted.

I would suggest, if it's possible, to publish your translation files to /resources/vendor/vyuldashev/nova-permission and use a translation namespace to read them from there.

This way, each time there is a composer update, we don't lose our own translations.

Cheers and keep it up.
Bruno

Specify for v2 ?

Hi @vyuldashev
Thanks for this!

Would you be willing to update this to make it clear that this is built for v2 of the Spatie package?

The v3 release is likely to change some fields/features, and thus this NovaPackage would be broken. I think it would be helpful if it was clear that this was designed for v2.

Undefined index: Vyuldashev\NovaPermission\NovaPermissionTool

Hello,

Just fresh install on laravel 5.7 & Nova 1.3.1 i have this error :

Undefined index: Vyuldashev\NovaPermission\NovaPermissionTool (View: /data/www/resources/views/vendor/nova/layout.blade.php) (View: /data/www/resources/views/vendor/nova/layout.blade.php)

Thank you

Localization (spanish)

Hi, great package, I'm trying to make the translations for Spanish for my project but I don't know where to put those files, can someone gimme some advice?

How to modify Role model in vendor folder

I need to add the following logic to Role resource. Is it possible somehow?

Currently I have added this method to Role resource under vender folder

    public static function relatableQuery(NovaRequest $request, $query)
    {
        return $query->where('name', 'NOT LIKE', 'superadmin');
    }

install error

Has a error on install.
My laravel version is 5.7

> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi

In ToolServiceProvider.php line 33:

  Class 'Laravel\Nova\Nova' not found

Restrict users from showing sidebar

Hello.

How i can i restrict a user from accessing the sidebar and role/permission editing? Is this feature yet to be added?

I think this is a core functionality. Only certain users should be able to edit those.

Where is Roles and Permissions?

Hi,

I have gone through the installation steps, but only the Users resource shows up in the menu.

✝ ~/Development/nova  composer require vyuldashev/nova-permission
✝ ~/Development/nova  php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="migrations"
✝ ~/Development/nova  php artisan migrate
✝ ~/Development/nova  php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="config"

Add use HasRoles to App\User model.
Add new \Vyuldashev\NovaPermission\NovaPermissionTool(), to NovaServiceProvider
Add MorphToMany::make('Roles', 'roles', \Vyuldashev\NovaPermission\Role::class), MorphToMany::make('Permissions', 'permissions', \Vyuldashev\NovaPermission\Permission::class), to App\Nova\User::fields

Am I missing something?

Issue while installation: Class 'Gate' not found in ToolServiceProvider.php

I just ran the command

composer require vyuldashev/nova-permission

Then I got the following error:

In ToolServiceProvider.php line 30:

  Class 'Gate' not found


Script php artisan clear-compiled handling the post-update-cmd event returned with error code 1

My Plugin Versions in composer.json:

"barryvdh/laravel-ide-helper": "~2.4",
        "doctrine/dbal": "~2.8",
        "dompdf/dompdf": "~0.8",
        "filp/whoops": "~2.2",
        "guzzlehttp/guzzle": "~6.3",
        "guzzlehttp/psr7": "~1.4",
        "illuminate/support": "~5.6",
        "intervention/image": "~2.4",
        "laracasts/utilities": "~2.1",
       "laravel/framework": "~5.6",
        "laravel/socialite": "~3.0",
        "laravelcollective/html": "~5.6",
        "league/flysystem-aws-s3-v3": "~1.0",
        "maatwebsite/excel": "~2.1",
        "maxhoffmann/parsedown-laravel": "dev-master",
        "mcamara/laravel-localization": "~1.2",
        "mews/purifier": "~2.0",
        "milon/barcode": "~5.3",
        "nitmedia/wkhtml2pdf": "dev-master",
        "omnipay/common": "~3",
        "omnipay/dummy": "~3",
        "omnipay/paypal": "~3",
        "omnipay/stripe": "~3",
        "php-http/curl-client": "^1.7",
        "php-http/message": "^1.6",
        "predis/predis": "~1.1",
       "vinelab/http": "~1.5",
        "spatie/laravel-permission": "^2.29",
        "vyuldashev/nova-permission": "^1.4"

getPermissionTo not working until run php artisan cache:forget spatie.permission.cache

attach permission to role, and the User has the role.
i can see the user has all permission:
Text::make('name', function () use ($request) {
return $request->user()->getAllPermissions()->pluck('name');
}),
but i use $request->user()->hasPermissionTo('User_Edit'), it return false。
after i run php artisan cache:forget spatie.permission.cache 。it return true and work fun....

Nova 1.3.0 and SQL Column 'id' in where clause is ambiguous

I updated to nova 1.3.0 and login to nova, then on opening page, get an error exception.

 Illuminate \ Database \ QueryException (23000)
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select * from `users` left join `model_has_roles` on `model_has_roles`.`model_id` = `users`.`id` left join `roles` on `roles`.`id` = `model_has_roles`.`role_id` where `id` = 1 and `model_has_roles`.`model_type` = App\User and `roles`.`name` in (admin, sales) limit 1)
Previous exceptions

    SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (23000)
    SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (23000)

Permission names

Thanks, good nova module!

I see one trouble with it. If i want give readable names for permissions, i have long names in my code. And If i want give short names for better code - swears editor, because he not understand some things. Situation is aggravated when the Manager does not know english permissions names.

Maybe add a column "title" to display in the interface and a column "name" to use in the code?

ForgetCachedPermissions crashes on attach edition

When I'm tryin to edit a related model from BelongsToMany component. Not attach/detach but edit

#69 didn't explain the error oigin

Here's the exception:
exception: "Symfony\Component\Debug\Exception\FatalThrowableError"
file: "~/vendor/vyuldashev/nova-permission/src/ForgetCachedPermissions.php"
line: 28
message: "Class name must be a valid object or a string"

the line is:
$permissionKey = Nova::resourceForModel(app(PermissionRegistrar::class)->getPermissionClass())::uriKey();

Seems like cannot load the correct resource

Call to undefined function Moontoast\Math\bcadd()

I installed the nova-permission plugin in a new Laravel project with clean Nova installation.

When I try to assign role or permission to a user, I get the following error:

Call to undefined function Moontoast\Math\bcadd()

Any idea?

Customization is not supported

  1. How can I show it or set it when I add a column for the permission table?
  2. How can I add cards, filters or lenses?
  3. How can I update the properties? eq: title, search

User relations not work

After follow your installation guide, if i try to see user, i obtain following error:

"message": "Too few arguments to function Laravel\Nova\Resource::__construct(), 0 passed in E:\xampp72\htdocs\logvrp\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasRelationships.php on line 670 and exactly 1 expected".

This is my code inside App/Nova/User.php:

public function fields(Request $request)
{
return [

        ....
        MorphToMany::make('Roles', 'roles', \Vyuldashev\NovaPermission\Role::class),
        MorphToMany::make('Permissions', 'permissions', \Vyuldashev\NovaPermission\Permission::class),
        ....
    ];
}

How can solve?

Permissions list

On view user to see permissions from role and direct permissions?

// Direct permissions
$user->getDirectPermissions() // Or $user->permissions;

// Permissions inherited from the user's roles
$user->getPermissionsViaRoles();

// All permissions which apply on the user (inherited and direct)
$user->getAllPermissions();

Default RolePolicy overriding my own RolePolicy

The default "allow all" RolePolicy included in this package in 7a1fdfd is overriding my own RolePolicy, and allowing unprivileged users to assign roles they aren't authorized to assign. I assume the same issue exist for PermissionPolicy, though I haven't tested that.

One way to fix it is to simply move the gate registrations inside the empty Nova::serving call in the oddly named ToolServiceProvider. This is still limiting, however, as even in Nova one may wish to customize the policy and prevent certain roles/permissions from being assigned, removed, etc.

I'm not clear on why these policies exist at all? My understanding is that, in the absence of a policy, by default Nova will allow all actions on a resource. It seems like it would be much better to simply remove the policies and allow users to create their own if they require them.

Use the new nova $group

Just a cosmetic improvement, make use of the new nova groups to group the Permission and Roles resources, instead of the current sidebar label

public static $group = 'Users';

Feature request -> show Users

Hi @ALL

it would be cool if can click on roles or permissions and than i can the which user have this role or permission.

I know this table can be huge. But we have #pagination.

Thanks

Overriding package language

Could you update the documentation to make overriding language clear for future users? I mean something like this:

Override language

Put your translations in /resources/lang/vendor/nova-permission-tool, to get you custom translations to work.

(Language files in /resources/lang/vendor/nova-permission will not work)

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.