如何在 Shopware 6 Storefront Controller 或 Subscriber 中检查用户是否已登录?

Ste*_*mer 1 authentication storefront shopware shopware6

我正在寻找如何检查用户是否在 Shopware 6 店面中登录的正确方法。我正在编写一个插件(不是应用程序),并且想在控制器和/或订阅者中使用它。

我是不是该:

  1. 使用店面 API?(但是如何?走哪条路?)
  2. 使用默认的symfony方式?(isGranted) - 但有哪些角色?难道角色处理不一样吗?
  3. 使用一些内置功能,例如我可以通过依赖注入获取的特殊服务(但是是哪一个?)?

解决方案:

感谢@Uwe Kleinmann,我找到了一个解决方案,可以在这样的订阅者中工作:

public static function getSubscribedEvents()
{
  return [
    ProductPageLoadedEvent::class => 'onProductPageLoaded'
  ];
}
    
public function onProductPageLoaded(ProductPageLoadedEvent $event): void
{
  $saleschannelContext = $event->getSaleschannelContext();
  $customer = $saleschannelContext->getCustomer();

  if(NULL === $customer) {
    $customer = 'not-logged-in';
  }

  $event->getPage()->addExtension(
    'myextension', new ArrayStruct([
      'test' => $customer
    ])
  );
}
Run Code Online (Sandbox Code Playgroud)

小智 8

SalesChannelContext一个$customer(可通过getCustomer()。此上下文通常会注入到任何 Storefront 事件的 Storefront 控制器和订阅者中。

仅当当前用户登录时才设置。