0

Here is the scenario: Prospective employees (PE) who need to access this Drupal site for onboarding resources will be sent an access code from someone in HR (to prevent random people from creating accounts).

The PE goes to Drupal site and "registers" for a user account and they enter the access code into a field.

Only approve the account if the access code is correct. If it is correct, approve account and set role to prospect. If it is not correct, block account (until that user registers with correct access code or alternately, someone in HR manually approves it).

What should the account settings be for who can register account? How to test access value and approve/grant role or block based on registration field? Is there a hook or class to extend?

2
  • Don't have an answer, but if the HR person will have to issue the codes and approve accounts, wouldn't it be easier just to have HR create the account in the first place?
    – Jaypan
    Feb 22, 2021 at 20:05
  • Because they send the access code in a email that goes out from a template that is part of other onboarding processes and not all prospective employees will want or need to access the site.
    – shelane
    Feb 22, 2021 at 21:13

1 Answer 1

1
  1. Create a new field on the user object, field_registration_code.

  2. Set the form field to show on the registration page.

  3. Use hook_form_alter() to hide the field when not registering, if the code is not to be used in the future. Don't hide the form field on the 'manage form' tab, else it will not be rendered on the registration page.

  4. Create a service with the following method:

    /**
     * Validates a registration code.
     *
     * This function checks if the submitted  code is a valid
     * registration code, and if it is, invalidates the code, and
     * returns TRUE. If the access code is invalid, it returns FALSE.
     *
     * @param string $registrationCode
     *   The code to be validate.
     *
     * @return bool
     *   TRUE if the code was valid, FALSE otherwise.
     */
     public function validateRegistrationCode(string $registrationCode): bool;
    
  5. Implement hook_ENTITY_TYPE_insert(), implemented as hook_user_insert(). This is called after the user entity has been saved. You can use that hook to check if the given code is validated, and if not, block the account. It can then be activated by an admin through the admin interface.

    function HOOK_user_insert(EntityInterface $user) {
      if ($this->myService->validateRegistrationCode($entity->field_registration_code->value)) {
        // Add roles to user here.
      }
      else {
        $user->block()->save();
      }
    }
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.