PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, September 4, 2022

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

 September 04, 2022     authentication, shopware, shopware6, storefront     No comments   

Issue

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.



Answered By - Uwe Kleinmann
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing