EzPublish 用户:如何在前端标准 symfony 控制器中使用 ezPublish 访问控制

EzPublish users : how to use ezPublish access control in front standard symfony controller

我仅将 ezPublish 5.3 用于其管理方面。我想做的是在这个后台管理用户/用户组/角色,并控制他们对设计 API.

的 FOSRestBundle 的访问

这是我的 security.yml :

security:
    providers:
        ezpublish:
            id: ezpublish.security.user_provider

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        my_api:
            pattern: ^/api/v[0-9]+
            stateless: true
            ezpublish_http_basic:
                realm: eZ Publish REST API

        ezpublish_front:
            pattern: ^/
            anonymous: ~
            ezpublish_rest_session: ~
            form_login:
                require_previous_session: false
            logout: ~

        default:
            anonymous: ~

这是我想在控制器中执行的操作:

<?php
namespace Acme\AppBundle\Controller;

use FOS\RestBundle\Controller\FOSRestController;

class ItemsController extends FOSRestController
{
    public function postItemsAction(Request $request)
    {
        if (!$this->get('security.authorization_checker')->isGranted('EZ_CUSTOM_ROLE')) {
            throw new \Exception('No Auth');
        }

        //... do something
     }
}

我收到了这样的回复:

{
  "code": 0,
  "message": "User 'USER_LOGIN' doesn't have user/login permission to SiteAccess 'site'"
}

我怎样才能做到这一点? 如何检索用户角色?

在探查器中我可以看到,当我对这个操作进行基本授权的标准 POST 时,用户连接到默认的 Symfony 角色 ROLE_USER

这是我的解决方案:

<?php
namespace Acme\AppBundle\Controller;

use FOS\RestBundle\Controller\FOSRestController;
use eZ\Publish\API\Repository\Values\User\RoleAssignment;
use eZ\Publish\API\Repository\Values\User\User;

class ItemsController extends FOSRestController
{
    public function postItemsAction(Request $request)
    {
        if (!$this->isUserRoleGranted()) {
            throw new \Exception('No Auth');
        }

        //... do something
     }

    private function isUserRoleGranted()
    {
        $user = $this->getCurrentUser();

        if ($user instanceof User) {
            $roleService = $this->get('ezpublish.api.repository')->getRoleService();
            $roles       = $roleService->getRoleAssignmentsForUser($user, true);

            if (is_array($roles) && !empty($roles)) {
                foreach ($roles as $role) {
                    if ($role instanceof RoleAssignment) {
                        $roleIdentifier = $role->getRole()->__get('identifier');

                        if (is_string($roleIdentifier) && $roleIdentifier === 'EZ_CUSTOM_ROLE') {
                            return true;
                        }
                    }
                }
            }
        }

        return false;
    }

    private function getCurrentUser()
    {
        return $this->get('ezpublish.api.repository')->getUserService()->loadUser(
            $this->get('ezpublish.api.repository')->getPermissionResolver()->getCurrentUserReference()->getUserId()
        );
    }
}