\BackendAuth::getUser() returns null, even in \App::before(){}

Hi,

I have an error with few users.

This: $user = \BackendAuth::getUser(); is returning null inside the boot() function in my Plugin.php.

Searching for a solution, i’ve come across to put the function in \App:before(){}.

It works for some people and for other, it doesn’t (create an 500 error).

The same account on my computer will work but on another computer, it doesn’t.

Here is my code:

public function boot() {

 \App::before(function() { 
            $this->extendContactController();
        });
}
public function extendContactController() {

        ContactController::extend(function($controller) {

            if (!$controller instanceof \Author\Plugin\Controllers\Contacts) {
                return;
            }

            $user = \BackendAuth::getUser();

            if ($user->role) {
                $code = $user->role->code;
            
                if ($code == 'er_regular') {
                    $controller->listConfig = '$/author/plugin/controllers/contacts/config_list_er.yaml';
                }
            } else {
                $controller->listConfig = '$/author/plugin/controllers/contacts/config_list_general.yaml';
            }
            
        });
    }

How can I make sure \BackendAuth::getUser() returns the logged user in the backend.

Thanks.

This may need to be

if ($user && $user->role) {

I agree but this is not the problem here.

The user is logged (he was in the backend, I’ve saw it) - so \BackendAuth::getUser(); shouldn’t return null.

@daft look this thread:

You wrote;

I think the Session is generally considered to be unavailable inside Service Provider/Plugin register and boot methods. This is because it fires very early in the life cycle.

Maybe consider using App::before(function() { /* ... */ }); to wrap the logic, the session should be available inside this event.

This is what I did but it doesn’t seems to work. Any ideas ? I have some code that I can’t move inside the controller directly because it’s not my plugins.

The code itself is fine. The advice in that ticket still applies today, using App::before will indeed defer until after the session has been activated.

The session requires cooperation from the browser and the server. If it works for some users and not others, we can reasonably determine it is some browsers not playing ball.

Check to make sure that the session cookie is accepted by the browser. Without this cookie, the getUser method will return null, even if they have signed in successfully.

I hope this helps.

1 Like

Thanks, I’ll start to dig deeper into that direction and do more tests.

Update: clearing both, the cache + cookies, did the job. So… if BackendAuth::getUser() returns null, you might want to do this…

1 Like