Impersonate() in hooks and Panel

Hi all,
I ran into an odd behaviour when building a hook that allows users to impersonate a certain role.

In its most boiled down version the hook looks like this:

    return [
        'hooks' => [
            'route:before' => function ($route, $path, $method) {
                $kirby = kirby();
                // If logging in
                if($path == 'panel/login'){
                    // Do nothing, default behaviour
                    return;
                } else {
                    $kirby->impersonate('some@user.com');
                }
            }
        ],...

The odd thing is: when I try to login to the panel (path ‘panel/login’)
I get the error message “Cannot read property ‘status’ of undefined”
If I comment out $kirby->impersonate(‘some@user.com’); everything works as expected.
If I add a return statement above the line as the first line of the else statement it also works as expected.

I checked that the condition is true and the return in the if statement is reached.
What am I missing?
I have Kirby 3.5.3.1

Thanks a lot!
Memi

What are you trying to do here? And when exactly do you get the error (can’t reproduce this).

Apart from that, returning something from a hook is not possible, so while it doesn’t hurt, it won’t do anything. Hooks perform an action in the background when they are triggered.

This is a stripped-down version of the hook I use. The hook looks if the visitor’s IP address is in a list of IP-Addresses and if so lets the visitor impersonate a specific user.
However, if a visitor wants to access the panel, Kirby should not impersonate a user but exit from the hook.

The return statement should do that: exit from the hook since the hook is a function.

I get the error when I try to open panel/login

Since you only want to do something when the path is not panel/login, you don’t need an if-else condition but only

if ( $path !== 'panel/login') {
   kirby()->impersonate('some@user.com');
}

No idea where you error is coming from, is that in console?

Thanks for your suggestion, I still get the error though.
It is a panel error view.
panel error

I looked if it possibly comes from an ajax call or some other api request, however there is none.

And there are no details regarding this error in the browser console?

No, none, unfortunately.
It is very weird.
However, thanks for your help!