You are here

class configure_otp_over_sms_and_email in Google Authenticator / 2 Factor Authentication - 2FA 8

Same name and namespace in other branches
  1. 8.2 src/Form/configure_otp_over_sms_and_email.php \Drupal\miniorange_2fa\form\configure_otp_over_sms_and_email

Hierarchy

Expanded class hierarchy of configure_otp_over_sms_and_email

File

src/Form/configure_otp_over_sms_and_email.php, line 14

Namespace

Drupal\miniorange_2fa\form
View source
class configure_otp_over_sms_and_email extends FormBase {
  public function getFormId() {
    return 'miniorange_configure_otp_over_sms_and_email';
  }
  public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $form['markup_top_2'] = array(
      '#markup' => '<div class="mo_saml_table_layout_1"><div class="mo_saml_table_layout mo_saml_container">',
    );
    $form['markup_library'] = array(
      '#attached' => array(
        'library' => array(
          "miniorange_2fa/miniorange_2fa.admin",
          "miniorange_2fa/miniorange_2fa.license",
        ),
      ),
    );
    global $base_url;
    $url = $base_url . '/admin/config/people/miniorange_2fa/setup_twofactor';
    $user = User::load(\Drupal::currentUser()
      ->id());
    $user_id = $user
      ->id();
    $utilities = new MoAuthUtilities();
    $custom_attribute = $utilities::get_users_custom_attribute($user_id);
    $user_email = $custom_attribute[0]->miniorange_registered_email;
    $customer = new MiniorangeCustomerProfile();
    $miniorange_user = new MiniorangeUser($customer
      ->getCustomerID(), $user_email, NULL, NULL, AuthenticationType::$SMS_AND_EMAIL['code']);
    $auth_api_handler = new AuthenticationAPIHandler($customer
      ->getCustomerID(), $customer
      ->getAPIKey());
    $form['header']['#markup'] = '<div class="mo2f-setup-header"><div class="mo2f-setup-header-top-left">Configure OTP Over SMS And Email</div></div><br>';
    $form['miniorange_phone'] = array(
      '#type' => 'textfield',
      '#title' => t('Verify Your Phone'),
      '#id' => 'query_phone',
      '#description' => 'Enter number with country code Eg. +00xxxxxxxxxx',
      '#attributes' => array(
        'class' => array(
          'query_phone',
        ),
        'pattern' => '[\\+]?[0-9]{1,4}\\s?[0-9]{7,12}',
        'placeholder' => 'Enter number with country code Eg. +00xxxxxxxxxx',
      ),
    );
    $form['miniorange_email'] = array(
      '#type' => 'textfield',
      '#value' => $user_email,
      '#disabled' => TRUE,
    );
    $form['verifyphone'] = array(
      '#type' => 'submit',
      '#value' => t('Verify'),
      '#submit' => array(
        '::mo_auth_configure_otp_over_sms_and_email_submit',
      ),
    );
    $form['miniorange_saml_customer_setup_resendotp'] = array(
      '#type' => 'submit',
      '#value' => t('Resend OTP'),
      '#submit' => array(
        '::miniorange_saml_resend_otp',
      ),
      '#suffix' => '<br><br>',
    );
    $form['miniorange_OTP'] = array(
      '#type' => 'textfield',
      '#maxlength' => 6,
      '#attributes' => array(
        'placeholder' => t('Enter passcode.'),
      ),
      '#title' => t('OTP'),
    );
    $form['miniorange_saml_customer_validate_otp_button'] = array(
      '#type' => 'submit',
      '#value' => t('Validate OTP'),
      '#submit' => array(
        '::miniorange_saml_validate_otp_submit',
      ),
    );
    $form['actions']['cancel'] = array(
      '#markup' => '<a href="' . $url . '">Cancel</a>',
    );
    $form['main_layout_div_end'] = array(
      '#markup' => '<br><br><br><br><br><br><br><br><br></div>',
    );
    MoAuthUtilities::AddsupportTab($form, $form_state);
    return $form;
  }
  function mo_auth_configure_otp_over_sms_and_email_submit(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $form_state
      ->setRebuild();
    $customer = new MiniorangeCustomerProfile();
    $custID = $customer
      ->getCustomerID();
    $api_key = $customer
      ->getAPIKey();
    $user = User::load(\Drupal::currentUser()
      ->id());
    $user_id = $user
      ->id();
    $utilities = new MoAuthUtilities();
    $custom_attribute = $utilities::get_users_custom_attribute($user_id);
    $user_email = $custom_attribute[0]->miniorange_registered_email;
    $phone_number = str_replace(' ', '', $form['miniorange_phone']['#value']);
    if (empty($phone_number)) {
      \Drupal::messenger()
        ->addMessage(t('Please enter phone number first.'), 'error');
      return;
    }
    $currentMethod = "OTP_OVER_SMS_AND_EMAIL";
    $customer_config = new MiniorangeCustomerSetup($user_email, $phone_number, NULL, NULL);
    $params = array(
      'phone' => $phone_number,
      'email' => $user_email,
    );
    $response = $customer_config
      ->send_otp_token($params, $currentMethod, $custID, $api_key);
    $send_otp_response = json_decode($response);
    if ($send_otp_response->status == 'SUCCESS') {

      // Store txID.
      \Drupal::configFactory()
        ->getEditable('miniorange_2fa.settings')
        ->set('mo_auth_tx_id', $send_otp_response->txId)
        ->save();
      \Drupal::messenger()
        ->addStatus(t('We have sent an OTP to <strong>@email</strong> and <strong>@phone</strong>. Please enter the OTP to verify your email and phone number.', array(
        '@email' => $user_email,
        '@phone' => $phone_number,
      )));
    }
    elseif ($send_otp_response->status == 'CURL_ERROR') {
      \Drupal::messenger()
        ->addMessage(t('cURL is not enabled. Please enable cURL'), 'error');
    }
    else {
      \Drupal::messenger()
        ->addMessage(t($send_otp_response->message), 'error');
    }
  }
  function miniorange_saml_resend_otp(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    global $base_url;
    $form_state
      ->setRebuild();
    $user = User::load(\Drupal::currentUser()
      ->id());
    $user_id = $user
      ->id();
    $utilities = new MoAuthUtilities();
    $custom_attribute = $utilities::get_users_custom_attribute($user_id);
    $user_email = $custom_attribute[0]->miniorange_registered_email;
    $phone_number = str_replace(' ', '', $form['miniorange_phone']['#value']);
    if (empty($phone_number)) {
      \Drupal::messenger()
        ->addMessage(t('Please enter phone number first.'), 'error');
      return;
    }
    $params = array(
      'phone' => $phone_number,
      'email' => $user_email,
    );
    $customer = new MiniorangeCustomerProfile();
    $custID = $customer
      ->getCustomerID();
    $api_key = $customer
      ->getAPIKey();
    $currentMethod = "OTP_OVER_SMS_AND_EMAIL";
    $customer_config = new MiniorangeCustomerSetup($user_email, $phone_number, NULL, NULL);
    $response = $customer_config
      ->send_otp_token($params, $currentMethod, $custID, $api_key);
    $send_otp_response = json_decode($response);
    if ($send_otp_response->status == 'SUCCESS') {

      // Store txID.
      \Drupal::configFactory()
        ->getEditable('miniorange_2fa.settings')
        ->set('mo_auth_tx_id', $send_otp_response->txId)
        ->save();
      \Drupal::messenger()
        ->addStatus(t('We have sent an OTP to <strong>@email</strong> and <strong>@phone</strong>. Please enter the OTP to verify your email and phone number.', array(
        '@email' => $user_email,
        '@phone' => $phone_number,
      )));
    }
    elseif ($send_otp_response->status == 'CURL_ERROR') {
      \Drupal::messenger()
        ->addMessage(t('cURL is not enabled. Please enable cURL'), 'error');
    }
    else {
      \Drupal::messenger()
        ->addMessage(t($send_otp_response->message), 'error');
    }
  }
  function miniorange_saml_validate_otp_submit(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $customer = new MiniorangeCustomerProfile();
    $cKey = $customer
      ->getCustomerID();
    $customerApiKey = $customer
      ->getAPIKey();
    $otpToken = $form['miniorange_OTP']['#value'];
    $user = User::load(\Drupal::currentUser()
      ->id());
    $user_id = $user
      ->id();
    $utilities = new MoAuthUtilities();
    $custom_attribute = $utilities::get_users_custom_attribute($user_id);
    $user_email = $custom_attribute[0]->miniorange_registered_email;
    $phone_number = str_replace(' ', '', $form['miniorange_phone']['#value']);
    if (empty($phone_number)) {
      \Drupal::messenger()
        ->addMessage(t('Please enter phone number first.'), 'error');
      return;
    }
    if (empty($otpToken)) {
      \Drupal::messenger()
        ->addMessage(t('Please enter OTP first.'), 'error');
      return;
    }
    \Drupal::configFactory()
      ->getEditable('miniorange_2fa.settings')
      ->set('mo_phone', $phone_number)
      ->save();
    $transactionId = \Drupal::config('miniorange_2fa.settings')
      ->get('mo_auth_tx_id');
    $customer_config = new MiniorangeCustomerSetup($user_email, $phone_number, NULL, NULL);
    $response = $customer_config
      ->validate_otp_token($transactionId, $otpToken, $cKey, $customerApiKey);
    $otp_validation = json_decode($response);
    $txId = $otp_validation->txId;
    if ($otp_validation->status == 'FAILED') {
      \Drupal::messenger()
        ->addMessage(t("Validation Failed. Please enter the correct OTP."), 'error');
      return;
    }
    elseif ($otp_validation->status == 'SUCCESS') {
      $form_state
        ->setRebuild();
      $authTypeCode = AuthenticationType::$SMS_AND_EMAIL['code'];
      $user_email = $custom_attribute[0]->miniorange_registered_email;
      $customer = new MiniorangeCustomerProfile();
      $miniorange_user = new MiniorangeUser($customer
        ->getCustomerID(), $user_email, NULL, NULL, AuthenticationType::$SMS_AND_EMAIL['code']);
      $auth_api_handler = new AuthenticationAPIHandler($customer
        ->getCustomerID(), $customer
        ->getAPIKey());
      $configured_methods = MoAuthUtilities::mo_auth_get_configured_methods($user_id);
      if (!in_array(AuthenticationType::$SMS_AND_EMAIL['code'], $configured_methods)) {
        array_push($configured_methods, AuthenticationType::$SMS_AND_EMAIL['code']);
      }
      $config_methods = implode(', ', $configured_methods);
      $user_api_handler = new UsersAPIHandler($customer
        ->getCustomerID(), $customer
        ->getAPIKey());

      // Updating the authentication method for the user
      $miniorange_user
        ->setAuthType($authTypeCode);
      $response = $user_api_handler
        ->update($miniorange_user);
      if ($response->status == 'SUCCESS') {

        // Save User
        $user_id = $user
          ->id();
        $utilities = new MoAuthUtilities();
        $available = $utilities::check_for_userID($user_id);
        $database = \Drupal::database();
        if ($available == TRUE) {
          $database
            ->update('UserAuthenticationType')
            ->fields([
            'activated_auth_methods' => AuthenticationType::$SMS_AND_EMAIL['code'],
          ])
            ->condition('uid', $user_id, '=')
            ->execute();
          $database
            ->update('UserAuthenticationType')
            ->fields([
            'configured_auth_methods' => $config_methods,
          ])
            ->condition('uid', $user_id, '=')
            ->execute();
        }
        else {
          echo "error while saving authentication method.";
          exit;
        }
        if ($authTypeCode == AuthenticationType::$SMS_AND_EMAIL['code']) {
          $message = 'OTP Over SMS and Email has been configured successfully.';
          MoAuthUtilities::show_error_or_success_message($message, 'status');
        }
      }
      return;
    }
    $message = 'An error occured while processing your request. Please try again.';
    MoAuthUtilities::show_error_or_success_message($message, 'error');
  }
  public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  }

}

Members

Namesort descending Modifiers Type Description Overrides
configure_otp_over_sms_and_email::buildForm public function Form constructor. Overrides FormInterface::buildForm
configure_otp_over_sms_and_email::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
configure_otp_over_sms_and_email::miniorange_saml_resend_otp function
configure_otp_over_sms_and_email::miniorange_saml_validate_otp_submit function
configure_otp_over_sms_and_email::mo_auth_configure_otp_over_sms_and_email_submit function
configure_otp_over_sms_and_email::submitForm public function Form submission handler. Overrides FormInterface::submitForm
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 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.