Register popup is not loading for anonymous users. Firebug showing the following message.
'csrf_token' URL query argument is invalid.
"message":"\u0027csrf_token\u0027 URL query argument is invalid."

Drupal 8.4.4/ php 7

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

    Comments

    linkson created an issue. See original summary.

    DrupalDude777’s picture

    This is related to another Drupal 8 core issue: https://www.drupal.org/project/drupal/issues/2730351

    DrupalDude777’s picture

    But as this https://www.drupal.org/project/drupal/issues/2730351 issue is still not resolved here is a workaround :

    In /like_dislike/like_dislike.routing.yml you should replace the content by:

    like_dislike.manager:
      path: like-dislike/{clicked}/{data}
      defaults:
        _controller: '\Drupal\like_dislike\Controller\LikeDislikeController::handler'
      requirements:
        _permission: 'access content'
        _csrf_token: 'TRUE'
    like_dislike.loggedout_manager:
      path: like-dislike/{clicked}/{data}
      defaults:
        _controller: '\Drupal\like_dislike\Controller\LikeDislikeController::handler'
      requirements:
        _permission: 'access content'
    

    In /like_dislike/src/Plugin/Field/FieldFormatter/LikeDislikeFormatter.php replace lines 134 to 139 by this:

    if(\Drupal::currentUser()->isAuthenticated()) {
        $route = 'like_dislike.manager';
    }
    else {
        $route = 'like_dislike.loggedout_manager';
    }
    $like_url = Url::fromRoute(
            $route, ['clicked' => 'like', 'data' => $data]
    )->toString();
    $dislike_url = Url::fromRoute(
        	$route, ['clicked' => 'dislike', 'data' => $data]
    )->toString();
    

    So this file content once changed should be:

    <?php
    
    namespace Drupal\like_dislike\Plugin\Field\FieldFormatter;
    
    use Drupal\Core\Field\FieldDefinitionInterface;
    use Drupal\Core\Field\FieldItemListInterface;
    use Drupal\Core\Field\FormatterBase;
    use Drupal\Core\Form\FormStateInterface;
    use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
    use Drupal\Core\Session\AccountInterface;
    use Drupal\Core\Url;
    use Symfony\Component\DependencyInjection\ContainerInterface;
    use Symfony\Component\HttpFoundation\RequestStack;
    
    /**
     * Plugin implementation of the 'like_dislike_formatter' formatter.
     *
     * @FieldFormatter(
     *   id = "like_dislike_formatter",
     *   label = @Translation("Like Dislike"),
     *   field_types = {
     *     "like_dislike"
     *   }
     * )
     */
    class LikeDislikeFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
    
      /**
       * The current user.
       *
       * @var \Drupal\Core\Session\AccountInterface
       */
      protected $currentUser;
    
      /**
       * The request stack.
       *
       * @var \Symfony\Component\HttpFoundation\RequestStack
       */
      protected $requestStack;
    
      /**
       * Constructs an ImageFormatter object.
       *
       * @param string $plugin_id
       *   The plugin_id for the formatter.
       * @param mixed $plugin_definition
       *   The plugin implementation definition.
       * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
       *   The definition of the field to which the formatter is associated.
       * @param array $settings
       *   The formatter settings.
       * @param string $label
       *   The formatter label display setting.
       * @param string $view_mode
       *   The view mode.
       * @param array $third_party_settings
       *   Any third party settings settings.
       * @param \Drupal\Core\Session\AccountInterface $current_user
       *   The current user.
       * @param \Symfony\Component\HttpFoundation\RequestStack $request
       *   The request stack.
       */
      public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, AccountInterface $current_user, RequestStack $request) {
        parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
        $this->currentUser = $current_user;
        $this->requestStack = $request;
      }
    
      /**
       * {@inheritdoc}
       */
      public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
        return new static(
          $plugin_id,
          $plugin_definition,
          $configuration['field_definition'],
          $configuration['settings'],
          $configuration['label'],
          $configuration['view_mode'],
          $configuration['third_party_settings'],
          $container->get('current_user'),
          $container->get('request_stack')
        );
      }
    
      /**
       * {@inheritdoc}
       */
      public static function defaultSettings() {
        return array(
          // Implement default settings.
        ) + parent::defaultSettings();
      }
    
      /**
       * {@inheritdoc}
       */
      public function settingsForm(array $form, FormStateInterface $form_state) {
        return array(
          // Implement settings form.
        ) + parent::settingsForm($form, $form_state);
      }
    
      /**
       * {@inheritdoc}
       */
      public function settingsSummary() {
        $summary = [];
        // Implement settings summary.
    
        return $summary;
      }
    
      /**
       * {@inheritdoc}
       */
      public function viewElements(FieldItemListInterface $items, $langcode='en') {
        $entity = $items->getEntity();
        $elements = [];
    
        // Data to be passed in the url.
        $initial_data = [
          'entity_type' => $entity->getEntityTypeId(),
          'entity_id' => $entity->id(),
          'field_name' => $items->getFieldDefinition()->getName(),
        ];
        foreach ($items as $delta => $item) {
          $initial_data['likes'] = $items[$delta]->likes;
          $initial_data['dislikes'] = $items[$delta]->dislikes;
        }
        $data = base64_encode(json_encode($initial_data));
    	
        if(\Drupal::currentUser()->isAuthenticated()) {
        	$route = 'like_dislike.manager';
        }
        else {
        	$route = 'like_dislike.loggedout_manager';
        }
        $like_url = Url::fromRoute(
        		$route, ['clicked' => 'like', 'data' => $data]
        )->toString();
        $dislike_url = Url::fromRoute(
        		$route, ['clicked' => 'dislike', 'data' => $data]
        )->toString();
        
        // If user is anonymous, then append the destination back url.
        $user = $this->currentUser->id();
        $destination = '';
        if ($user == 0) {
          $destination = '?like-dislike-redirect=' . $this->requestStack->getCurrentRequest()->getUri();
        }
        
        $elements[] = [
          '#theme' => 'like_dislike',
          '#likes' => $initial_data['likes'],
          '#dislikes' => $initial_data['dislikes'],
          '#like_url' => $like_url . $destination,
          '#dislike_url' => $dislike_url . $destination,
          '#entity_id' => $initial_data['entity_id'],
        ];
    
        $elements['#attached']['library'][] = 'core/drupal.ajax';
        $elements['#attached']['library'][] = 'like_dislike/like_dislike';
    
        // Set the cache for the element.
        $elements['#cache']['max-age'] = 0;
        return $elements;
      }
    
    }
    

    The idea is to have a second route with the same path and same handler in controller but without csrf_token and to use it if the user is not connected.

    DrupalDude777’s picture

    Status: Active » Needs review
    DrupalDude777’s picture

    Here is a better coded version of /like_dislike/src/Plugin/Field/FieldFormatter/LikeDislikeFormatter.php (full content of the file):

    <?php
    
    namespace Drupal\like_dislike\Plugin\Field\FieldFormatter;
    
    use Drupal\Core\Field\FieldDefinitionInterface;
    use Drupal\Core\Field\FieldItemListInterface;
    use Drupal\Core\Field\FormatterBase;
    use Drupal\Core\Form\FormStateInterface;
    use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
    use Drupal\Core\Session\AccountInterface;
    use Drupal\Core\Url;
    use Symfony\Component\DependencyInjection\ContainerInterface;
    use Symfony\Component\HttpFoundation\RequestStack;
    
    /**
     * Plugin implementation of the 'like_dislike_formatter' formatter.
     *
     * @FieldFormatter(
     *   id = "like_dislike_formatter",
     *   label = @Translation("Like Dislike"),
     *   field_types = {
     *     "like_dislike"
     *   }
     * )
     */
    class LikeDislikeFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
    
      /**
       * The current user.
       *
       * @var \Drupal\Core\Session\AccountInterface
       */
      protected $currentUser;
    
      /**
       * The request stack.
       *
       * @var \Symfony\Component\HttpFoundation\RequestStack
       */
      protected $requestStack;
    
      /**
       * Constructs an ImageFormatter object.
       *
       * @param string $plugin_id
       *   The plugin_id for the formatter.
       * @param mixed $plugin_definition
       *   The plugin implementation definition.
       * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
       *   The definition of the field to which the formatter is associated.
       * @param array $settings
       *   The formatter settings.
       * @param string $label
       *   The formatter label display setting.
       * @param string $view_mode
       *   The view mode.
       * @param array $third_party_settings
       *   Any third party settings settings.
       * @param \Drupal\Core\Session\AccountInterface $current_user
       *   The current user.
       * @param \Symfony\Component\HttpFoundation\RequestStack $request
       *   The request stack.
       */
      public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, AccountInterface $current_user, RequestStack $request) {
        parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
        $this->currentUser = $current_user;
        $this->requestStack = $request;
      }
    
      /**
       * {@inheritdoc}
       */
      public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
        return new static(
          $plugin_id,
          $plugin_definition,
          $configuration['field_definition'],
          $configuration['settings'],
          $configuration['label'],
          $configuration['view_mode'],
          $configuration['third_party_settings'],
          $container->get('current_user'),
          $container->get('request_stack')
        );
      }
    
      /**
       * {@inheritdoc}
       */
      public static function defaultSettings() {
        return array(
          // Implement default settings.
        ) + parent::defaultSettings();
      }
    
      /**
       * {@inheritdoc}
       */
      public function settingsForm(array $form, FormStateInterface $form_state) {
        return array(
          // Implement settings form.
        ) + parent::settingsForm($form, $form_state);
      }
    
      /**
       * {@inheritdoc}
       */
      public function settingsSummary() {
        $summary = [];
        // Implement settings summary.
    
        return $summary;
      }
    
      /**
       * {@inheritdoc}
       */
      public function viewElements(FieldItemListInterface $items, $langcode='en') {
        $entity = $items->getEntity();
        $elements = [];
    
        // Data to be passed in the url.
        $initial_data = [
          'entity_type' => $entity->getEntityTypeId(),
          'entity_id' => $entity->id(),
          'field_name' => $items->getFieldDefinition()->getName(),
        ];
        foreach ($items as $delta => $item) {
          $initial_data['likes'] = $items[$delta]->likes;
          $initial_data['dislikes'] = $items[$delta]->dislikes;
        }
        $data = base64_encode(json_encode($initial_data));
    	
        if($this->currentUser->isAuthenticated()) {
        	$route = 'like_dislike.manager';
        }
        else {
        	$route = 'like_dislike.loggedout_manager';
        }
        $like_url = Url::fromRoute(
        		$route, ['clicked' => 'like', 'data' => $data]
        )->toString();
        $dislike_url = Url::fromRoute(
        		$route, ['clicked' => 'dislike', 'data' => $data]
        )->toString();
        
        // If user is anonymous, then append the destination back url.
        $user = $this->currentUser->id();
        $destination = '';
        if ($user == 0) {
          $destination = '?like-dislike-redirect=' . $this->requestStack->getCurrentRequest()->getUri();
        }
        
        $elements[] = [
          '#theme' => 'like_dislike',
          '#likes' => $initial_data['likes'],
          '#dislikes' => $initial_data['dislikes'],
          '#like_url' => $like_url . $destination,
          '#dislike_url' => $dislike_url . $destination,
          '#entity_id' => $initial_data['entity_id'],
        ];
    
        $elements['#attached']['library'][] = 'core/drupal.ajax';
        $elements['#attached']['library'][] = 'like_dislike/like_dislike';
    
        // Set the cache for the element.
        $elements['#cache']['max-age'] = 0;
        return $elements;
      }
    
    }
    
    heykarthikwithu’s picture

    Version: 8.x-1.1 » 2.1.0
    Status: Needs review » Needs work

    Hello DrupalDude777! Thank you.

    I think it needs a patch.

    heykarthikwithu’s picture

    Assigned: Unassigned » anandhi karnan
    bill_redman’s picture

    I installed this module and when trying it as an anonymous user got the 'cs_rf token' error. I found this issue and after applying the changes provided by @DrupalDude777 my error was resolved. However, when I again tried to Like my page as an anonymous user, I got the following error in the console:

    Drupal.AjaxError{ "message": "\nAn AJAX HTTP error occurred.\nHTTP Result Code: 200\nDebugging information follows.\nPath: /like-dislike/like/eyJlbnRpdHlfdHlwZSI6Im5vZGUiLCJlbnRpdHlfaWQiOiI1MzQ2IiwiZmllbGRfbmFtZSI6ImZpZWxkX2xpa2UiLCJsaWtlcyI6IjYifQ%3D%3D?token=NBGdogFRsOm7_-B85Xrd17QOX9uu2qu1nBEOkfX_UpA?like-dislike-redirect=https://mysite.com/mynode\nStatusText: parsererror\nResponseText: Error: Call to undefined method Drupal\\like_dislike\\Controller\\LikeDislikeController::likeDislikeLoginRegister() in Drupal\\like_dislike\\Controller\\LikeDislikeController-&gt;handler() (line 120 of /code/modules/like_dislike/src/Controller/LikeDislikeController.php).",
        "name": "AjaxError"
    }

    Does this module not allow Like/Dislike by anonymous users or is something else wrong? If the module does not allow it, is there a way to change that? I really like the simple & clean look of the module and would like to be able to use it.

    My site is using Drupal 8.9.20 & PHP 7.4

    heykarthikwithu’s picture

    Title: Register popup is not loading for anonymous users » Anonymous user get the 'cs_rf token' error when clicked on Like/Dislike
    Version: 2.1.0 » 2.2.0
    Assigned: anandhi karnan » Unassigned

    Thanks you all for working on this issue.

    Done some major fixes around like & dislikes within 2.2.0 release,
    Have a check if this issue still exist with 2.2.0 version?

    Please check for the module page for the features covered.

    CSRF Token issues needs to be fixed.

    • f5165139 committed on 2.x
      Issue #2943324 by DrupalDude777, heykarthikwithu: Anonymous user get the...
    heykarthikwithu’s picture

    Status: Needs work » Reviewed & tested by the community

    Alternate solution is applied until this issue is fixed in core - https://www.drupal.org/project/drupal/issues/2730351

    This will be released in the upcoming release.

    heykarthikwithu’s picture

    Status: Reviewed & tested by the community » Fixed

    Fixed in latest 2.3.0 version.

    Status: Fixed » Closed (fixed)

    Automatically closed - issue fixed for 2 weeks with no activity.