Search code examples
phproutesfat-free-framework

How to use f3 beforeroute() to check for logged in user, redirect to login and then back to original route?


I'm trying to use fat free framework in my application. beforeroute() seems like a logical choice for checking for an active session, if all routes on this path require authentication. I am having trouble trying to find which route the user was attempting to go to before I hijack it and force them to login. I feel like there should be an f3 variable, or something simple that I can call within beforeroute() that'll give me information about where they were trying to go, and that I should be able to use f3 to accomplish this, instead of other ways I've done this in php apps (session variable, or sending something as a param in the domain, etc).

Am I missing something about beforeroute()? Should it not be used for this situation? And if not, what is the best practice?

I've tried grabbing the url in a session variable $f3->set('SESSION.previousUrl', $f3->REALM), but since I am always redirecting them to login, the result is always /login.

While I'm at it, can somebody explain the difference between reroute and redirect within f3? Thanks in advance.


Solution

  • Just pass the origin URL to the login route. E.g:

    function beforeRoute($f3,$params) {
      if (/*user not authenticated*/)
        $f3->reroute('/login?origin='.$f3->PATH);
        // or if you need to preserve query strings:
        $f3->reroute('/login?origin='.urlencode($f3->PATH.($f3->QUERY?'?'.$f3->QUERY:'')));
    }
    

    Now in your login route, if the user authenticates correctly, reroute it back to the origin URL:

    function post($f3,$params) {
      if (/*user gets authenticated*/) {
        $f3->reroute(isset($_GET['origin'])?$_GET['origin']:'/');
      }
    }
    

    As for the redirect method, it's a mix between route and reroute.

    For example, $f3->redirect('GET /oldpage','/newpage',TRUE) is a shorthand for:

    $f3->route('GET /oldpage',function($f3){
      $f3->reroute('/newpage',TRUE);
    });
    

    It's mostly interesting to be used in configuration files, such as:

    [redirects]
    GET /oldpage = /newpage