Add JS file only when user is authenticated

Created on 9 January 2025, 4 months ago

Problem/Motivation

The JS always make requests to the routes even if user is not logged. This results in several requests returning 403 and being unneeded.

Proposed resolution

function autologout_attach_js(array &$element, array $settings) {
  if (\Drupal::currentUser()->isAuthenticated()){
    $element['#attached']['drupalSettings']['autologout'] = $settings;
    $element['#attached']['library'][] = 'autologout/drupal.autologout';
    $element['#cache']['tags'][] = 'config:autologout.settings';
  }
}
Feature request
Status

Active

Version

2.0

Component

Code

Created by

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

  • Issue created by @emanuelcoelho
  • 🇮🇳India sandip

    Working on it.

  • 🇮🇳India sandip

    Hi @emanuelcoelho,
    I think we can check the authenticated user condition in function autologout_page_attachments_alter(array &$attachments) from where function autologout_attach_js(array &$element, array $settings) is called.
    If you agree i will start working on it.

  • Hi sandip,
    Yes if possible.

  • Pipeline finished with Success
    3 months ago
    Total: 629s
    #392968
  • 🇮🇳India sandip

    Please review the MR

  • Everything looks perfect.
    For me it's a go.

    Thank you for the quick response.

  • Hey @emanuelcoelho,

    I have tried reproducing your issue but the libraries mentioned above are not being attached for anonymous users and is only being attached for authenticated users. So, I don't think we will need any validation here. I think the validation is already present for anonymous users.

    // If user is anonymous.
      if ($user->id() == 0) {
        return TRUE;
      }
    

    The above validation present in the autologout_autologout_prevent() method is validating for anonymous users.

    Please provide detailed steps to replicate the issue, if I am missing something here.

    I am using Drupal 11 and 2.x-dev version of the Module here. I am attaching screenshots for the reference.
    Thanks !

  • Status changed to Needs review 23 days ago
  • I have tested the module, and I observed that the autologout.js file is not loading for anonymous users but is correctly loading for authenticated users. This behavior occurs without applying the proposed patch.

    Since the reported issue was about autologout.js making unnecessary requests for anonymous users, but that is not happening in the 2.x-dev version, this might already be resolved.

    Can anyone confirm if this issue still exists in any specific scenario?
    Moving the issue to NR for now.

Production build 0.71.5 2024