Okay I created this small authentication middleware to prevent access to private routes in my slim application:
$authenticate = function($app) {
return function() use ($app) {
if (!isset($_SESSION['user'])) {
$errors = array();
$errors['authentication'] = 'Login Required';
$app->flash('error', $errors);
$app->redirect('/login');
}
};
};
Now I want to prevent the user to be able to go to the login route ('/login') once the user has already been authenticated?
Should I create another middleware like so:
$loggedIn = function($app) {
return function() use ($app) {
if (isset($_SESSION['user'])) {
$app->redirect('/members');
}
};
};
And add it here:
$app->get('/login', $loggedIn($app), function() use ($app){
// something in here.
})
If you want to keep logged in users from hitting the /login
route, you can just use one of the route helpers to redirect them to an appropriate end point (maybe their account/user detail page or something like that if you have one):
$app->get('/login', function () use ($app) {
if (isLoggedIn()) {
$app->redirect('/account');
}
else {
// your standard login code here
}
});
I think that makes more sense than writing an isLoggedIn middleware.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.