[英]Laravel 5 role based access control
我正在嘗試為我的應用程序提出一個高效靈活的RBAC解決方案。 我做了一點研究,並認為我創造了以下內容。
在我的用戶模型中,我有:
...
public function role() {
return $this->belongsToMany('App\Models\Role', 'user_roles');
}
public function hasRole($role) {
if($this->role->where('name', $role)->first())
return true;
}
...
以及用法示例:
Route::group(['middleware' => 'auth'], function () {
Route::get('/dashboard', function () {
if (Auth::user()->hasRole('Sales')) {
return view('dashboards/sales');
} else {
return 'Don\'t know where to send you :(';
}
});
});
權限分配給角色,但在上面的示例中未檢查權限。 然后將角色分配給用戶,並且用戶可以具有許多角色。
我的工作方式是否可擴展且有效的RBAC解決方案?
我已經制作了一些RBAC
應用程序,這取決於你所面臨的挑戰,例如
用戶有一個角色但你想要一個特定的用戶可以訪問某些區域,比如Posts
,現在用戶可以像主持人一樣編輯帖子。 在這種情況下,權限方法不僅僅適用於角色方法。
通過slug定義訪問權限,其他字段可以用作Super Admin的引用,或者具有諷刺意味的是編輯角色 ,從現在開始,編輯角色加上對新“區域”的權限。
public function up()
{
Schema::create('permissions', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('name');
$table->string('slug')->unique();
$table->string('description')->nullable();
$table->string('model')->nullable();
});
}
作為內容數據的示例,
$createUsersPermission = Permission::create([
'name' => 'Create permissions',
'slug' => 'create.permissions',
...
]);
以及用法示例:
if ($user->can('create.permissions') { // you can pass an id or slug
//
}
個人偏好 ,從未使用其他人建議的Zizaco Entrust ,但它的工作方式相同。 你也有級別的方法。
我做了一點點不同,我在UserRole中創建了hasRole,而不是用戶(不會影響太多,但根據代碼應該是這樣)。 所以這是我的路線:
Route::group(['middleware' => 'auth'], function () {
Route::get('/myProfile', function () {
if (App\UserRole::hasRole('ROLE_CUSTOMER',Auth::user())) {
return view('views/customer');
} else {
return 'Don\'t know where to send you :(';
}
}); });
Next Thing是我的UserRole中的方法。 我試着保持簡單:
public static function hasRole($authority,$user) {
$role = Role::where('authority',$authority)->first();
$userRole = UserRole::where('role_id',$role->id)
->where('user_id',$user->id)->first();
if($userRole){
return true;
}
}
我們尋找權限(ROLE_USER,ROLE_CUSTOMER等),$ user是從DB檢索的用戶對象。 其他一切按照您的問題運行/希望它有所幫助! 干杯!
由於laravel中沒有可用於基於角色的身份驗證的現成解決方案。 您可以創建定義應用程序可以具有的所有可能角色的自定義角色表,以及包含用戶和角色關聯的role_user表。
您可以在用戶模型下創建方法,以檢查用戶是否屬於特定角色。 利用該方法注冊新的中間件。 中間件可以附加到路由或控制器。
詳細演示在此鏈接https://www.5balloons.info/user-role-based-authentication-and-access-control-in-laravel/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.