Romain
Romain

Reputation: 3673

Symfony2 Getting the Current User

I'm developing an api, and I can't get the current user when I try the BasicAuth :

FatalErrorException: Error: Call to a member function getUser() on a non-object

Below you'll find the security.yml part that cause the error (I think it does) :

firewalls:
    dev:
        pattern:  ^/(_(profiler|wdt)|css|images|js)/
        security: false
    main:
        pattern:        ^/
        anonymous:      true
        stateless:      true
        http_basic:
            realm:  "REST Service Realm"
            provider:   fos_userbundle

access_control:
    - { path: ^/users/me,       role: IS_AUTHENTICATED_FULLY }

I just put the path in access_control I'm testing. I've several more.

I'm using FOSRestBundle as well as FOSUserBundle (as you can see) and I didn't want to put a prefix, because it would be redundant :

// Routing.yml
rest : 
  type : rest 
  resource : "routing_rest.yml"

Now the part where the error occur is in the UserController (extending the FOSUser one) :

private function response($data, $status, $groups = array())
{
    $currentUser = $this->container->get('security.context')->getToken()->getUser();
    if (!$currentUser)
        $groups = array("anon");
    else
    {
        if ($currentUser->hasRole("ROLE_SUPER_ADMIN"))
             array_push($groups, "admin");
        else if ($currentUser->hasRole("ROLE_ADMIN"))
             array_push($groups, "admin");
        else if ($currentUser->hasRole("ROLE_USER"))
             array_push($groups, "user");
    }
    return $this->view($data, $status)->setSerializationContext(SerializationContext::create()->setGroups($groups));
}

Any idea what's wrong ?

Upvotes: 1

Views: 1946

Answers (1)

Derick F
Derick F

Reputation: 2769

The problem is that your token is null. You have an unknown user if your token does not exist.

$token = $this->container->get('security.context')->getToken();
if (!$token) {
    return ('anon.');
} 
$user = $token->getUser();

Upvotes: 2

Related Questions