class UserRegistrationResource
Represents user registration as a resource.
Attributes
#[RestResource(id: "user_registration", label: new TranslatableMarkup("User registration"), serialization_class: User::class, uri_paths: [
"create" => "/user/register",
])]
  Hierarchy
- class \Drupal\Component\Plugin\PluginBase implements \Drupal\Component\Plugin\PluginInspectionInterface, \Drupal\Component\Plugin\DerivativeInspectionInterface
- class \Drupal\Core\Plugin\PluginBase uses \Drupal\Core\StringTranslation\StringTranslationTrait, \Drupal\Core\DependencyInjection\DependencySerializationTrait, \Drupal\Core\Messenger\MessengerTrait extends \Drupal\Component\Plugin\PluginBase
- class \Drupal\rest\Plugin\ResourceBase implements \Drupal\Core\Plugin\ContainerFactoryPluginInterface, \Drupal\rest\Plugin\ResourceInterface extends \Drupal\Core\Plugin\PluginBase
- class \Drupal\user\Plugin\rest\resource\UserRegistrationResource uses \Drupal\rest\Plugin\rest\resource\EntityResourceValidationTrait, \Drupal\rest\Plugin\rest\resource\EntityResourceAccessTrait extends \Drupal\rest\Plugin\ResourceBase
 
 
 - class \Drupal\rest\Plugin\ResourceBase implements \Drupal\Core\Plugin\ContainerFactoryPluginInterface, \Drupal\rest\Plugin\ResourceInterface extends \Drupal\Core\Plugin\PluginBase
 
 - class \Drupal\Core\Plugin\PluginBase uses \Drupal\Core\StringTranslation\StringTranslationTrait, \Drupal\Core\DependencyInjection\DependencySerializationTrait, \Drupal\Core\Messenger\MessengerTrait extends \Drupal\Component\Plugin\PluginBase
 
Expanded class hierarchy of UserRegistrationResource
1 file declares its use of UserRegistrationResource
- UserRegistrationResourceTest.php in core/
modules/ user/ tests/ src/ Unit/ UserRegistrationResourceTest.php  
File
- 
              core/
modules/ user/ src/ Plugin/ rest/ resource/ UserRegistrationResource.php, line 25  
Namespace
Drupal\user\Plugin\rest\resourceView source
class UserRegistrationResource extends ResourceBase {
  use EntityResourceValidationTrait;
  use EntityResourceAccessTrait;
  
  /**
   * User settings config instance.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $userSettings;
  
  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;
  
  /**
   * The password generator.
   *
   * @var \Drupal\Core\Password\PasswordGeneratorInterface
   */
  protected $passwordGenerator;
  
  /**
   * Constructs a new UserRegistrationResource instance.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin ID for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Config\ImmutableConfig $user_settings
   *   A user settings config instance.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   * @param \Drupal\Core\Password\PasswordGeneratorInterface|null $password_generator
   *   The password generator.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, LoggerInterface $logger, ImmutableConfig $user_settings, AccountInterface $current_user, ?PasswordGeneratorInterface $password_generator = NULL) {
    if (is_null($password_generator)) {
      @trigger_error('Calling ' . __METHOD__ . '() without the $password_generator argument is deprecated in drupal:10.3.0 and will be required in drupal:11.0.0. See https://www.drupal.org/node/3405799', E_USER_DEPRECATED);
      $password_generator = \Drupal::service('password_generator');
    }
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
    $this->userSettings = $user_settings;
    $this->currentUser = $current_user;
    $this->passwordGenerator = $password_generator;
  }
  
  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container->getParameter('serializer.formats'), $container->get('logger.factory')
      ->get('rest'), $container->get('config.factory')
      ->get('user.settings'), $container->get('current_user'), $container->get('password_generator'));
  }
  
  /**
   * Responds to user registration POST request.
   *
   * @param \Drupal\user\UserInterface $account
   *   The user account entity.
   *
   * @return \Drupal\rest\ModifiedResourceResponse
   *   The HTTP response object.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
   * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
   */
  public function post(?UserInterface $account = NULL) {
    $this->ensureAccountCanRegister($account);
    // Only activate new users if visitors are allowed to register.
    if ($this->userSettings
      ->get('register') == UserInterface::REGISTER_VISITORS) {
      $account->activate();
    }
    else {
      $account->block();
    }
    // Generate password if email verification required.
    if ($this->userSettings
      ->get('verify_mail')) {
      $account->setPassword($this->passwordGenerator
        ->generate());
    }
    $this->checkEditFieldAccess($account);
    // Make sure that the user entity is valid (email and name are valid).
    $this->validate($account);
    // Create the account.
    $account->save();
    $this->sendEmailNotifications($account);
    return new ModifiedResourceResponse($account, 200);
  }
  
  /**
   * Ensure the account can be registered in this request.
   *
   * @param \Drupal\user\UserInterface $account
   *   The user account to register.
   */
  protected function ensureAccountCanRegister(?UserInterface $account = NULL) {
    if ($account === NULL) {
      throw new BadRequestHttpException('No user account data for registration received.');
    }
    // POSTed user accounts must not have an ID set, because we always want to
    // create new entities here.
    if (!$account->isNew()) {
      throw new BadRequestHttpException('An ID has been set and only new user accounts can be registered.');
    }
    // Only allow anonymous users to register, authenticated users with the
    // necessary permissions can POST a new user to the "user" REST resource.
    // @see \Drupal\rest\Plugin\rest\resource\EntityResource
    if (!$this->currentUser
      ->isAnonymous()) {
      throw new AccessDeniedHttpException('Only anonymous users can register a user.');
    }
    // Verify that the current user can register a user account.
    if ($this->userSettings
      ->get('register') == UserInterface::REGISTER_ADMINISTRATORS_ONLY) {
      throw new AccessDeniedHttpException('You cannot register a new user account.');
    }
    if (!$this->userSettings
      ->get('verify_mail')) {
      if (empty($account->getPassword())) {
        // If no email verification then the user must provide a password.
        throw new UnprocessableEntityHttpException('No password provided.');
      }
    }
    else {
      if (!empty($account->getPassword())) {
        // If email verification required then a password cannot provided.
        // The password will be set when the user logs in.
        throw new UnprocessableEntityHttpException('A Password cannot be specified. It will be generated on login.');
      }
    }
  }
  
  /**
   * Sends email notifications if necessary for user that was registered.
   *
   * @param \Drupal\user\UserInterface $account
   *   The user account.
   */
  protected function sendEmailNotifications(UserInterface $account) {
    $approval_settings = $this->userSettings
      ->get('register');
    // No email verification is required. Activating the user.
    if ($approval_settings == UserInterface::REGISTER_VISITORS) {
      if ($this->userSettings
        ->get('verify_mail')) {
        // No administrator approval required.
        _user_mail_notify('register_no_approval_required', $account);
      }
    }
    elseif ($approval_settings == UserInterface::REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) {
      _user_mail_notify('register_pending_approval', $account);
    }
  }
}
Members
| Title Sort descending | Modifiers | Object type | Summary | Overriden Title | Overrides | 
|---|---|---|---|---|---|
| DependencySerializationTrait::$_entityStorages | protected | property | An array of entity type IDs keyed by the property name of their storages. | ||
| DependencySerializationTrait::$_serviceIds | protected | property | An array of service IDs keyed by property name used for serialization. | ||
| DependencySerializationTrait::__sleep | public | function | 2 | ||
| DependencySerializationTrait::__wakeup | public | function | #[\ReturnTypeWillChange] | 2 | |
| EntityResourceAccessTrait::checkEditFieldAccess | protected | function | Performs edit access checks for fields. | ||
| EntityResourceValidationTrait::validate | protected | function | Verifies that an entity does not violate any validation constraints. | ||
| MessengerTrait::$messenger | protected | property | The messenger. | 25 | |
| MessengerTrait::messenger | public | function | Gets the messenger. | 25 | |
| MessengerTrait::setMessenger | public | function | Sets the messenger. | ||
| PluginBase::$configuration | protected | property | Configuration information passed into the plugin. | 1 | |
| PluginBase::$pluginDefinition | protected | property | The plugin implementation definition. | 1 | |
| PluginBase::$pluginId | protected | property | The plugin ID. | ||
| PluginBase::DERIVATIVE_SEPARATOR | constant | A string which is used to separate base plugin IDs from the derivative ID. | |||
| PluginBase::getBaseId | public | function | Gets the base_plugin_id of the plugin instance. | Overrides DerivativeInspectionInterface::getBaseId | |
| PluginBase::getDerivativeId | public | function | Gets the derivative_id of the plugin instance. | Overrides DerivativeInspectionInterface::getDerivativeId | |
| PluginBase::getPluginDefinition | public | function | Gets the definition of the plugin implementation. | Overrides PluginInspectionInterface::getPluginDefinition | 2 | 
| PluginBase::getPluginId | public | function | Gets the plugin ID of the plugin instance. | Overrides PluginInspectionInterface::getPluginId | |
| PluginBase::isConfigurable | public | function | Determines if the plugin is configurable. | ||
| ResourceBase::$logger | protected | property | A logger instance. | ||
| ResourceBase::$serializerFormats | protected | property | The available serialization formats. | ||
| ResourceBase::availableMethods | public | function | Returns the available HTTP request methods on this plugin. | Overrides ResourceInterface::availableMethods | 1 | 
| ResourceBase::getBaseRoute | protected | function | Gets the base route for a particular method. | 2 | |
| ResourceBase::getBaseRouteRequirements | protected | function | Gets the base route requirements for a particular method. | 1 | |
| ResourceBase::permissions | public | function | Implements ResourceInterface::permissions(). | Overrides ResourceInterface::permissions | 2 | 
| ResourceBase::requestMethods | protected | function | Provides predefined HTTP request methods. | ||
| ResourceBase::routes | public | function | Returns a collection of routes with URL path information for the resource. | Overrides ResourceInterface::routes | |
| StringTranslationTrait::$stringTranslation | protected | property | The string translation service. | 3 | |
| StringTranslationTrait::formatPlural | protected | function | Formats a string containing a count of items. | ||
| StringTranslationTrait::getNumberOfPlurals | protected | function | Returns the number of plurals supported by a given language. | ||
| StringTranslationTrait::getStringTranslation | protected | function | Gets the string translation service. | ||
| StringTranslationTrait::setStringTranslation | public | function | Sets the string translation service to use. | 2 | |
| StringTranslationTrait::t | protected | function | Translates a string to the current language or to a given language. | ||
| UserRegistrationResource::$currentUser | protected | property | The current user. | ||
| UserRegistrationResource::$passwordGenerator | protected | property | The password generator. | ||
| UserRegistrationResource::$userSettings | protected | property | User settings config instance. | ||
| UserRegistrationResource::create | public static | function | Creates an instance of the plugin. | Overrides ResourceBase::create | |
| UserRegistrationResource::ensureAccountCanRegister | protected | function | Ensure the account can be registered in this request. | ||
| UserRegistrationResource::post | public | function | Responds to user registration POST request. | ||
| UserRegistrationResource::sendEmailNotifications | protected | function | Sends email notifications if necessary for user that was registered. | ||
| UserRegistrationResource::__construct | public | function | Constructs a new UserRegistrationResource instance. | Overrides ResourceBase::__construct | 
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.