authenticationshopwarestorefrontshopware6

How to check if user is logged in, in Shopware 6 Storefront Controller or Subscriber?


I am looking for the right way on how to check, if a user is logged in, in the Shopware 6 storefront. I am writing a plugin (not an app), and want to use this in Controllers and/or Subscribers.

Should I:

  1. Use the Storefront API? (but how? which path?)
  2. Use the default symfony way? (isGranted) - but with which Roles? Isn't the role handling different?
  3. Use some built-in functionality like a special service that I can fetch by Dependeny Injection (but which one?)?

Solution:

Thanks to @Uwe Kleinmann, I found a solution, that works in a subscriber like this:

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
    ])
  );
}

Solution

  • The SalesChannelContext has a $customer (accessible with getCustomer()) attribute. This context is usually injected into both Storefront controllers and subscribers for any Storefront events.

    It is only set, if the current user is logged-in.