Linking Spatie Permissions to Backpack UI show/hide

我只是一个虾纸丫 提交于 2021-01-05 07:08:01

问题


New to Laravel and Backpack here, but trying to integrate the PermissionManager with Backpack. I've got it all installed and showing the Users/Permissions/Roles in the UI, however I was unable to figure out how to show/hide buttons and functionality in the Backpack UI based on those permissions. I'm hoping someone can comment on the solution I came up with or if there is something else that should be used.

Note, this is really about showing and hiding UI elements, not the actual policies (which I am handling separately using the "can" functions in my controllers, routes, etc.)

My solution:

In my EntityCrudController, I use a trait I made called CrudPermissionsLink, then in setup() I call the function I made:

public function setup()
{
    CRUD::setModel(\App\Models\ProgramUnit::class);
    CRUD::setRoute(config('backpack.base.route_prefix') . '/programunit');
    CRUD::setEntityNameStrings('programunit', 'program_units');

    $this->linkPermissions();
}

Then in my trait, I have it simply defined based on a naming convention, splitting on dashes.

<?php

namespace App\Http\Traits;
use Illuminate\Support\Facades\Auth;

/**
 * Properties and methods used by the CrudPermissionsLink trait.
 */
trait CrudPermissionsLink
{
    /**
     * Remove access to all known operations by default, reset them based on permissions defined in the format 
     * entity_name-operation
     *
     */
    public function linkPermissions()
    {
        $ui_ops = ['list','create','delete','update'];
        $user = Auth::user();
        $this->crud->denyAccess($ui_ops);
        foreach($ui_ops as $op){
            $perm_name = "{$this->crud->entity_name}-{$op}";
            if($user->can($perm_name)){
                $this->crud->allowAccess($op);
            }
        }
    }
}

回答1:


What you have will work. That said, I recently created a similar solution for my apps. For my solution, I used an abstract Crud controller as below and all my specific crud controllers extend this class:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Gate;
use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
use Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
use Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation;
use Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation;
use Backpack\CRUD\app\Http\Controllers\CrudController as BaseCrudController;

abstract class CrudController extends BaseCrudController
{
    use ListOperation, DeleteOperation;
    use CreateOperation { store as traitStore; }
    use UpdateOperation { update as traitUpdate; }

    /**
     * All possible CRUD "actions"
     */
    public const CRUD_ACTION_CREATE    = 'create';
    public const CRUD_ACTION_LIST      = 'list'; // synonymous with "read"
    public const CRUD_ACTION_UPDATE    = 'update';
    public const CRUD_ACTION_DELETE    = 'delete';
    public const CRUD_ACTION_REORDER   = 'reorder';
    public const CRUD_ACTION_REVISIONS = 'revisions';

    /**
     * @var array An array of all possible CRUD "actions"
     */
    public const ACTIONS = [
        self::CRUD_ACTION_CREATE,
        self::CRUD_ACTION_LIST,
        self::CRUD_ACTION_UPDATE,
        self::CRUD_ACTION_DELETE,
        self::CRUD_ACTION_REORDER,
        self::CRUD_ACTION_REVISIONS,
    ];

    /**
     * @var array An array of all CRUD "actions" that are not allowed for this resource
     * Add any of the CRUD_ACTION_X constants to this array to prevent users accessing
     * those actions for the given resource
     */
    public $_prohibitedActions = [
        self::CRUD_ACTION_REORDER,   // not currently using this feature
        self::CRUD_ACTION_REVISIONS, // not currently using this feature
    ];

    /**
     * Protect the operations of the crud controller from access by users without the proper
     * permissions
     *
     * To give a user access to the operations of a CRUD page give that user the permissions below
     * (where X is the name of the table the CRUD page works with)
     *
     * `X.read`      permission: users can view the CRUD page and its records
     * `X.create`    permission: users can create records on the CRUD page
     * `X.update`    permission: users can update records on the CRUD page
     * `X.delete`    permission: users can delete records on the CRUD page
     * `X.reorder`   permission: users can reorder records on the CRUD page
     * `X.revisions` permission: users can manage record revisions on the CRUD page
     *
     * @return void
     */
    public function setupAccess(): void
    {
        // get the name of the table the crud operates on
        $table = null;
        if (isset($this->crud->model) && $this->crud->model instanceof Model) {
            /** @var Model $this->crud->Model; */
            $table = $this->crud->model->getTable();
        }
        // for each action, check if the user has permissions
        // to perform that action and enforce the result
        foreach (self::ACTIONS as $action) {
            $requiredPermission = "$table.$action";
            // If our model has no $table property set deny all access to this CRUD
            if ($table && !$this->isProhibitedAction($action) && Gate::check($requiredPermission)) {
                $this->crud->allowAccess($action);
                continue;
            }
            $this->crud->denyAccess($action);
        }
    }

    /**
     * Check if the given action is allowed for this resource
     * @param string $action One of the CRUD_ACTION_X constants
     * @return bool
     */
    public function isProhibitedAction($action): bool
    {
        return in_array($action, $this->_prohibitedActions, true);
    }

    /**
     * Setup the CRUD page
     * @throws \Exception
     */
    public function setup(): void
    {
        $this->setupAccess();
    }

}


来源:https://stackoverflow.com/questions/63395129/linking-spatie-permissions-to-backpack-ui-show-hide

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!