【发布时间】:2021-06-19 10:34:42
【问题描述】:
我制作了一个 Laravel 8 application(链接到 GitHub 存储库),需要用户注册和登录。
我目前正在添加用户角色和权限。我有 3 个角色(用户类型):管理员、作者和成员。每种类型的用户都应该有权访问仪表板的某个部分。
用户表:
角色表:
在routes\web.php 我有:
Route::get('/', [HomepageController::class, 'index'])->name('homepage');
Auth::routes();
Route::group(['middleware' => ['auth']], function() {
Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
Route::get('/dashboard/profile', [UserProfileController::class, 'index'])->name('profile');
Route::match(['get', 'post'],'/dashboard/profile/update', [UserProfileController::class, 'update'])->name('profile.update');
Route::post('/dashboard/profile/deleteavatar/{id}/{fileName}', [UserProfileController::class, 'deleteavatar'])->name('profile.deleteavatar');
//User roles
Route::get('/dashboard/author', [AuthorController::class, 'index']);
});
在 User 模型中 (app\Models\User.php) 我有:
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'role_id',
'username',
'first_name',
'last_name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function roles() {
return $this->belongsToMany(Role::class);
}
public function users()
{
return $this
->belongsToMany('App\User');
}
public function authorizeRoles($roles)
{
if ($this->hasAnyRole($roles)) {
return true;
}
abort(401, 'This action is unauthorized.');
}
public function hasAnyRole($roles)
{
if (is_array($roles)) {
foreach ($roles as $role) {
if ($this->hasRole($role)) {
return true;
}
}
} else {
if ($this->hasRole($roles)) {
return true;
}
}
return false;
}
public function hasRole($role)
{
if ($this->roles()->where('name', $role)->first()) {
return true;
}
return false;
}
}
在AuthorController(Controllers\Dashboard\AuthorController.php)中
class AuthorController extends Controller
{
public function __construct()
{
$this->middleware('auth');
$this->middleware('role:ROLE_Author');
}
public function index()
{
return view('dasboard.author');
}
}
正如 CheckRole 中间件所示,如果用户未授权,则消息应为“此操作未授权”:
class CheckRole
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next, $role)
{
if (!$request->user()->hasRole($role)) {
abort(401, 'This action is unauthorized.');
}
return $next($request);
}
}
问题
由于我无法找到的原因,尝试将 作者 重定向到它的管理面板部分会导致 403 错误:
User does not have any of the necessary access rights.
问题
我做错了什么?
【问题讨论】:
-
能否请您展示带有角色的表格?
-
@Dmitry 我不想使用任何包。
-
@RazvanZamfir 你能把更新的代码添加到 github repo 和 sql 文件的数据吗
-
@JohnLobo 在 repo 的 user_roles 分支上,有所有最新的代码和 sql 导出。