AltoRouter icon indicating copy to clipboard operation
AltoRouter copied to clipboard

Is there a way to force redirect (match)?

Open doksara opened this issue 6 years ago • 4 comments

So I was wondering is it possible to force redirect (or force match to one of mapped routes) in router? Since every request is handled by my router (index.php), I am firstly calling validateToken() function to check is token is validated. If it is valid just call router->match(), or else redirect to login page (NOTE: I don't want to do this using header).

$router->map('GET', '/login/', function() { require __DIR__ . '/login.php'; }, 'login');
 // Get the match
$match = $router->match();

// Check if user is signed in
if (!validateToken()){
    header("Location: /caffemania/login.php");
} 

doksara avatar Mar 03 '19 14:03 doksara

You can simply move the match below the if, right?

koenpunt avatar Mar 03 '19 17:03 koenpunt

But I am forcing user to go on a certain mapped route (/caffemania/login), not matching the user's route! If I place the match below the if, it will simply try to match the desired location. What I am trying to do is forbid access to certain location (route) if the token is not valid, and redirect the user to login page then. Am I doing something wrong?

doksara avatar Mar 03 '19 17:03 doksara

If I try to put it below the if, I get this capture

doksara avatar Mar 03 '19 18:03 doksara

Hi,
I'm not sure if this helps, but I check for login after a match, something like the below. I'm using my own MVC style approach (i.e no frameworks) but the same principle should apply to your scenario?

/* Match the current request */
$match = $router->match();

if(User::isLoggedIn()) : // check user is logged before routing

 //route code here

else:                              

      include_once __DIR__ . '/app/views/user/login.php';

 endif;

webdev-lee avatar Aug 05 '19 12:08 webdev-lee