OctoberCMS BackendAuth::getUser() return NULL

OctoberCMS BackendAuth::getUser() return NULL

问题: 尝试在后台获取当前认证用户(具有一定权限的管理员),OctoberCMS 平台。 我通过自定义插件扩展了一个插件(在 boot() 方法中)并且 我想在用户不这样做时从菜单中删除 sideMenuItem无权访问它。 (我成功做到了这一点 - 用户无法访问该项目(访问被拒绝) - 但我想从 sideMenu 中删除该项目)。

以下代码在 MyPlugin 中,因为我想扩展 OtherAuthor 插件。

public function boot()
    {
        /** Extends plugin */
        $this->otherAuthorPluginExtend();
    }


 public function registerPermissions()
    {
        return [
            /** Permissions for accessing sidemenuItems from OtherAuthor plugin */
            'author.plugin.plugin_access' => [
                'roles' => ['Developer'],
            ],
        ];
    }

public function otherAuthorPluginExtend(){

//>>>THIS NOT WORK
        $user = \Backend\Facades\BackendAuth::getUser();
var_dump($user);

    /*this hide sideMenu item based on permission level*/
          if(array_key_exists('author.plugin.plugin_access', $user->permissions)) {
    //>>>THIS WORKS FINE, but for all backend users
            Event::listen('backend.menu.extendItems', function ($manager) {
                $manager->removeSideMenuItem('OtherAuthor.Plugin', 'Plugin', 'sideMenuItem');
            });
          }
    
      //>>>THIS WORKS FINE
    /*this restrict access to that page from sideMenu*/

        \OtherAuthor\Plugin\Controllers\SideMenuItemController::extend(function ($controller){
            $controller->requiredPermissions = ['author.plugin.plugin_access'];
        });
}

为什么 $user 得到 NULL? 是另一种访问方式吗?

提前致谢!

事情是 event 一旦所有插件注册并且用户会话开始就被调用,所以你需要做的是推送 your conditional check code inside event callback.

In this way you can get the current backend logged-in user. `if you try to put the current user code outside maybe it's possible that the session is not initialized yet.

您的代码应如下所示。

public function boot()
{
    /** Extends plugin */
    $this->otherAuthorPluginExtend();
}

public function otherAuthorPluginExtend(){

    // here you can not get user
    // $user = \Backend\Facades\BackendAuth::getUser();

    \Event::listen('backend.menu.extendItems', function ($manager) {
        /*this hide sideMenu item based on permission level*/
        // inside event callback you can retrieve user
        $user = \Backend\Facades\BackendAuth::getUser();
        if(array_key_exists('author.plugin.plugin_access', $user->permissions)) {
            $manager->removeSideMenuItem('OtherAuthor.Plugin', 'Plugin', 'sideMenuItem');
        }
    });

    /*this restrict access to that page from sideMenu*/
    \OtherAuthor\Plugin\Controllers\SideMenuItemController::extend(function ($controller){
        $controller->requiredPermissions = ['author.plugin.plugin_access'];
    });
}

Now everything should work as expected :)

如有疑问请评论

尝试在 'backend.menu.extendItems' 事件中添加用户提取