Jun 06, 2019 in Drupal 8, Snippets

When you give users the permission to administer users and assign roles, there is a security implication in that users with this permission can add the role 'administrator' role to any user. With the following snippet you disallow access to this option for logged in users with the role of "editor". This is to prevent unnessecary usage of contrib!

/*
 * Allow adding roles in user registration form
 */
function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $current_user = \Drupal::currentUser();
  $roles = $current_user->getRoles();
  if(!in_array('administrator', $roles)) {
    unset($form['account']['roles']['#options']['administrator']);
    unset($form['account']['roles']['#options']['authenticated']);
    $form['account']['roles']['#access'] = TRUE;
  }
}

Now the editor user can only give the role of "editor" (or other specified roles) to other users.