CodeIgniter Forums
Global session check and re-direct - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Global session check and re-direct (/showthread.php?tid=90568)



Global session check and re-direct - joho - 04-04-2024

Scenario:

Segmented application, with two or more parts, handling different aspects of access. Similar to how an OAuth situation would look. In the main application, I need to check if there's a valid session. If there is not a valid session, I want to re-direct to the authentication handling application. This could be the "internal" one (still a separate URL, etc) or an "external" one, like Google, Microsoft, whatever.

To avoid having to put a session check in every single Controller function or "route", is it a good idea to put a "global check" in app/Config/Routes.php before anything else, and simply issue a re-direct (and die) before any routes are configured?

Or is there a better/more correct way of doing this the CodeIgniter way?

I guess I should also mention that if the "global session check" fails, the main application should obviously check if we're coming back from an authentication handling app with the correct parameters.

I just realized I could possibly use the Controller's before filter, I think? :-) But then I'd need to add one for every controller, so it's still not a "global session check" per se.

Or is it a $global Filter I should actually use ... ?


RE: Global session check and re-direct - InsiteFX - 04-04-2024

In your BaseController initController(...)

PHP Code:
        // Ensure that the session is started and running
        if (session_status() === PHP_SESSION_NONE)
        {
            // if session status is none then start the session
            $this->session Services::session();
        



RE: Global session check and re-direct - kenjis - 04-04-2024

(04-04-2024, 01:49 AM)joho Wrote: To avoid having to put a session check in every single Controller function or "route", is it a good idea to put a "global check" in app/Config/Routes.php before anything else, and simply issue a re-direct (and die) before any routes are configured?

It is bad practice in the old Ci3 age.
It breaks the framework process flow.

Also, if you put die() in your code, you cannot write test code.
Because when you run test, the test runner will die with it.


RE: Global session check and re-direct - kenjis - 04-04-2024

Probably there are two ways.
- https://codeigniter4.github.io/CodeIgniter4/incoming/filters.html#globals
- https://codeigniter4.github.io/CodeIgniter4/incoming/routing.html#setting-filters


RE: Global session check and re-direct - joho - 04-04-2024

I ended up doing it in a global filter, we'll see how that goes. Thank you for your comments.