Laravel 为用户和角色授权

问题描述 投票:0回答:1

我试图以这样的方式授权用户和角色,即每个用户在编辑时都无法访问另一个用户的 ID。 例如,如果我进入我的终端(会议)的编辑页面(在本例中)

http://localhost:8000/admin/termins/2/edit
无法访问我未在其中创建该终端的其他用户的任何会议 ID。 所以,当我手动输入
http://localhost:8000/admin/termins/1/edit
时,我无法访问它,显示403错误。

我当前的控制器:

 public function edit($id)
    {
        $termin = Termin::findOrFail($id);

        $this->authorize('edit', $termin);

Rest of code...

我的政策:

<?php


// app/Policies/TerminPolicy.php

namespace App\Policies;

use App\User;
use App\Termin;
use Illuminate\Auth\Access\HandlesAuthorization;

class TerminPolicy
{
    use HandlesAuthorization;

    public function edit(User $user, Termin $termin)
{
    \Log::info("User ID: {$user->id}, Created By ID: {$termin->created_by_id}");

    return $user->id === $termin->created_by_id;
}

    public function view(User $user, Termin $termin)
    {
        return $user->id === $termin->created_by_id;
    }
}

AuthServiceProvider:

<?php

namespace App\Providers;

use App\Policies\TerminPolicy;
use App\Role;
use App\User;
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 = [
        Termin::class => TerminPolicy::class,
    ];

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

        
        if (! app()->runningInConsole()) {
            $roles = Role::with('permission')->get();

            $permissionArray = [];
            
            foreach ($roles as $role) {
                foreach ($role->permission as $permission) {
                    $permissionArray[$permission->title][] = $role->id;
                }
            }

            foreach ($permissionArray as $title => $roles) {
                Gate::define($title, function (User $user) use ($roles) {
                    return count(array_intersect($user->role->pluck('id')->toArray(), $roles));
                });
            }

        }
    }
}

用户型号:

public function role()
    {
        return $this->belongsToMany(Role::class, 'role_user');
    }

Rest of code...

使用此代码,当从任何用户进入编辑页面时,我总是会收到错误

403 This action is unauthorized
。 但是,正如我所说,每个用户都必须编辑并只能看到自己的终端。

谢谢你。

php laravel permissions roles authorize
1个回答
0
投票

最简单的解决方案是在用户和终端之间创建关系,并通过 auth()->user() 访问终端。这样,如果 Termin 不属于用户,他们将无法访问它。

public function edit($id)
{
    $termin = auth()->user()->termin()->findOrFail($id);
    $this->authorize('edit', $termin);
    
    //..Rest of the code
}
© www.soinside.com 2019 - 2024. All rights reserved.