Problem/Motivation

When the module is enabled on an existing website with a lot of content types, a lot of changes must be done in the module permissions to keep the site running as it was before (user can access content).

I recently had to add a new section with a restricted content to a new role on an existing website with a lot of content types (+15). I use the `node_view_permissions` module which is perfect for this. But when the module is activated, even if the new part is not yet done, I had to change quickly the permissions to allow normal or anonymous users to be able to browse the site.

I think it would be better if the module installation does not change the current behaviour of the existing site.

Proposed resolution

Automatically add the new `view any [bundle] content` permission for all existing node types, to anonymous and connected users roles in `hook_install`.

Here is the proposed code, inspired from the other hooks of the module:


/**
 * @file
 * Contains install and update functions for node_view_permissions.
 */

use Drupal\node\Entity\NodeType;
use Drupal\user\Entity\Role;

/**
 * Implements hook_install().
 */
function node_view_permissions_install() {
  node_access_needs_rebuild(TRUE);

  // Add 'view any [node_type] content' permission
  // for anonymous and connected users.
  $roles = [
    Role::ANONYMOUS_ID,
    Role::AUTHENTICATED_ID,
  ];

  foreach ($roles as $role) {
    $role_object = Role::load($role);
    foreach (NodeType::loadMultiple() as $type) {
      $type_id = $type->id();
      $role_object->grantPermission("view any $type_id content");
    }
    $role_object->save();
  }
}

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

ccrosaz created an issue. See original summary.

mlncn’s picture

Status: Active » Reviewed & tested by the community

Code looks great, and this is very needed!

nagy.balint’s picture

Version: 8.x-1.x-dev » 2.x-dev

  • nagy.balint committed b90f7656 on 2.x
    feat: #3439984 On module install set new content view permissions...
nagy.balint’s picture

Status: Reviewed & tested by the community » Fixed

Now that this issue is closed, review the contribution record.

As a contributor, attribute any organization that helped you, or if you volunteered your own time.

Maintainers, credit people who helped resolve this issue.

Status: Fixed » Closed (fixed)

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