I m beginner on drupal, and i have a problem with session.
I created a custom form submission inside the clubs module.
namespace Drupal\idan_login\Form; // Form submission handler. public function submitForm(array &$form, FormStateInterface $form_state) { // Get the submitted values. $values = $form_state->getValues(); $username = $values['username']; $password = $values['password']; // Tentez d'authentifier l'utilisateur. // Attempt to check infos the user. $uid = \Drupal::service('user.auth')->authenticate($username, $password); // Check if authentication was successful. if ($uid) { // User authenticated successfully. // Load the user entity. $user = User::load($uid); // Check if the user has the "club idan" role. if ($user->hasRole('club_idan')) { $_SESSION['has_subscribed'] = TRUE; // User authenticated successfully and has the "club idan" role. \Drupal::messenger()->addStatus(t("Vous avez été connecté avec succès")); // Redirect to "/fr/clubs". $response = new RedirectResponse('/fr/clubs'); $response->send(); } else { unset($_SESSION['has_subscribed']); // User authentication failed due to missing role. \Drupal::messenger()->addError(t("Vous n'avez pas le rôle requis pour accéder à ce site")); // Redirect to a different page. $form_state->setRedirectUrl(Url::fromUri('internal:/fr/club-idan')); } } else { // Authentication failed. unset($_SESSION['has_subscribed']); // Display an error message. \Drupal::messenger()->addError(t("Nom d'utilisateur ou mot de passe invalide. Veuillez réessayer")); // Redirect back to the same page. $form_state->setRedirectUrl(Url::fromUri('internal:/fr/club-idan')); } // Rebuild the form to display any updated messages. //$form_state->setRebuild(TRUE); } And i create a new custom module named "custom_access_check" to grant access to a page when the "has_subscribed" value has been set for the current session.
// custom_access_check.module use Drupal\Core\Url; use Drupal\Core\Session\SessionManagerInterface; /** * Implements hook_node_view_alter(). */ function custom_access_check_node_view_alter(&$build) { // Start the session if it's not already started. \Drupal::service('session')->start(); // Check if the node being viewed is of type 'your_content_type'. if (!empty($build['#node']->getType()) && $build['#node']->getType() == 'page') { if ($alias_path == '/clubs') { // Check if the session variable "has_subscribed" is set. if (!isset($_SESSION['has_subscribed']) || !$_SESSION['has_subscribed']) { // If user has not subscribed, deny access to the content. throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException(); } } } } $_SESSION['has_subscribed'] contains NULL.
If someone has the some situation or has any idea for this problem?
$build['#cache']['contexts'][] = 'session';for the content type in the node view hook.