GithubHelp home page GithubHelp logo

pktharindu / nova-permissions Goto Github PK

View Code? Open in Web Editor NEW
133.0 5.0 19.0 4.39 MB

Add Permissions based authorization for your Nova installation via User-based Roles and Permissions. Roles are defined in the database whereas Permissions are defined in the code base.

Home Page: https://www.pktharindu.com/projects/nova-permissions

License: MIT License

PHP 65.72% Vue 29.55% JavaScript 4.73%
laravel nova tool acl roles permissions access-control gates policies authentication

nova-permissions's Introduction

banner that says Hi, I am Tharindu - A seasoned full-stack web developer alongside a pretty picture of Tharindu

Nice to meet you! I'm a web developer from Sri Lanaka who care deeply about creating world-class, useful and beautiful products that help people and make a difference. I enjoy building everything from small business sites to rich interactive web apps. I spend my evenings working on side projects, contributing to open-source and learning as much as I can. Laravel and Vue.js are my go-to frameworks, and I'm pretty handy with them. But I have skills in a variety of other tools and frameworks as well.

Profile Views Twitter Badge Linkedin Badge Codewars

nova-permissions's People

Contributors

dependabot[bot] avatar dmason30 avatar dormadekhin avatar milewski avatar pktharindu avatar ramonnitsnets 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

nova-permissions's Issues

Transaltable group name

Group name of resource is not translatable

public static function group()
{
    return config('nova-permissions.role_resource_group', 'Other');
}

this should be replaced with

public static function group()
{
    return __(config('nova-permissions.role_resource_group', 'Other'));
}

in config file translator does not exist.

NovaPermissions is not defined

Prerequisites

  • Able to reproduce the behaviour outside of your code, the problem is isolated to Nova Permissions.
  • Checked that your issue isn't already filed.
  • Checked if no PR was submitted that fixes this problem.

Versions

  • PHP version: 8.1.3
  • Laravel version: 8.40
  • Nova version: 3.31.0
  • Package version: #.#.#

Description

Steps to Reproduce

The problem is in the tools, can load the NovaPermissions component

image

unknown permission

Hello i'm using version ^2.1 with php7
and i keep getting unknown permission whenever i try to update a role

Not work with the last version of laravel/nova

Prerequisites

  • Able to reproduce the behaviour outside of your code, the problem is isolated to Nova Permissions.
  • Checked that your issue isn't already filed.
  • Checked if no PR was submitted that fixes this problem.

Versions

  • PHP version: 8.1.11
  • Laravel version: 9.35.1
  • Nova version: 4.15.2

Description

I cannot get the package to work with the latest versions of laravel and nova.
I followed the instructions but I can't get the resource to appear

Setting permission shouldn't save a Role

$this->save();

Hi,

let's assume I extend your Role model to be able to use a Factory like so:

app/Models/Role.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

class Role extends \Pktharindu\NovaPermissions\Role
{
    use HasFactory;
}

database/factories/RoleFactory.php

<?php

namespace Database\Factories;

use App\Models\Role;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class RoleFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Role::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $slug = str_replace('.', '', $this->faker->text(rand(50, 100))),
            'slug' => Str::slug($slug),
            'permissions' => [],
        ];
    }
}

routes/web.php

Route::get('/test', function () {
    Artisan::call('migrate:fresh --force');

    $role = App\Models\Role::where('name', 'test')->first();
    dump($role);

    App\Models\Role::factory()->make(['name' => 'test']);

    $role = App\Models\Role::where('name', 'test')->firstOrFail();

    dump($role->name);
});

The expected behavior would be to fail here because make should not persist the record. If the Role does not exist at the time of setting permissions we should not just save the model?

Jumbled layout with longer permission names

Problem
It seems that the responsive layout gets a bit jumbled when some of the permissions have longer names:
image

Cause
I think use of flex-auto on each permission group block is the issue.

Solution
If I change this to flex: 1 1 300px it displays nicely for me on all screen sizes with some wrapping on the smaller screens which is fine:

Details - Screens

Desktop
image

Tablet
image

Mobile
image

Form - Screens

Desktop
image

Tablet
image

Mobile
image

I am willing to PR a change once discussed. If you are not willing to change the class then please consider making the views publishable.

Create Policy for Role?

I want to limit only Administrator Role can mange Role. So I created a Policy for Role

namespace App\Policies;

use Pktharindu\Nova\Permissions\Role;
use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class RolePolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view any roles.
     *
     * @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)
    {
        //
    }

but all users have access to Role Resource. How to make a Policy for Role?

Teams feature

Are you thinking about creating a teams feature?

Basically, a user can create a team. Invite other users to that team and that team can access only some specific things?

can't update role

Hello ,
when i try to update a role i get this error

Unknown permission
C:\xampp\htdocs\qcm\vendor\laravel\framework\src\Illuminate\Foundation\Application.php#1043

any help

Enable translations by default

Hi there, nice package that totally fits our needs.

Do you think of enabling more translations by default?

The following parts are currently missing the helper:

  • for the Role Resource label and singularLabel overlooked, this already exists ๐Ÿ™ˆ
  • when population the permission checkboxes for group, display_name and description

superadmin edit role bug

Everything is working fine (great work!) except for this one update issue for a role called superadmin. The edit role is working for any role that I define but when I try to update a role which is named 'superadmin', it redirects me to 403 error page like this with an error message showing: There was a problem submitting the form: Forbidden.

In the RolePolicy.php , i have the update method defined like this

public function update(User $user, Role $role)
{
        if ($user->hasPermissionTo('create roles')) {
            return true;
        }
}

The boot function in the AuthServiceProvider.php:

public function boot()
    {
        $this->registerPolicies();

        foreach (config('nova-permissions.permissions') as $key => $permissions) {
            Gate::define($key, function (User $user) use ($key) {
                if ($this->nobodyHasAccess($key)) {
                    return true;
                }

                return $user->hasPermissionTo($key);
            });
        }
    }

image

Am I doing something wrong here? help!

Question: how to apply Policies to BelongsToMany resources?

Hello,

I'm looking for a way to apply the permissions on the resource's BelongsToMany section. To be more specific, I want to apply a Policy to a BelongsToMany resource.

For example:

  • in App\Nova\User resource I have a BelongsToMany field, like this:
    BelongsToMany::make('Roles', 'roles', Role::class)
  • in App\Providers\AuthServiceProvider, I have set the policy:
    'Pktharindu\NovaPermissions\Role' => RolePolicy::class

Having this BelongsToMany resource, when I view a User, I have a section with the assigned roles, and actions (view/edit/delete) for each role.

2.png

Please notice that when I browse the Roles resource, the RolePolicy is properly used.
1.png

Default Users and Roles permission not workin.

Hi,

Great package overall.

I installed and used it as per documented. But the default user and roles permissions doesnt seem to work. I tested creating new resource policy and added the permission on the config which worked. I created a different role and assigned it to a different user as well. Unchecked all permissions on Users and Roles but I can still manipulate the Users and Roles resources.

Have I missed something regarding about this?

Defining Super Admin

Took me a little while to figure this out, but it was pretty simple in the end so I figured I'd share. Basically add the following to the boot method of your AuthServiceProvider.php file.

Gate::before(function ($user, $ability) {
    return $user->is_admin == 1 ? true : null;
});

You can also replace the is_admin with a permission check from this package.

Gate::before(function ($user, $ability) {
    return $user->hasPermissionTo('super admin') ? true : null;
});

Of course this requires you to also have a role with that ability assigned, so be sure to do that.

403 code when attemp to update a role.

I had used this library without problems, until I had to execute the command php artisan migrate: refresh, in order to test my implementation with docker, for this I wrote a seeder for the default roles, everything up to here turns out very well, the problem is that when I want to edit the roles, laravel sends me a screen with the 403 error, specifically when I click the update button

My envoiroment
Ubuntu 20.04
PHP 7.3
Docker version 19.03.13, build 4484c46d9d
Mysql 8.0
Laravel Nova 3.10
Laravel 7.3.28

Config table names not supposed correctly

First off, you should edit your Readme to publish and edit the config before publishing migrations and migrating.

Secondly, you have the configuration to specify custom table names, but this doesn't seem to be supported in your models and migrations. Changing which User model / Resource you're using, plus the tables is all good, but some people might have something not named User, but maybe PublicUser or BackendUser. You should reflect that in both your migrations and code either by adding it to your config, so people can specify the foreign keys or in our code. Same goes for the role and role_user. Some might have it named Team or Group.

I really like the whole feel and look of the package, but making these things customizable would make it even better than it already is.

I for one have a database where backend_user and backend_group is a thing in my DB and I can't change that.

Extend App\Nova\Resource

I see that "Pktharindu\NovaPermissions\Role" extends "Laravel\Nova\Resource".

Wouldn't it be better to extend "App\Nova\Resource" instead. This way we could create methods to be inherited by all child resources.

For example I'd want to be able to ONLY do this:

namespace App\Nova;

abstract class Resource extends App\Nova\Resource
{
    public function Breadcrumbs() {};
    public function IndexQuery() {};
    public function AbbreviateLabel() {};
}

But at the moment, I'm having to create traits to ensure all resources can inherit; like this:

namespace App\Nova;

abstract class Resource extends NovaResource
{
    use Breadcrumbs;
    use SearchesRelations;
    use AbbreviateLabel;
}
namespace App\Nova;

use Pktharindu\NovaPermissions\Nova\Role as RoleResource;

class Role extends RoleResource
{
    use Breadcrumbs;
    use OrderIndexQueryByName;
    use AbbreviateLabel;
}

After installation Target class [App\Policies\RolePolicy] does not exist

Prerequisites

  • Able to reproduce the behaviour outside of your code, the problem is isolated to Nova Permissions.
  • Checked that your issue isn't already filed.
  • Checked if no PR was submitted that fixes this problem.

Versions

  • PHP version: 7.4.20
  • Laravel version: 7.30.4
  • Nova version: 3.19.1
  • Package version: ^2.1

Description

I have installed the module following the whole procedure but once I reload the page the following error appears:

Illuminate\Contracts\Container\BindingResolutionException
Target class [App\Policies\RolePolicy] does not exist. (View: /var/www/nova/resources/views/layout.blade.php)

Screenshot 2021-06-25 at 16 13 54

I suppose the error is in

namespace App\Providers;

use App\Policies\UserPolicy;
use App\User;
use App\Models\InfoWeb\Customer as InfoWebCustomer;
use App\Policies\InfoWebCustomerPolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Pktharindu\NovaPermissions\Traits\ValidatesPermissions;

class AuthServiceProvider extends ServiceProvider
{
    use ValidatesPermissions;
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        User::class => UserPolicy::class,
        InfoWebCustomer::class => InfoWebCustomerPolicy::class,
        \Pktharindu\NovaPermissions\Role::class => \App\Policies\RolePolicy::class,
    ];

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

        foreach (config('nova-permissions.permissions') as $key => $permissions) {
            Gate::define($key, function (User $user) use ($key) {
                if ($this->nobodyHasAccess($key)) {
                    return true;
                }

                return $user->hasPermissionTo($key);
            });
        }
    }
}

\Pktharindu\NovaPermissions\Role::class => \App\Policies\RolePolicy::class, -> the `RolePolicy::classics missing

Steps to Reproduce

Install following the procedure

Expected behavior:

No errors after following the installation guide

Actual behavior:

Missing App\Policies\RolePolicy

Additional Information

Different Users Table

Hi!

our users table is named admin_users and our model is named AdminUsers. When I set the user_model and user_resource in the nova-permission config I've got errors when I'm using the hasPermissionTo() in the policies.

I've got a sql error until I have changed the table role_user.user_id to .admin_user_id. But when I want to view the roles the query searches for 'user_id'.

The "error" is in the src/Role.php line 34. There the field 'user_id' is hardcoded. When I change this to 'admin_user_id' everything works again.

Is it possible to make this configurable or is there any other way to not mess with the source?

Thanks!

Regards, Ingo

Cannot attach user to role

Hello

I am trying to attach user to role or role to user, but got this error in console:

vendor.js?id=8337884d0b7b132299df:1 TypeError: Cannot read property 'attribute' of null at a.clearSelection (vendor.js?id=8337884d0b7b132299df:1) at a.initializeComponent (app.js?id=9315b56b5fde09a69c70:1) at a.mounted (app.js?id=9315b56b5fde09a69c70:1) at It (vendor.js?id=8337884d0b7b132299df:1) at en (vendor.js?id=8337884d0b7b132299df:1) at insert (vendor.js?id=8337884d0b7b132299df:1) at It (vendor.js?id=8337884d0b7b132299df:1) at Object.n [as insert] (vendor.js?id=8337884d0b7b132299df:1) at x (vendor.js?id=8337884d0b7b132299df:1) at a.__patch__ (vendor.js?id=8337884d0b7b132299df:1)

Can you help me ?

Question about AuthServiceProvider

Hi, and thanks for this package.

I don't understand the purpose of this code in AuthServiceProvier:

foreach (config('nova-permissions.permissions') as $key => $permissions) {
    Gate::define($key, function (User $user) use ($key) {
        if ($this->nobodyHasAccess($key)) {
            return true;
        }

        return $user->hasPermissionTo($key);
    });
}

It never seems to be called, and nobodyHasAccess method use a Permission model but your package don't have a permission table...

Could you explain this part please ?

Access to only own user Profile

Hi,

thanks for your package. Works great.

I wanted to share some things which can help other users and maybe parts can be taken into documentation?

I wanted to create an admin role and authenticated user role.
I do no want the standard user to view the user resource. This can be achieved by adding the following to the app\nova\user.php:

/**
* Indicates if the resource should be displayed in the sidebar.
*
* @var bool
*/
public static function availableForNavigation(Request $request)
{
    return $request->user()->hasPermissionTo('view users');
}

This way, only roles with permission 'view users' can see the resource in the menu. But this doesn't remove permission to view/edit users by directly going to the url.

I created a UserPolicy with a distinction between 2 view permissions:

  • Manage userprofile : can only view/edit own user profile.

  • view users : given to admin user, can view/edit all the users.

This is the code from the UserPolicy:

<?php

namespace App\Policies;

use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Http\Request;

class UserPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view any models.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function viewAny(User $user)
    {
        if ($user->hasPermissionTo('manage userprofile') && $user->id == request()->resourceId ) {
            return true;
        }
        return $user->hasPermissionTo('view users');
    }

    /**
     * Determine whether the user can view the model.
     *
     * @param  \App\User  $user
     * @param  \App\User  $model
     * @return mixed
     */
    public function view(User $user, User $model)
    {
        if ($user->hasPermissionTo('manage userprofile') && $user->id == request()->resourceId) {
            return true;
        }
        return $user->hasPermissionTo('view users');
    }

    /**
     * Determine whether the user can create models.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function create(User $user)
    {
        return $user->hasPermissionTo('create users');
    }

    /**
     * Determine whether the user can update the model.
     *
     * @param  \App\User  $user
     * @param  \App\User  $model
     * @return mixed
     */
    public function update(User $user, User $model)
    {
        if ($user->hasPermissionTo('manage userprofile') && $user->id == request()->resourceId) {
            return true;
        }
        return $user->hasPermissionTo('view users');
    }

    /**
     * Determine whether the user can delete the model.
     *
     * @param  \App\User  $user
     * @param  \App\User  $model
     * @return mixed
     */
    public function delete(User $user, User $model)
    {
        return $user->hasPermissionTo('delete users');
    }

    /**
     * Determine whether the user can restore the model.
     *
     * @param  \App\User  $user
     * @param  \App\User  $model
     * @return mixed
     */
    public function restore(User $user, User $model)
    {
        return $user->hasPermissionTo('delete users');
    }

    /**
     * Determine whether the user can permanently delete the model.
     *
     * @param  \App\User  $user
     * @param  \App\User  $model
     * @return mixed
     */
    public function forceDelete(User $user, User $model)
    {
        return $user->hasPermissionTo('delete users');
    }
}

Maybe this helps some people, I saw a lot of questions regarding this when searching how to do this. There might be a better way to achieve this, but this works for me.

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.