我想根據角色保護我的路線。 這就是我所做的,但我似乎無法得到它的工作。基於角色的路線保護的簡單方法Laravel 5.2
角色模型:
protected $table = 'roles';
protected $fillable = array(
'name', 'description'
);
public function users(){
return $this->belongsToMany('App\User', 'user_role', 'role_id', 'user_id');
}
作用遷移
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('name', 40);
$table->string('description', 255);
});
RoletableSeeder文件
Role::create([
'id' => 1,
'name' => 'Admin',
'description' => 'Admin User.'
]);
Role::create([
'id' => 2,
'name' => 'Vendor',
'description' => 'Vendor User.'
]);
Role::create([
'id' => 3,
'name' => 'User',
'description' => 'Simple User.'
]);
樣品路線:
Route::get('/admin/dashboard', [
'uses' => '[email protected]',
'as' => 'admin.dashboard',
'middleware' => ['auth', 'roles'],
'roles' => ['Admin']
]);
用戶模式:
protected $fillable = [
'email','username', 'password', 'confirmation_code'
];
protected $hidden = [
'password', 'remember_token',
];
public function orders() {
return $this->hasMany('App\Order');
}
public function roles(){
return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id');
}
public function hasRole($roles){
$this->have_role = $this->getUserRole();
if($this->have_role->name == 'Admin') {
return true;
}
if(is_array($roles)){
foreach($roles as $need_role){
if($this->checkIfUserHasRole($need_role)) {
return true;
}
}
} else{
return $this->checkIfUserHasRole($roles);
}
return false;
}
private function getUserRole(){
return $this->roles()->getResults();
}
private function checkIfUserHasRole($need_role){
return (strtolower($need_role)==strtolower($this->have_role->name)) ? true : false;
}
CheckRole.php文件,該文件是內部中間件:
<?php namespace App\Http\Middleware;
use Closure;
class CheckRole{
public function handle($request, Closure $next)
{
$roles = $this->getRequiredRoleForRoute($request->route());
if($request->user()->hasRole($roles) || !$roles){
return $next($request);
}
return response([
'error' => [
'code' => 'INSUFFICIENT_ROLE',
'description' => 'You are not authorized to access this resource.'
]
], 401);
}
private function getRequiredRoleForRoute($route)
{
$actions = $route->getAction();
return isset($actions['roles']) ? $actions['roles'] : null;
}
}
和最後我補充一條線到內核:
protected $routeMiddleware = [
...
'roles' => 'App\Http\Middleware\CheckRole',
];
沒有人有任何想法?或者更好/更簡單的方法來做到這一點?提前致謝!
謝謝您回答隊友。我會看看! – daino92
你看看嗎?如果有幫助,請接受答案 – lewis4u
抱歉不能早日回覆。我發現了另一個解決方案,我的問題,工作得很好。無論如何感謝你的努力。 – daino92