I'm using laravel 5.7 Gate and policies for site authorization. I have done it as follows but Page is forbidden even if user has permission in the roles table. in my system I have 3 main Roles as Super Admin, Admin,Guest. They have different permissions as attached image. Roles and Permissions. Please help me to fix this.
web.php
Route::get('/users', 'UserController@index')->name('users')->middleware('can:view-user');
AuthServiceProvide.php
public function boot()
{
$this->registerPolicies();
$this->registerPostPolicies();
}
public function registerPostPolicies()
{
Gate::define('view-user', function($user){
$user->hasAccess(['view-user']);
});
Gate::define('activate-user', function($user){
$user->hasAccess(['activate-user']);
});
}
Role Model
public function hasAccess(array $permissions)
{
foreach($permissions as $permission){
if($this->hasPermission($permission)){
return true;
echo("<script>console.log('PHP: ".$permissions."');</script>");
}
}
return false;
}
protected function hasPermission(string $permission){
$permissions = json_decode($this->permissions,true);
return $permissions[$permission]??false;
}
Roles and hasAction function in User Model
public function roles()
{
return $this->belongsToMany(Role::class, 'roles_users');
}
public function hasAccess(array $permissions)
{
foreach($this->roles as $role){
if($role->hasAccess($permissions)){
return true;
}
}
return false;
}
Role seeder
use Illuminate\Database\Seeder;
Use App\Role;
class rolerSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$super_admin = Role::create([
'name' => 'Super Admin',
'slug' => 'super admin',
'permissions' => json_encode([
'create-user' => true,
'update-user' => true,
'update-user' => true,
'activate-user' => true,
'view-user' => true,
]),
]);
$admin = Role::create([
'name' => 'Admin',
'slug' => 'admin',
'permissions' => json_encode([
'view-user' => true,
]),
]);
$guest = Role::create([
'name' => 'Guest',
'slug' => 'guest',
'permissions' => json_encode([
'view-user' => true,
]),
]);
}
}
And code is written as below tutorial link to tutorial
from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2FQdRat
via IFTTT
Aucun commentaire:
Enregistrer un commentaire