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:
- Use the Storefront API? (but how? which path?)
- Use the default symfony way? (isGranted) - but with which Roles? Isn't the role handling different?
- Use some built-in functionality like a special service that I can fetch by Dependeny Injection (but which one?)?
CodePudding user response:
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.
CodePudding user response:
You may also use the _loginRequired
and _loginRequiredAllowGuest
flags in the @Route
annotation of a storefront controller's method. This is handy if you only want to allow access for logged in customers as this will automatically redirect logged out users to the login page and back to the origin after they logged in.
/**
* @Route("/my/custom/page", name="frontend.custom.page", methods={"GET"}, defaults={"_loginRequired"=true, "_loginRequiredAllowGuest"=true})
*/