You are here

configure_otp_over_sms_and_email.php in Google Authenticator / 2 Factor Authentication - 2FA 8

Same filename and directory in other branches
  1. 8.2 src/Form/configure_otp_over_sms_and_email.php

File

src/Form/configure_otp_over_sms_and_email.php
View source
<?php

namespace Drupal\miniorange_2fa\form;

use Drupal\user\Entity\User;
use Drupal\Core\Form\FormBase;
use Drupal\miniorange_2fa\MiniorangeUser;
use Drupal\miniorange_2fa\UsersAPIHandler;
use Drupal\miniorange_2fa\MoAuthUtilities;
use Drupal\miniorange_2fa\AuthenticationType;
use Drupal\miniorange_2fa\MiniorangeCustomerSetup;
use Drupal\miniorange_2fa\AuthenticationAPIHandler;
use Drupal\miniorange_2fa\MiniorangeCustomerProfile;
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) {
  }

}