2017-03-03 68 views
2

我使用的是基於Laravel的OctoberCMS用OctoberCMS Laravel檢查後端用戶是否屬於Group?

我有一個後端用戶,Mattownersadministrators

如何檢查用戶是否屬於特定組以允許身份驗證?

我被告知需要傳遞一個組對象,但我不知道那是什麼。

use Auth; 
use BackendAuth; 
use Backend\Models\User; 

if (BackendAuth::check()) { 

    // get current backend user 
    $backend_user = BackendAuth::getUser(); 

    // get current backend user's groups 
    $backend_user_groups = Backend::getUser()->groups; 

    // authenticate 
    if ($backend_user->inGroup('administrators') { 

    } 
} 

錯誤

public function inGroup($group) 
Call to a member function getKey() on string 

另一種方法我試過

if (User::inGroup('administrators') { 

} 

錯誤

Non-static method October\Rain\Auth\Models\User::inGroup() should not be called statically

文檔

https://octobercms.com/docs/backend/users

https://github.com/octobercms/library/blob/master/src/Auth/Models/User.php

+0

有沒有理由檢查一個組,而不是權限? – dragontree

+0

@dragontree在OctoberCMS中,我製作了具有一組權限的後端用戶組。我向管理員或版主添加用戶,然後在php中檢查當前用戶的組以允許訪問功能。我應該以不同的方式去做嗎? –

+1

你應該使用'hasAccess'或'hasPermission()'函數。 其記錄在這裏:https://octobercms.com/docs/backend/users#features – dragontree

回答

4

可能有一些這方面的輔助功能,但你也可以使用這個:

$backend_user->groups()->whereName('administrators')->exists(); 
+0

我認爲它可能正在工作,我正在進行一些測試,我會盡快與您聯繫。 –

+0

這適用於檢測組。我將不得不再次執行權限,謝謝。 –

1

您還可以擴展後端用戶模型,並添加一個輔助方法,它檢查角色。不要在你的插件的boot()方法如下:

use Backend\Models\User as BackendUser; 

public function boot() 
{ 
    BackendUser::extend(function($model) { 

     $model->addDynamicMethod('hasRole', function($role) use ($model) { 
      return $model->groups()->whereName($role)->exists(); 
     }); 

     $model->addDynamicMethod('isAdmin', function() use ($model) { 
      return $model->hasRole('administrators'); 
     }); 

    } 
} 
1

我覺得首先你應該嘗試做permissions part

公共職能內羣($組)

打電話之前瞭解的錯誤到一個成員函數getKey()on字符串

你看起來是什麼inGroup()功能呢?此方法不指望一個字符串作爲參數

下面是完整的功能:

/** 
* See if the user is in the given group. 
* @param Group $group 
* @return bool 
*/ 
public function inGroup($group) 
{ 
    foreach ($this->getGroups() as $_group) { 
     if ($_group->getKey() == $group->getKey()) <<== Call to a member function getKey() on string 
     { 
      return true; 
     } 
    } 

    return false; 
} 

至於第二個錯誤

非靜態方法十月\雨\身份驗證\型號\用戶:: inGroup()不應該被靜態調用

你應該初始化這樣的非靜態方法:

(new User)->someMethod()