clean install

This commit is contained in:
matze committed 2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 files changed
+3555714

No files matched your search

@@ -0,0 +1,10 @@
assing
csslint
Delegatable
delegatable
Dougherty
enity
Jeroen
phplint
recieves
Tubex
@@ -0,0 +1,99 @@
################
# DrupalCI GitLabCI template
#
# Gitlab-ci.yml to replicate DrupalCI testing for Contrib
#
# With thanks to:
# * The GitLab Acceleration Initiative participants
# * DrupalSpoons
################
################
# Guidelines
#
# This template is designed to give any Contrib maintainer everything they need to test, without requiring modification. It is also designed to keep up to date with Core Development automatically through the use of include files that can be centrally maintained.
#
# However, you can modify this template if you have additional needs for your project.
################
################
# Includes
#
# Additional configuration can be provided through includes.
# One advantage of include files is that if they are updated upstream, the changes affect all pipelines using that include.
#
# Includes can be overridden by re-declaring anything provided in an include, here in gitlab-ci.yml
# https://docs.gitlab.com/ee/ci/yaml/includes.html#override-included-configuration-values
################
include:
################
# DrupalCI includes:
# As long as you include this, any future includes added by the Drupal Association will be accessible to your pipelines automatically.
# View these include files at https://git.drupalcode.org/project/gitlab_templates/
################
- project: $_GITLAB_TEMPLATES_REPO
ref: $_GITLAB_TEMPLATES_REF
file:
- '/includes/include.drupalci.main.yml'
# EXPERIMENTAL: For Drupal 7, remove the above line and uncomment the below.
# - '/includes/include.drupalci.main-d7.yml'
- '/includes/include.drupalci.variables.yml'
- '/includes/include.drupalci.workflows.yml'
################
# Pipeline configuration variables
#
# These are the variables provided to the Run Pipeline form that a user may want to override.
#
# Docs at https://git.drupalcode.org/project/gitlab_templates/-/blob/1.0.x/includes/include.drupalci.variables.yml
################
# variables:
# SKIP_ESLINT: '1'
###################################################################################
#
# *
# /(
# ((((,
# /(((((((
# ((((((((((*
# ,(((((((((((((((
# ,(((((((((((((((((((
# ((((((((((((((((((((((((*
# *(((((((((((((((((((((((((((((
# ((((((((((((((((((((((((((((((((((*
# *(((((((((((((((((( .((((((((((((((((((
# ((((((((((((((((((. /(((((((((((((((((*
# /((((((((((((((((( .(((((((((((((((((,
# ,(((((((((((((((((( ((((((((((((((((((
# .(((((((((((((((((((( .(((((((((((((((((
# ((((((((((((((((((((((( ((((((((((((((((/
# (((((((((((((((((((((((((((/ ,(((((((((((((((*
# .((((((((((((((/ /(((((((((((((. ,(((((((((((((((
# *(((((((((((((( ,(((((((((((((/ *((((((((((((((.
# ((((((((((((((, /(((((((((((((. ((((((((((((((,
# (((((((((((((/ ,(((((((((((((* ,(((((((((((((,
# *((((((((((((( .((((((((((((((( ,(((((((((((((
# ((((((((((((/ /((((((((((((((((((. ,((((((((((((/
# ((((((((((((( *(((((((((((((((((((((((* *((((((((((((
# ((((((((((((( ,(((((((((((((..((((((((((((( *((((((((((((
# ((((((((((((, /((((((((((((* /((((((((((((/ ((((((((((((
# ((((((((((((( /((((((((((((/ (((((((((((((* ((((((((((((
# (((((((((((((/ /(((((((((((( ,((((((((((((, *((((((((((((
# (((((((((((((( *(((((((((((/ *((((((((((((. ((((((((((((/
# *((((((((((((((((((((((((((, /(((((((((((((((((((((((((
# ((((((((((((((((((((((((( ((((((((((((((((((((((((,
# .(((((((((((((((((((((((/ ,(((((((((((((((((((((((
# ((((((((((((((((((((((/ ,(((((((((((((((((((((/
# *((((((((((((((((((((( (((((((((((((((((((((,
# ,(((((((((((((((((((((, ((((((((((((((((((((/
# ,(((((((((((((((((((((* /((((((((((((((((((((
# ((((((((((((((((((((((, ,/((((((((((((((((((((,
# ,(((((((((((((((((((((((((((((((((((((((((((((((((((
# .(((((((((((((((((((((((((((((((((((((((((((((
# .((((((((((((((((((((((((((((((((((((,.
# .,(((((((((((((((((((((((((.
#
###################################################################################
+339
View File
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
+57
View File
@@ -0,0 +1,57 @@
CONTENTS OF THIS FILE
---------------------
* Introduction
* Requirements
* Installation
* Configuration
* Maintainers
INTRODUCTION
------------
This module allows site administrators to grant specific roles the authority
to assign selected roles to users, without them needing
the administer permissions permission.
For each role, Role Delegation provides a new assign ROLE role permission to
allow the assignment of that role.
* For a full description of the module, visit the project page:
https://www.drupal.org/project/role_delegation
* To submit bug reports and feature suggestions, or track changes:
https://www.drupal.org/project/issues/role_delegation
REQUIREMENTS
------------
No special requirements.
INSTALLATION
------------
* Install as you would normally install a contributed Drupal module. Visit
https://www.drupal.org/node/1897420 for further information.
CONFIGURATION
-------------
1. Go to /admin/people/permissions and notice that for each role,
Role Delegation provides a new assign ROLE role permission to
allow the assignment of that role.
2. If an administrator has one of the the assign {{ role }} role permissions
or the assign all roles permission, a role assignment widget gets displayed
in the account creation or editing form, and bulk add/remove role operations
become available on the user administration page.
MAINTAINERS
-----------
Current maintainers:
* Jeroen Tubex - https://www.drupal.org/u/jeroent
* Ben Dougherty - https://www.drupal.org/u/benjy
+22
View File
@@ -0,0 +1,22 @@
{
"name": "drupal/role_delegation",
"description": "Allows site administrators to grant some roles the authority to assign selected roles to users.",
"type": "drupal-module",
"homepage": "http://drupal.org/project/role_delegation",
"require-dev": {
"drupal/action": "^0.2"
},
"authors": [
{
"name": "Jeroen Tubex",
"homepage": "https://www.drupal.org/u/jeroent",
"role": "Maintainer"
}
],
"support": {
"issues": "http://drupal.org/project/role_delegation",
"source": "https://git.drupalcode.org/project/role_delegation"
},
"license": "GPL-2.0-or-later",
"minimum-stability": "dev"
}
+16
View File
@@ -0,0 +1,16 @@
build:
assessment:
validate_codebase:
phpcs:
sniff-all-files: true
halt-on-fail: true
phpstan:
halt-on-fail: true
testing:
run_tests.standard:
types: 'PHPUnit-Unit,PHPUnit-Kernel,PHPUnit-Functional'
suppress-deprecations: false
run_tests.js:
concurrency: 1
types: 'PHPUnit-FunctionalJavascript'
suppress-deprecations: false
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

@@ -0,0 +1,12 @@
name: Role Delegation
type: module
description: 'Allows site administrators to grant some roles the authority to assign selected roles to users.'
package: Permissions
core_version_requirement: ^10.3 || ^11
dependencies:
- drupal:user
# Information added by Drupal.org packaging script on 2024-09-13
version: '8.x-1.3'
project: 'role_delegation'
datestamp: 1726236827
@@ -0,0 +1,4 @@
role_delegation.edit_form:
route_name: role_delegation.edit_form
base_route: entity.user.canonical
title: 'Roles'
@@ -0,0 +1,274 @@
<?php
/**
* @file
* Allows admins to grant roles the authority to assign selected roles to users.
*
* This module allows site administrators to grant some roles the authority to
* change roles assigned to users, without them needing the 'administer access
* control' permission.
*
* It provides its own tab in the user profile so that roles can be changed
* without needing access to the user edit form.
*/
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\role_delegation\DelegatableRoles;
use Drupal\role_delegation\Plugin\Action\RoleDelegationAddRoleUser;
use Drupal\role_delegation\Plugin\Action\RoleDelegationRemoveRoleUser;
use Drupal\user\Entity\Role;
use Drupal\user\Plugin\Action\AddRoleUser;
use Drupal\user\Plugin\Action\RemoveRoleUser;
use Drupal\user\RoleInterface;
use Drupal\user\UserInterface;
/**
* Implements hook_help().
*/
function role_delegation_help(string $route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.role_delegation':
$output = '<p>' . t('This module allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the <em>administer permissions</em> permission.') . '</p>';
$output .= '<p>' . t('It provides its own tab in the user profile so that roles can be assigned without needing access to the user edit form.') . '</p>';
return $output;
}
}
/**
* Implements hook_ENTITY_TYPE_delete().
*/
function role_delegation_user_role_delete(RoleInterface $entity) {
$permission = sprintf('assign %s role', $entity->id());
/** @var array $roles */
$roles = \Drupal::entityQuery('user_role')
->condition('permissions.*', $permission)
->condition('id', $entity->id(), '<>')
->accessCheck(FALSE)
->execute();
/** @var \Drupal\user\RoleInterface $role */
foreach (Role::loadMultiple($roles) as $role) {
$role->revokePermission($permission);
$role->save();
}
}
/**
* Implements hook_ENTITY_TYPE_presave().
*/
function role_delegation_user_presave(UserInterface $entity) {
if (!$entity->hasField('role_change')) {
return;
}
$submitted_roles = [];
foreach ($entity->role_change as $item) {
$submitted_roles[] = $item->target_id;
}
// Change roles based on the field for role delegation.
if ($submitted_roles !== DelegatableRoles::$emptyFieldValue) {
$current_user = \Drupal::currentUser();
$delegatable_roles = array_keys(\Drupal::service('delegatable_roles')
->getAssignableRoles($current_user));
// Of the roles that were submitted, only add ones that the user has access
// to use.
$add_roles = array_intersect($delegatable_roles, $submitted_roles);
foreach ($add_roles as $id) {
$entity->addRole($id);
}
// Any roles that the user has access to use and did not include in
// submission are removals.
$remove_roles = array_diff($delegatable_roles, $submitted_roles);
foreach ($remove_roles as $id) {
$entity->removeRole($id);
}
}
}
/**
* Implements hook_ENTITY_TYPE_load().
*/
function role_delegation_user_load(array $entities) {
// This is a workaround for known limitations of computed fields: since they
// are not stored, they are also not loaded with the user, so values must be
// manually supplied. This allows us to later determine that an empty field
// actually means intentional role removals, as opposed to field data not
// being sent/no access to field.
// Things may later with https://www.drupal.org/node/2392845.
foreach ($entities as $user_entity) {
if ($user_entity->hasField('role_change')) {
$user_entity->set('role_change', DelegatableRoles::$emptyFieldValue);
}
}
}
/**
* Implements hook_form_BASE_FORM_ID_alter().
*/
function role_delegation_form_user_form_alter(array &$form, FormStateInterface $form_state, string $form_id) {
// Add an entity builder for the user entity to ensure that it recieves the
// "empty" value when the field is not accessible.
if (isset($form['role_change'])) {
$form['role_change']['#group'] = 'account';
$form['#entity_builders'][] = 'role_delegation_user_form_builder';
}
}
/**
* Implements hook_field_widget_single_element_form_alter().
*/
function role_delegation_field_widget_single_element_form_alter(array &$element, FormStateInterface $form_state, array $context) {
/** @var \Drupal\Core\Field\FieldItemListInterface $items */
$items = $context['items'];
/** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
$field_definition = $items->getFieldDefinition();
// Since the field is computed, the default value of the form element will be
// empty, so we need to adjust it.
if ($field_definition->getTargetEntityTypeId() === 'user' && $field_definition->getName() === 'role_change' && isset($element['#options'])) {
$roles_current = $items->getEntity()->getRoles();
$roles_options = array_keys($element['#options']);
$element['#default_value'] = array_intersect($roles_current, $roles_options);
}
}
/**
* Implements hook_options_list_alter().
*/
function role_delegation_options_list_alter(array &$options, array $context) {
/** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
$field_definition = $context['fieldDefinition'];
// By default, ALL the entities for a given type will be used for the options
// on an enity reference field, but we only want the user to be able to choose
// from the roles they can assign.
if ($field_definition->getTargetEntityTypeId() === 'user' && $field_definition->getName() === 'role_change') {
$current_user = \Drupal::currentUser();
$options = \Drupal::service('delegatable_roles')
->getAssignableRoles($current_user);
}
}
/**
* Entity builder for the user form with empty field value for "role_change".
*
* @see role_delegation_form_alter()
*/
function role_delegation_user_form_builder(string $entity_type, UserInterface $user, array &$form, FormStateInterface $form_state) {
// If the user has no access to the "role_change" field, then the form will
// submit an empty array for the field, which will make later processing think
// it was intentional. Set it to the empty field value to correct this.
if (!isset($form['role_change']['#access']) || !$form['role_change']['#access']) {
$user->set('role_change', DelegatableRoles::$emptyFieldValue);
}
}
/**
* Implements hook_entity_base_field_info().
*/
function role_delegation_entity_base_field_info(EntityTypeInterface $entity_type) {
$fields = [];
if ($entity_type->id() === 'user') {
$fields['role_change'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Roles'))
->setSetting('target_type', 'user_role')
->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
->setComputed(TRUE)
->setDisplayOptions('form', [
'type' => 'options_buttons',
'weight' => 1,
])
->setSetting('handler', 'role_change:user_role')
->setDefaultValue(DelegatableRoles::$emptyFieldValue);
}
return $fields;
}
/**
* Implements hook_entity_field_access().
*/
function role_delegation_entity_field_access(string $operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
if ($operation === 'edit' && $field_definition->getName() === 'role_change' && $field_definition->getTargetEntityTypeId() === 'user') {
// Deny access if the user has access to the normal roles field.
if ($account->hasPermission('administer permissions')) {
return AccessResult::forbidden()->cachePerPermissions();
}
// Or if they don't have at least one role that allows them to delegate.
$permissions = \Drupal::service('permission_generator.role_delegation')
->rolePermissions();
$permissions = array_merge(['assign all roles'], array_keys($permissions));
foreach ($permissions as $permission) {
if ($account->hasPermission($permission)) {
return AccessResult::allowed()->cachePerPermissions();
}
}
return AccessResult::forbidden()->cachePerPermissions();
}
return AccessResult::neutral();
}
/**
* Implements hook_entity_operation().
*/
function role_delegation_entity_operation(EntityInterface $entity) {
$operations = [];
if (!$entity instanceof UserInterface) {
return $operations;
}
$url = Url::fromRoute('role_delegation.edit_form', [
'user' => $entity->id(),
]);
// Check if the current user has access to the role_delegation edit form.
if ($url->access()) {
$operations['role_delegation'] = [
'title' => t('Roles'),
'weight' => 210,
'url' => $url,
];
}
return $operations;
}
/**
* Implements hook_views_data_alter().
*/
function role_delegation_views_data_alter(array &$data) {
$data['users']['user_bulk_form']['field']['id'] = 'role_delegation_user_bulk_form';
}
/**
* Implements hook_action_info_alter().
*/
function role_delegation_action_info_alter(&$definitions) {
// Override the addRoleUser and RemoveRoleUser action, so those actions also
// work without the 'administer users' permission. If another module has
// already swapped out those classes, though, we'll be polite and do nothing.
foreach ($definitions as &$definition) {
if ($definition['id'] === 'user_add_role_action' && $definition['class'] === AddRoleUser::class) {
$definition['class'] = RoleDelegationAddRoleUser::class;
}
if ($definition['id'] === 'user_remove_role_action' && $definition['class'] === RemoveRoleUser::class) {
$definition['class'] = RoleDelegationRemoveRoleUser::class;
}
}
}
@@ -0,0 +1,7 @@
assign all roles:
title: 'Assign all roles'
description: 'Access permission for assigning all roles.'
restrict access: TRUE
permission_callbacks:
- permission_generator.role_delegation::rolePermissions
@@ -0,0 +1,9 @@
role_delegation.edit_form:
path: '/user/{user}/roles'
defaults:
_form: 'Drupal\role_delegation\Form\RoleDelegationSettingsForm'
_title: 'Roles'
requirements:
_role_delegation_access_check: 'TRUE'
options:
_admin_route: TRUE
@@ -0,0 +1,11 @@
services:
access_check.role_delegation:
class: Drupal\role_delegation\Access\RoleDelegationAccessCheck
arguments: ['@permission_generator.role_delegation', '@current_user']
tags:
- { name: access_check, applies_to: _role_delegation_access_check }
delegatable_roles:
class: Drupal\role_delegation\DelegatableRoles
permission_generator.role_delegation:
class: Drupal\role_delegation\PermissionGenerator
arguments: ['@delegatable_roles']
@@ -0,0 +1,76 @@
<?php
namespace Drupal\role_delegation\Access;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Access\AccessResultInterface;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\role_delegation\PermissionGenerator;
/**
* Checks access for displaying configuration edit user pages.
*/
class RoleDelegationAccessCheck implements AccessInterface {
/**
* The permission generator service.
*
* @var \Drupal\role_delegation\PermissionGenerator
*/
protected $permissionGenerator;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountProxyInterface
*/
protected $currentUser;
/**
* The Role Delegation access check.
*
* @param \Drupal\role_delegation\PermissionGenerator $permission_generator
* The role delegation service.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
*/
public function __construct(PermissionGenerator $permission_generator, AccountInterface $current_user) {
$this->permissionGenerator = $permission_generator;
$this->currentUser = $current_user;
}
/**
* Custom access check for the /user/%/roles page.
*
* @param \Drupal\Core\Session\AccountInterface|null $account
* Run access checks for this account.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*/
public function access(AccountInterface $account = NULL): AccessResultInterface {
if ($account === NULL) {
$account = $this->currentUser;
}
// No need for this access when the current user has the 'administer users'
// permission. Roles can be edited on the user edit page.
if ($account->hasPermission('administer users')) {
return AccessResult::neutral()->cachePerPermissions();
}
// If the user has any of the "assign custom role" permissions then we give
// them access to the form.
foreach ($this->permissionGenerator->rolePermissions() as $perm => $title) {
if ($account->hasPermission($perm)) {
return AccessResult::allowed()->cachePerPermissions();
}
}
// If the user can administer all permissions then they can also view the
// roles page.
return AccessResult::allowedIfHasPermission($account, 'assign all roles');
}
}
@@ -0,0 +1,46 @@
<?php
namespace Drupal\role_delegation;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\user\Entity\Role;
use Drupal\user\RoleInterface;
/**
* Helper Service that loads all assignable roles for the given user.
*/
class DelegatableRoles implements DelegatableRolesInterface {
use StringTranslationTrait;
/**
* A value used to indicate that nothing has been submitted.
*
* @var array
*/
public static $emptyFieldValue = ['__role_delegation_empty_field_value__'];
/**
* {@inheritdoc}
*/
public function getAssignableRoles(AccountInterface $account): array {
$assignable_roles = [];
foreach ($this->getAllRoles() as $role) {
if ($account->hasPermission('assign all roles') || $account->hasPermission(sprintf('assign %s role', $role->id()))) {
$assignable_roles[$role->id()] = $role->label();
}
}
return $assignable_roles;
}
/**
* {@inheritdoc}
*/
public function getAllRoles(): array {
$all_roles = Role::loadMultiple();
unset($all_roles[RoleInterface::ANONYMOUS_ID], $all_roles[RoleInterface::AUTHENTICATED_ID]);
return $all_roles;
}
}
@@ -0,0 +1,31 @@
<?php
namespace Drupal\role_delegation;
use Drupal\Core\Session\AccountInterface;
/**
* Interface for the delegatable roles service.
*/
interface DelegatableRolesInterface {
/**
* Gets the roles a user is allowed to assing.
*
* @param \Drupal\Core\Session\AccountInterface $account
* The account for which you want to know which roles they can assign.
*
* @return array
* An array of roles with machine names as keys and labels as values.
*/
public function getAssignableRoles(AccountInterface $account): array;
/**
* Gets all roles apart from anonymous and authenticated.
*
* @return \Drupal\user\RoleInterface[]
* An array of role objects.
*/
public function getAllRoles(): array;
}
@@ -0,0 +1,115 @@
<?php
namespace Drupal\role_delegation\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\role_delegation\DelegatableRolesInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Configure book settings for this site.
*/
class RoleDelegationSettingsForm extends FormBase {
/**
* The current user viewing the form.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* The role delegation service.
*
* @var \Drupal\role_delegation\DelegatableRolesInterface
*/
protected $delegatableRoles;
/**
* The roles page setting form.
*
* @param \Drupal\role_delegation\DelegatableRolesInterface $delegatable_roles
* The role delegation service.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user viewing the form.
*/
public function __construct(DelegatableRolesInterface $delegatable_roles, AccountInterface $current_user) {
$this->delegatableRoles = $delegatable_roles;
$this->currentUser = $current_user;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('delegatable_roles'),
$container->get('current_user')
);
}
/**
* {@inheritdoc}
*/
public function getFormId(): string {
return 'role_delegation_role_assign_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, AccountInterface $user = NULL): array {
if (!$user instanceof AccountInterface) {
return $form;
}
$current_roles = $user->getRoles(TRUE);
$current_roles = array_combine($current_roles, $current_roles);
$form['account']['role_change'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Roles'),
'#options' => $this->delegatableRoles->getAssignableRoles($this->currentUser),
'#default_value' => $current_roles,
'#description' => $this->t('Change roles assigned to user.'),
];
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Save'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state): void {
/** @var \Drupal\user\UserInterface $account */
$account = $form_state->getBuildInfo()['args'][0];
// Make sure this functionality works when single_user_role is enabled.
// This module can change the role_change form element to a select or
// radio buttons, which will return an single value instead of the default
// checkboxes.
$assigned_roles = is_array($form_state->getValue('role_change')) ? $form_state->getValue('role_change') : [$form_state->getValue('role_change') => $form_state->getValue('role_change')];
$assignable_roles = $this->delegatableRoles->getAssignableRoles($this->currentUser);
$roles = [];
foreach ($assignable_roles as $rid => $assignable_role) {
$roles[$rid] = isset($assigned_roles[$rid]) && !empty($assigned_roles[$rid]) ? $rid : 0;
}
foreach ($roles as $rid => $value) {
empty($value) === TRUE ? $account->removeRole($rid) : $account->addRole($rid);
}
$account->save();
$this->messenger()->addStatus($this->t('The roles have been updated.'));
}
}
@@ -0,0 +1,48 @@
<?php
namespace Drupal\role_delegation;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* The PermissionGenerator class.
*/
class PermissionGenerator {
use StringTranslationTrait;
/**
* The delegatable role service for getting all the roles.
*
* @var \Drupal\role_delegation\DelegatableRolesInterface
*/
protected $delegatableRoles;
/**
* Construct a new permission generator.
*
* @param \Drupal\role_delegation\DelegatableRolesInterface $delegatable_roles
* The delegatable roles service.
*/
public function __construct(DelegatableRolesInterface $delegatable_roles) {
$this->delegatableRoles = $delegatable_roles;
}
/**
* Returns an array of permissions to assign specific roles.
*
* @return array
* An array of permissions in the correct format for permission_callbacks.
*/
public function rolePermissions(): array {
$permissions = [];
foreach ($this->delegatableRoles->getAllRoles() as $rid => $role) {
$permissions[sprintf('assign %s role', $rid)] = [
'title' => $this->t('Assign %role role', ['%role' => $role->label()]),
];
}
return $permissions;
}
}
@@ -0,0 +1,65 @@
<?php
namespace Drupal\role_delegation\Plugin\Action;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\role_delegation\Access\RoleDelegationAccessCheck;
use Drupal\user\Plugin\Action\AddRoleUser;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Alternate action plugin for 'user_add_role_action'.
*
* This plugin makes sure the add role action also works without
* the 'administer users' permission.
*
* @see \Drupal\user\Plugin\Action\AddRoleUser
*/
class RoleDelegationAddRoleUser extends AddRoleUser {
/**
* The role delegation access checker.
*
* @var \Drupal\role_delegation\Access\RoleDelegationAccessCheck
*/
protected $roleDelegationAccessCheck;
/**
* {@inheritdoc}
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeInterface $entity_type, RoleDelegationAccessCheck $roleDelegationAccessCheck) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type);
$this->roleDelegationAccessCheck = $roleDelegationAccessCheck;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager')->getDefinition('user_role'),
$container->get('access_check.role_delegation')
);
}
/**
* {@inheritdoc}
*/
public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
$access = parent::access($object, $account, $return_as_object);
// If access == true, the user already has the administer users permission.
if ($access === TRUE) {
return $access;
}
// Check if the user has access to add the role to the user.
return $this->roleDelegationAccessCheck->access($account);
}
}
@@ -0,0 +1,65 @@
<?php
namespace Drupal\role_delegation\Plugin\Action;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\role_delegation\Access\RoleDelegationAccessCheck;
use Drupal\user\Plugin\Action\RemoveRoleUser;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Alternate action plugin for 'user_remove_role_action'.
*
* This plugin makes sure the remove role action also works without
* the 'administer users' permission.
*
* @see \Drupal\user\Plugin\Action\RemoveRoleUser
*/
class RoleDelegationRemoveRoleUser extends RemoveRoleUser {
/**
* The role delegation access checker.
*
* @var \Drupal\role_delegation\Access\RoleDelegationAccessCheck
*/
protected $roleDelegationAccessCheck;
/**
* {@inheritdoc}
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeInterface $entity_type, RoleDelegationAccessCheck $roleDelegationAccessCheck) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type);
$this->roleDelegationAccessCheck = $roleDelegationAccessCheck;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager')->getDefinition('user_role'),
$container->get('access_check.role_delegation')
);
}
/**
* {@inheritdoc}
*/
public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
$access = parent::access($object, $account, $return_as_object);
// If access == true, the user already has the administer users permission.
if ($access === TRUE) {
return $access;
}
// Check if the user has access to remove the role from the user.
return $this->roleDelegationAccessCheck->access($account);
}
}
@@ -0,0 +1,34 @@
<?php
namespace Drupal\role_delegation\Plugin\EntityReferenceSelection;
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;
use Drupal\role_delegation\DelegatableRoles;
/**
* Entity reference implementation for the role_change field.
*
* @EntityReferenceSelection(
* id = "role_change:user_role",
* label = @Translation("Role change"),
* entity_types = {"user_role"},
* group = "role_change",
* weight = 0,
* )
*/
class RoleChangeSelection extends DefaultSelection {
/**
* {@inheritdoc}
*/
public function validateReferenceableEntities(array $ids): array {
$result = parent::validateReferenceableEntities($ids);
if ($ids) {
$result = array_merge($result, DelegatableRoles::$emptyFieldValue);
}
return $result;
}
}
@@ -0,0 +1,85 @@
<?php
namespace Drupal\role_delegation\Plugin\views\field;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Routing\ResettableStackedRouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\Plugin\views\field\UserBulkForm;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\ViewExecutable;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Defines a user operations bulk form element.
*
* @ViewsField("role_delegation_user_bulk_form")
*/
class RoleDelegationUserBulkForm extends UserBulkForm {
/**
* The currently logged in user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* {@inheritdoc}
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, LanguageManagerInterface $language_manager, MessengerInterface $messenger, EntityRepositoryInterface $entity_repository, ResettableStackedRouteMatchInterface $route_match, AccountInterface $currentUser) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $language_manager, $messenger, $entity_repository, $route_match);
$this->currentUser = $currentUser;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager'),
$container->get('language_manager'),
$container->get('messenger'),
$container->get('entity.repository'),
$container->get('current_route_match'),
$container->get('current_user'),
);
}
/**
* {@inheritdoc}
*/
public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
parent::init($view, $display, $options);
$entity_type = $this->getEntityType();
// Filter the actions to only include those for this entity type.
/** @var \Drupal\system\ActionConfigEntityInterface[] $actions */
$actions = $this->actionStorage->loadMultiple();
$this->actions = array_filter($actions, function ($action) use ($entity_type) {
$plugin_definition = $action->getPluginDefinition();
if ('user' === $action->getType() && in_array($plugin_definition['id'], [
'user_add_role_action',
'user_remove_role_action',
])) {
$collections = $action->getPluginCollections();
$collection = reset($collections);
$configuration = $collection->getConfiguration();
return $this->currentUser->hasPermission('assign all roles') || $this->currentUser->hasPermission(sprintf('assign %s role', $configuration['rid']));
}
else {
return $action->getType() == $entity_type;
}
});
}
}
@@ -0,0 +1,211 @@
<?php
namespace Drupal\Tests\role_delegation\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Functional tests for assigning roles.
*
* @group role_delegation
*/
class RoleAssignTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['user', 'role_delegation', 'node'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Ensure we can only see the roles we have permission to assign.
*/
public function testRoleAccess() {
$rid1 = $this->drupalCreateRole([]);
$rid2 = $this->drupalCreateRole([]);
$rid3 = $this->drupalCreateRole([]);
// Only 2 of the 3 roles appear on the roles edit page.
$current_user = $this->drupalCreateUser([
sprintf('assign %s role', $rid1),
sprintf('assign %s role', $rid2),
]);
$this->drupalLogin($current_user);
$account = $this->drupalCreateUser();
$this->drupalGet(sprintf('/user/%s/roles', $account->id()));
$this->assertSession()->fieldExists(sprintf('role_change[%s]', $rid1));
$this->assertSession()->fieldExists(sprintf('role_change[%s]', $rid2));
$this->assertSession()->fieldNotExists(sprintf('role_change[%s]', $rid3));
// A user who can access the real roles field should not see the role
// delegation field.
$current_user = $this->drupalCreateUser([
'administer users',
'administer permissions',
'assign all roles',
]);
$this->drupalLogin($current_user);
$this->drupalGet(sprintf('/user/%s/edit', $account->id()));
$this->assertSession()->fieldExists(sprintf('roles[%s]', $rid1));
$this->assertSession()->fieldNotExists(sprintf('role_change[%s]', $rid1));
// A user who can edit a user, but does not have access to the real role
// field, but can delegate should see the role delegation field.
$current_user = $this->drupalCreateUser([
'administer users',
'assign all roles',
]);
$this->drupalLogin($current_user);
$this->drupalGet(sprintf('/user/%s/edit', $account->id()));
$this->assertSession()->fieldNotExists(sprintf('roles[%s]', $rid1), NULL);
$this->assertSession()->fieldExists(sprintf('role_change[%s]', $rid1));
// Similar, but single role permissions rather than assigning all roles.
$current_user = $this->drupalCreateUser([
'administer users',
sprintf('assign %s role', $rid1),
]);
$this->drupalLogin($current_user);
$this->drupalGet(sprintf('/user/%s/edit', $account->id()));
$this->assertSession()->fieldNotExists(sprintf('roles[%s]', $rid1), NULL);
$this->assertSession()->fieldExists(sprintf('role_change[%s]', $rid1));
$this->assertSession()->fieldNotExists(sprintf('role_change[%s]', $rid2), NULL);
}
/**
* Test that we can assign roles we have access to via the Roles form.
*/
public function testRoleAssignRolesForm() {
$user_storage = \Drupal::entityTypeManager()->getStorage('user');
// Create a role and login as a user with the permission to assign it.
$rid1 = $this->drupalCreateRole([]);
$rid2 = $this->drupalCreateRole([]);
$current_user = $this->drupalCreateUser([
sprintf('assign %s role', $rid1),
sprintf('assign %s role', $rid2),
]);
$this->drupalLogin($current_user);
// Go to the users roles edit page.
$account = $this->drupalCreateUser();
$this->drupalGet(sprintf('/user/%s/roles', $account->id()));
// The form element field id and name.
$field_id = sprintf('edit-role-change-%s', $rid1);
$field_name = sprintf('role_change[%s]', $rid1);
// Ensure its disabled by default.
$this->assertSession()->checkboxNotChecked($field_id);
self::assertFalse($account->hasPermission('assign $rid1 role'), 'The target user does not have the role by default.');
$this->assertSession()->checkboxNotChecked($field_id);
// Assign the role and ensure its now checked and assigned.
$this->submitForm([$field_name => $rid1], 'Save');
$user_storage->resetCache();
$account = $user_storage->load($account->id());
self::assertTrue($account->hasRole($rid1), 'The target user has been granted the role.');
$this->assertSession()->checkboxChecked($field_id);
// Revoke the role.
$this->submitForm([$field_name => FALSE], 'Save');
$user_storage->resetCache();
$account = $user_storage->load($account->id());
self::assertFalse($account->hasRole($rid1), 'The target user has gotten the role revoked.');
$this->assertSession()->checkboxNotChecked($field_id);
}
/**
* Test that we can assign roles we have access to via the user edit form.
*/
public function testRoleAssignUserForm() {
$user_storage = \Drupal::entityTypeManager()->getStorage('user');
$rid1 = $this->drupalCreateRole([]);
$current_user = $this->drupalCreateUser([
'administer users',
'assign all roles',
]);
$this->drupalLogin($current_user);
// Go to the users roles edit page.
$account = $this->drupalCreateUser();
$this->drupalGet(sprintf('/user/%s/edit', $account->id()));
// The form element field id and name.
$field_id = sprintf('edit-role-change-%s', $rid1);
$field_name = sprintf('role_change[%s]', $rid1);
// Ensure its disabled by default.
self::assertFalse($account->hasPermission(sprintf('assign %s role', $rid1)), 'The target user does not have the role by default.');
$this->assertSession()->checkboxNotChecked($field_id);
// Assign the role and ensure its now checked and assigned.
$this->submitForm([$field_name => $rid1], 'Save');
$user_storage->resetCache();
$account = $user_storage->load($account->id());
self::assertTrue($account->hasRole($rid1), 'The target user has been granted the role.');
$this->assertSession()->checkboxChecked($field_id);
// Revoke the role.
$this->submitForm([$field_name => FALSE], 'Save');
$user_storage->resetCache();
$account = $user_storage->load($account->id());
self::assertFalse($account->hasRole($rid1), 'The target user has gotten the role revoked.');
$this->assertSession()->checkboxNotChecked($field_id);
}
/**
* Test that the user has access to the role delegation page.
*/
public function testRoleDelegationPageAccess() {
$regular_user = $this->drupalCreateUser();
// Anonymous users can never access the roles page.
$this->drupalGet(sprintf('/user/%s/roles', $regular_user->id()));
$this->assertSession()->statusCodeEquals(403);
// Users with 'administer users' cannot view the page, they must use
// the normal user edit page or also 'have assign all roles'.
$account = $this->createUser(['administer users']);
$this->drupalLogin($account);
$this->drupalGet(sprintf('/user/%s/roles', $regular_user->id()));
$this->assertSession()->statusCodeEquals(403);
// Users with 'administer permissions' cannot view the page, they must use
// the normal user edit page or also 'have assign all roles'.
$account = $this->createUser(['administer permissions']);
$this->drupalLogin($account);
$this->drupalGet(sprintf('/user/%s/roles', $regular_user->id()));
$this->assertSession()->statusCodeEquals(403);
// Users with a custom 'assign %custom role' permission should be able to
// see the role admin page.
$role = $this->createRole([]);
$account = $this->createUser([sprintf('assign %s role', $role)]);
$this->drupalLogin($account);
$this->drupalGet(sprintf('/user/%s/roles', $regular_user->id()));
$this->assertSession()->statusCodeEquals(200);
// Users with 'assign all roles' can view the page.
$account = $this->createUser(['assign all roles']);
$this->drupalLogin($account);
$this->drupalGet(sprintf('/user/%s/roles', $regular_user->id()));
$this->assertSession()->statusCodeEquals(200);
}
/**
* Test access to the "Roles" entity operation.
*/
public function testRoleDelegationEntityOperationAccess() {
// Make sure the entity operation is only added to users.
$node = $this->drupalCreateNode();
$this->drupalGet('/admin/content');
$this->assertSession()->linkByHrefNotExists(sprintf('/user/%s/roles', $node->id()));
}
}
@@ -0,0 +1,141 @@
<?php
namespace Drupal\Tests\role_delegation\Functional\Views;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\system\Entity\Action;
use Drupal\Tests\BrowserTestBase;
use Drupal\views\Entity\View;
/**
* Functional tests for assigning roles in vbo.
*
* @group role_delegation
*/
class RoleDelegationBulkOperationsTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['action', 'user', 'role_delegation', 'views'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Test if a user is able to edit the allowed roles in VBO.
*/
public function testVboRoleDelegation(): void {
$rid1 = $this->drupalCreateRole([]);
$rid2 = $this->drupalCreateRole([]);
$rid3 = $this->drupalCreateRole([]);
// User that can assign all roles.
$account = $this->createUser(['administer users', 'assign all roles']);
$this->drupalLogin($account);
$this->drupalGet('/admin/people');
$this->assertSession()->optionExists('action', sprintf('user_add_role_action.%s', $rid1));
$this->assertSession()->optionExists('action', sprintf('user_add_role_action.%s', $rid2));
$this->assertSession()->optionExists('action', sprintf('user_add_role_action.%s', $rid3));
$this->assertSession()->optionExists('action', sprintf('user_remove_role_action.%s', $rid1));
$this->assertSession()->optionExists('action', sprintf('user_remove_role_action.%s', $rid2));
$this->assertSession()->optionExists('action', sprintf('user_remove_role_action.%s', $rid3));
// User that can assign only role 1.
$account = $this->createUser([
'administer users',
sprintf('assign %s role', $rid1),
]);
$this->drupalLogin($account);
$this->drupalGet('/admin/people');
$this->assertSession()->optionExists('action', sprintf('user_add_role_action.%s', $rid1));
$this->assertSession()->optionNotExists('action', sprintf('user_add_role_action.%s', $rid2));
$this->assertSession()->optionNotExists('action', sprintf('user_add_role_action.%s', $rid3));
$this->assertSession()->optionExists('action', sprintf('user_remove_role_action.%s', $rid1));
$this->assertSession()->optionNotExists('action', sprintf('user_remove_role_action.%s', $rid2));
$this->assertSession()->optionNotExists('action', sprintf('user_remove_role_action.%s', $rid3));
// User that can assign role 2 and role 3.
$account = $this->createUser([
'administer users',
sprintf('assign %s role', $rid2),
sprintf('assign %s role', $rid3),
]);
$this->drupalLogin($account);
$this->drupalGet('/admin/people');
$this->assertSession()->optionNotExists('action', sprintf('user_add_role_action.%s', $rid1));
$this->assertSession()->optionExists('action', sprintf('user_add_role_action.%s', $rid2));
$this->assertSession()->optionExists('action', sprintf('user_add_role_action.%s', $rid3));
$this->assertSession()->optionNotExists('action', sprintf('user_remove_role_action.%s', $rid1));
$this->assertSession()->optionExists('action', sprintf('user_remove_role_action.%s', $rid2));
$this->assertSession()->optionExists('action', sprintf('user_remove_role_action.%s', $rid3));
}
/**
* Test VBO still works without the "administer users" permission.
*/
public function testVboRoleDelegationWithoutAdministerUsersPermission(): void {
/** @var \Drupal\views\Entity\View $view */
$view = View::load('user_admin_people');
$display = &$view->getDisplay('default');
$display['display_options']['access']['options']['perm'] = 'access administration pages';
$view->save();
$this->container->get('router.builder')->rebuildIfNeeded();
$rid1 = $this->drupalCreateRole([]);
$rid2 = $this->drupalCreateRole([]);
$account = $this->createUser([
'access administration pages',
sprintf('assign %s role', $rid1),
sprintf('assign %s role', $rid2),
]);
$this->drupalLogin($account);
$this->drupalGet('/admin/people');
$this->assertSession()->statusCodeEquals(200);
$this->submitForm([
'action' => 'user_add_role_action.' . $rid1,
'user_bulk_form[1]' => TRUE,
],
'Apply to selected items'
);
$add_action = Action::load('user_add_role_action.' . $rid1);
$this->assertSession()->responseNotContains(new FormattableMarkup('No access to execute %action on the @entity_type_label %entity_label.', [
'%action' => $add_action->label(),
'@entity_type_label' => 'User',
'%entity_label' => $account->label(),
]));
$this->assertSession()->responseContains(new FormattableMarkup('%action was applied to @count item.', [
'%action' => $add_action->label(),
'@count' => 1,
]));
$this->submitForm([
'action' => 'user_remove_role_action.' . $rid2,
'user_bulk_form[1]' => TRUE,
],
'Apply to selected items'
);
$remove_action = Action::load('user_remove_role_action.' . $rid2);
$this->assertSession()->responseNotContains(new FormattableMarkup('No access to execute %action on the @entity_type_label %entity_label.', [
'%action' => $remove_action->label(),
'@entity_type_label' => 'User',
'%entity_label' => $account->label(),
]));
$this->assertSession()->responseContains(new FormattableMarkup('%action was applied to @count item.', [
'%action' => $remove_action->label(),
'@count' => 1,
]));
}
}
@@ -0,0 +1,71 @@
<?php
namespace Drupal\Tests\role_delegation\Kernel;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\user\Traits\UserCreationTrait;
/**
* @coversDefaultClass \Drupal\role_delegation\Access\RoleDelegationAccessCheck
*
* @group role_delegation
*/
class AccessTest extends KernelTestBase {
use UserCreationTrait;
/**
* The modules to enable for this test.
*
* @var array
*/
protected static $modules = ['system', 'role_delegation', 'user'];
/**
* The Role Delegation access checker.
*
* @var \Drupal\role_delegation\Access\RoleDelegationAccessCheck
*/
protected $accessChecker;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installSchema('system', 'sequences');
$this->installEntitySchema('user');
$this->accessChecker = $this->container->get('access_check.role_delegation');
// User 1 is still a super user so we create that user first so moving
// forward we're just using normal users.
$this->createUser();
}
/**
* Test the access checker for user/%/roles.
*
* @covers ::access
*/
public function testRoleDelegationAccess() {
// Anonymous users can never access the roles page.
$account = $this->createUser();
$this->assertEquals(FALSE, $this->accessChecker->access($account)->isAllowed());
// Users with "administer permissions" cannot view the page, they must use
// the normal user edit page or also "have assign all roles".
$account = $this->createUser(['administer permissions']);
$this->assertEquals(FALSE, $this->accessChecker->access($account)->isAllowed());
// Users with a custom "assign %custom role" permission should be able to
// see the role admin page.
$role = $this->createRole([]);
$account = $this->createUser([sprintf('assign %s role', $role)]);
$this->assertEquals(TRUE, $this->accessChecker->access($account)->isAllowed());
// Users with 'assign all roles' can view the page.
$account = $this->createUser(['assign all roles']);
$this->assertEquals(TRUE, $this->accessChecker->access($account)->isAllowed());
}
}
@@ -0,0 +1,96 @@
<?php
namespace Drupal\Tests\role_delegation\Kernel;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\user\Traits\UserCreationTrait;
use Drupal\user\Entity\Role;
/**
* @coversDefaultClass \Drupal\role_delegation\DelegatableRoles
*
* @group role_delegation
*/
class DelegatableRolesTest extends KernelTestBase {
use UserCreationTrait;
/**
* The modules to enable for this test.
*
* @var array
*/
protected static $modules = ['system', 'role_delegation', 'user'];
/**
* The Role Delegation service.
*
* @var \Drupal\role_delegation\DelegatableRolesInterface
*/
protected $delegatableRoles;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installSchema('system', 'sequences');
$this->installEntitySchema('user');
$this->delegatableRoles = $this->container->get('delegatable_roles');
// User 1 is still a super user so we create that user first so moving
// forward we're just using normal users.
$this->createUser();
}
/**
* Test the roles that can be assigned by a given user.
*
* @covers ::getAssignableRoles
*/
public function testAssignableRoles() {
$rid1 = $this->createRole([]);
$rid2 = $this->createRole([]);
$rid3 = $this->createRole([]);
// Test the 'assign all roles permission'. We have to merge in the roles of
// the account as well because createUser() creates a new role.
$account = $this->createUser(['assign all roles']);
$this->assertEquals(array_merge([$rid1, $rid2, $rid3], $account->getRoles(TRUE)), array_keys($this->delegatableRoles->getAssignableRoles($account)));
// If they have these two roles, they can assign exactly those two roles.
$account = $this->createUser(["assign $rid1 role", "assign $rid2 role"]);
$this->assertEquals([$rid1, $rid2], array_keys($this->delegatableRoles->getAssignableRoles($account)));
// Doesn't matter what permissions they have here, they can never assign
// anonymous or authenticated roles.
$account = $this->createUser(['administer users', 'administer permissions']);
$this->assertEquals([], $this->delegatableRoles->getAssignableRoles($account));
}
/**
* Test the all roles methods filters special roles.
*
* @covers ::getAllRoles
*/
public function testGetAllRoles() {
$rid1 = $this->createRole([]);
$rid2 = $this->createRole([]);
$this->assertEquals([$rid1, $rid2], array_keys($this->delegatableRoles->getAllRoles()));
}
/**
* Deleting a role revokes the permission allowing users to assign the role.
*/
public function testDeleteRole() {
$rid = $this->createRole([]);
$permission = "assign $rid role";
$account = $this->createUser([$permission]);
$this->assertTrue($account->hasPermission($permission), sprintf('User has "%s" permission.', $permission));
// Delete the role and ensure the user no longer has the permission.
Role::load($rid)->delete();
$this->assertFalse($account->hasPermission($permission), sprintf('User no longer has "%s" permission.', $permission));
}
}