skip to Main Content

I want to check that a user is logged into my app directly in the initController method of the BaseController and redirect them to an OIDC authentication mechanism (AuthController) if not logged in.

If I run the following code, my script obviously loops to itself.

BaseController.php

public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);

        if (!session()->userLogin) {
            //no user logged in
            $this->response->redirect(site_url('/auth'));
        }
    }

So, how can I prevent AuthController redirecting to itself?

Should I override the initController method in AuthController or can I check the name of the current controller or route in the initController of BaseController with get_class($this); ?

Which is the most appropriate?

2

Answers


  1. Chosen as BEST ANSWER

    The simpliest way to do it, like sayd by @simonweber, is to use the global filters, with an EXCEPT directive.

    It has been anwswered already here :

    how to excluding global filter for a single controller


  2. Simply add a route check to your if condition.

    !session()->userLogin && !str_contains(current_url(), site_url('/auth'))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search