Reputation: 12457
I would like to get current userid like this in one class(FOSUBUserProvider)
$this->get('security.context')->getToken()->getUser()
but it says
FatalErrorException: Error: Call to undefined method Acme\UserBundle\Security\Core\User\FOSUBUserProvider::get() in
I think I should inject something in this class though,
How can I do it?
My construct is this, how can I add here security.context?
class FOSUBUserProvider extends BaseClass
{
public function __construct(UserManagerInterface $userManager, array $properties)
{
$this->userManager = $userManager;
$this->properties = $properties;
}
Upvotes: 0
Views: 3730
Reputation: 2034
Reason
FOSUBUserProvider
doesn't have container injected so $this->get()
won't work (alias for $this->container->get()
)
Solution
if you want to access security.context
service then easiest and I think the most elegant way would be to extend FOSUBUserProvider
in your bundle.
to do so create new class that extends: HWI\Bundle\OAuthBundle\Security\Core\User\FOSUBUserProvider
Please note that array $properties
must be the last argument, I injected $securityContext between them. This is necessary because we override service definition and later it will have appended arguments. (Quite advanced topic not relevant here)
namespace KP\MainBundle\Security\Core\User;
use FOS\UserBundle\Model\UserManagerInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\FOSUBUserProvider as BaseFOSUBUserProvider;
use Symfony\Component\Security\Core\SecurityContext;
class FOSUBUserProvider extends BaseFOSUBUserProvider
{
/**
* @var SecurityContext
*/
protected $securityContext;
/**
* Constructor.
*
* @param UserManagerInterface $userManager FOSUB user provider.
* @param SecurityContext $securityContext Security context
* @param array $properties Property mapping.
*/
public function __construct(UserManagerInterface $userManager, $securityContext, array $properties)
{
$this->userManager = $userManager;
$this->securityContext = $securityContext;
$this->properties = $properties;
}
}
Override class name used by HWIOAuthBundle add in your services file
parameter:
hwi_oauth.user.provider.fosub_bridge.class: KP\MainBundle\Security\Core\User\FOSUBUserProvider
services:
hwi_oauth.user.provider.fosub_bridge.def:
class: %hwi_oauth.user.provider.fosub_bridge.class%
abstract: true
arguments:
- @fos_user.user_manager
- @security.context
Important note
Your bundle must be registered AFTER HWIOAuthBundle
, otherwise overriding service won't work.
# app/AppKernel.php
$bundles = array(
...
new FOS\UserBundle\FOSUserBundle(),
new HWI\Bundle\OAuthBundle\HWIOAuthBundle(),
new KP\MainBundle\KPMainBundle(),
...
Now you can access SecurityContext
service with simple $this->securityContext
Upvotes: 2