So as the title dictates, I'm trying to redirect the user based on his status but I'm facing difficulty in doing so. Here is what i'm doing:
In the submit form:
public function submitForm(array &$form, FormStateInterface $form_state){
.......
$logged_user = json_decode($response);
$_SESSION['loggedin'] = true;
$_SESSION["jwt"] = $logged_user->token;
$form_state->setRedirect('entity.node.canonical', ['node' => 1]);//After submit i redirect the user to /node/1 which is intercepterd by the route defined in module.routing.yml
........
}
In my routing file:
user.home:
path: '/node/1'
defaults:
_controller: '\Drupal\smeno\Controller\SmenoHomeController::index'
requirements:
_permission: 'access content'
In my controller file:
function index(){
if (!(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true)) {
return $this->redirect('<front>');
}
}
Now if the user is not authenticated and attempt to access /node/1 he is redirected to the page, it works fine, however, if the user is authenticated and tries to access /node/1 it gives me an error that there is no error in my controller which is logical because I haven't defined an else in the index() function where the user is already authenticated, then the user should get the page he is demanding. So i did the following:
function index(){
if (!(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true)) {
return $this->redirect('<front>');
}else{
return $this->redirect('entity.node.canonical', ['node' => 1]);
}
}
but with this it puts me in an infinite loop of redirection which is comprehensible. when an authenticated user request /node/1 the route is activated and it sends him to the index function and the latter redirect him back to /node/1 and the route is activated again and so on.
Now the question is how can i let the authenticated user gets the page he is demanding??
node/1
and the authenticated user wants to get there and you are redirecting infinitely? What are you trying to accomplish? You have a form. On submit, you redirect to theoretically a node, but you've hijacked the node/1 route. If you've hijacked the node/1 route, why? Are anonymous user allowed to go to the actual node/1 at all? If not, then make an event subscriber to redirect anonymous users and get rid of the hijacked route./node/1
and using the route i defined earlier i intercept users trying to access/node/1
in order to see which type of user is asking the home page, if its an anonymous i redirect him back to the login page which is working and if its authenticated user i let him pass (P.S. indeed i'm being redirected infinitely and there is only one page).