You are here

class miniorange_oauth_clientController in OAuth2 Login 8

Hierarchy

Expanded class hierarchy of miniorange_oauth_clientController

2 files declare their use of miniorange_oauth_clientController
handler.php in src/handler.php
MiniorangeOAuthClientSupport.php in src/MiniorangeOAuthClientSupport.php
This class represents support information for customer.

File

src/Controller/miniorange_oauth_clientController.php, line 22
Contains \Drupal\miniorange_oauth_client\Controller\DefaultController.

Namespace

Drupal\oauth2_login\Controller
View source
class miniorange_oauth_clientController extends ControllerBase {

  //handles the feedback flow of the module
  public function miniorange_oauth_client_feedback_func() {
    global $base_url;
    handler::sendFeedbackEmail();

    /**
     * Uninstalling the OAuth login module after sending the feedback email
     */
    \Drupal::service('module_installer')
      ->uninstall([
      'oauth2_login',
    ]);
    if (!empty(\Drupal::config('oauth2_login.settings')
      ->get('miniorange_oauth_client_base_url'))) {
      $baseUrlValue = \Drupal::config('oauth2_login.settings')
        ->get('miniorange_oauth_client_base_url');
    }
    else {
      $baseUrlValue = $base_url;
    }
    $uninstall_redirect = $baseUrlValue . '/admin/modules';
    $response = new RedirectResponse($uninstall_redirect);
    $response
      ->send();
    return new Response();
  }

  /**
   * This function is used to get the timestamp value
   */
  public static function get_oauth_timestamp() {
    $url = 'https://login.xecurify.com/moas/rest/mobile/get-timestamp';
    $ch = \curl_init($url);
    \curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    \curl_setopt($ch, CURLOPT_ENCODING, "");
    \curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    \curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    \curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    \curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

    // required for https urls
    \curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    \curl_setopt($ch, CURLOPT_POST, TRUE);
    $content = \curl_exec($ch);
    if (\curl_errno($ch)) {
      echo 'Error in sending curl Request';
      exit;
    }
    \curl_close($ch);
    if (empty($content)) {
      $currentTimeInMillis = round(microtime(TRUE) * 1000);
      $currentTimeInMillis = number_format($currentTimeInMillis, 0, '', '');
    }
    return empty($content) ? $currentTimeInMillis : $content;
  }
  public function miniorange_oauth_client_mo_login() {
    $code = isset($_GET['code']) ? $_GET['code'] : '';
    $code = isset($code) ? Html::escape($code) : '';
    $state = isset($_GET['state']) ? $_GET['state'] : '';
    $state = isset($state) ? Html::escape($state) : '';
    if (isset($code) && isset($state)) {
      if (session_id() == '' || !isset($_SESSION)) {
        session_start();
      }
      if (!isset($code)) {
        if (isset($_GET['error_description'])) {
          exit($_GET['error_description']);
        }
        else {
          if (isset($_GET['error'])) {
            exit($_GET['error']);
          }
        }
        exit('Invalid response');
      }
      else {
        $currentappname = "";
        if (isset($_SESSION['appname']) && !empty($_SESSION['appname'])) {
          $currentappname = $_SESSION['appname'];
        }
        else {
          if (isset($state) && !empty($state)) {
            $currentappname = base64_decode($state);
          }
        }
        if (empty($currentappname)) {
          exit('No request found for this application.');
        }
      }
    }

    // Getting Access Token
    $app = [];
    $app = \Drupal::config('oauth2_login.settings')
      ->get('miniorange_oauth_client_appval');
    $name_attr = "";
    $email_attr = "";
    $name = "";
    $email = "";
    if (isset($app['miniorange_oauth_client_email_attr'])) {
      $email_attr = trim($app['miniorange_oauth_client_email_attr']);
    }
    if (isset($app['miniorange_oauth_client_name_attr'])) {
      $name_attr = trim($app['miniorange_oauth_client_name_attr']);
    }
    $parse_from_header = \Drupal::config('oauth2_login.settings')
      ->get('miniorange_oauth_send_with_header_oauth');
    $parse_from_body = \Drupal::config('oauth2_login.settings')
      ->get('miniorange_oauth_send_with_body_oauth');
    if (!$parse_from_header == TRUE || !$parse_from_header == 1) {
      $parse_from_header = FALSE;
    }
    if (!$parse_from_body == TRUE || !$parse_from_body == 1) {
      $parse_from_body = FALSE;
    }
    $accessToken = AccessToken::getAccessToken($app['access_token_ep'], 'authorization_code', $app['client_id'], $app['client_secret'], $code, $app['callback_uri'], $parse_from_header, $parse_from_body);
    if (!$accessToken) {
      print_r('Invalid token received.');
      exit;
    }
    $resourceownerdetailsurl = $app['user_info_ep'];
    if (substr($resourceownerdetailsurl, -1) == "=") {
      $resourceownerdetailsurl .= $accessToken;
    }
    $resourceOwner = UserResource::getResourceOwner($resourceownerdetailsurl, $accessToken);

    /*
     *   Test Configuration
     */
    if (isset($_COOKIE['Drupal_visitor_mo_oauth_test']) && $_COOKIE['Drupal_visitor_mo_oauth_test'] == TRUE) {
      $_COOKIE['Drupal_visitor_mo_oauth_test'] = 0;
      $module_path = \Drupal::service('extension.list.module')
        ->getPath('oauth2_login');
      $username = isset($resourceOwner['email']) ? $resourceOwner['email'] : 'User';
      \Drupal::configFactory()
        ->getEditable('oauth2_login.settings')
        ->set('miniorange_oauth_client_attr_list_from_server', $resourceOwner)
        ->save();
      echo '<div style="font-family:Calibri;padding:0 3%;">';
      echo '<div style="color: #3c763d;background-color: #dff0d8; padding:2%;margin-bottom:20px;text-align:center; border:1px solid #AEDB9A;
                        font-size:15pt;">
                        TEST SUCCESSFUL
                      </div>
                      <div style="display:block;text-align:center;margin-bottom:4%;">
                        <img style="width:15%;"src="' . $module_path . '/includes/images/green_check.png">
                      </div>';
      echo '<span style="font-size:13pt;"><b>Hello</b>, ' . $username . '</span><br/>
                      <p style="font-weight:bold;font-size:13pt;margin-left:1%;">ATTRIBUTES RECEIVED:</p>
                      <table style="border-collapse:collapse;border-spacing:0; display:table;width:100%; font-size:13pt;background-color:#EDEDED;">
                          <tr style="text-align:center;">
                              <td style="font-weight:bold;border:2px solid #949090;padding:2%;width: fit-content;">ATTRIBUTE NAME</td>
                              <td style="font-weight:bold;padding:2%;border:2px solid #949090; word-wrap:break-word;">ATTRIBUTE VALUE</td>
                          </tr>';
      self::testattrmappingconfig("", $resourceOwner);
      echo '</table></div>';
      echo '<div style="margin:3%;display:block;text-align:center;">
                        <input style="padding:1%;width:37%;background: #0091CD none repeat scroll 0% 0%;cursor: pointer;font-size:15px;
                            border-width: 1px;border-style: solid;border-radius: 3px;white-space: nowrap;box-sizing: border-box;border-color: #0073AA;
                            box-shadow: 0px 1px 0px rgba(120, 200, 230, 0.6) inset;color: #FFF;"type="button" value="Configure Attribute/Role Mapping"
                        onClick="close_and_redirect();">
                        <input style="padding:1%;width:100px;background: #0091CD none repeat scroll 0% 0%;cursor: pointer;font-size:15px;
                            border-width: 1px;border-style: solid;border-radius: 3px;white-space: nowrap;box-sizing: border-box;border-color: #0073AA;
                            box-shadow: 0px 1px 0px rgba(120, 200, 230, 0.6) inset;color: #FFF;"type="button" value="Done" onClick="self.close();">
                    </div>
                    <script>
                        function close_and_redirect(){
                            window.opener.redirect_to_attribute_mapping();
                            self.close();
                        }
                        function redirect_to_attribute_mapping(){
                            var baseurl = window.location.href.replace("config_clc","mapping");
                            window.location.href= baseurl;
                          }
                    </script>';
      return new Response();
      exit;
    }
    if (!empty($email_attr)) {
      $email = self::getnestedattribute($resourceOwner, $email_attr);
    }

    //$resourceOwner[$email_attr];
    if (!empty($name_attr)) {
      $name = self::getnestedattribute($resourceOwner, $name_attr);
    }

    //$resourceOwner[$name_attr];
    global $base_url;

    /*************==============Attributes not mapped check===============************/
    if (empty($email)) {
      echo '<div style="font-family:Calibri;padding:0 3%;">';
      echo '<div style="color: #a94442;background-color: #f2dede;padding: 15px;margin-bottom: 20px;text-align:center;border:1px solid #E6B3B2;font-size:18pt;"> ERROR</div>
                                <div style="color: #a94442;font-size:14pt; margin-bottom:20px;"><p><strong>Error: </strong>Email address does not received.</p>
                                    <p>Check your <b>Attribute Mapping</b> configuration.</p>
                                    <p><strong>Possible Cause: </strong>Email Attribute field is not configured.</p>
                                </div>
                                <div style="margin:3%;display:block;text-align:center;"></div>
                                <div style="margin:3%;display:block;text-align:center;">
                                    <form action="' . $base_url . '" method ="post">
                                        <input style="padding:1%;width:100px;background: #0091CD none repeat scroll 0% 0%;cursor: pointer;font-size:15px;border-width: 1px;border-style: solid;border-radius: 3px;white-space: nowrap;box-sizing: border-box;border-color: #0073AA;box-shadow: 0px 1px 0px rgba(120, 200, 230, 0.6) inset;color: #FFF;"type="submit" value="Done">
                                    </form>
                                </div>';
      exit;
      return new Response();
    }

    //Validates the email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      echo "Invalid email format of the received value";
      exit;
    }
    if (empty($name)) {
      $name = $email;
    }
    $account = '';
    if (!empty($email)) {
      $account = user_load_by_mail($email);
    }
    if ($account == NULL) {
      if (!empty($name) && isset($name)) {
        $account = user_load_by_name($name);
      }
    }
    global $user;

    // Creating a new user in case the user does not exists in the Drupal database
    $disable_create_user = \Drupal::config('oauth2_login.settings')
      ->get('miniorange_oauth_disable_autocreate_users');
    if ($disable_create_user) {
      $redirect = \Drupal::config('miniorange_oauth_client.settings')
        ->get('miniorange_oauth_redirect_url');
    }
    else {
      if (!isset($account->uid)) {
        $random_password = user_password(8);
        $new_user = [
          'name' => $name,
          'mail' => $email,
          'pass' => $random_password,
          'status' => 1,
        ];
        $account = User::create($new_user);
        $account
          ->save();
      }
      $user = \Drupal\user\Entity\User::load($account
        ->id());
      $edit = [];
      if (!empty(\Drupal::config('oauth2_login.settings')
        ->get('miniorange_oauth_client_base_url'))) {
        $baseUrlValue = \Drupal::config('oauth2_login.settings')
          ->get('miniorange_oauth_client_base_url');
      }
      else {
        $baseUrlValue = $base_url;
      }
      $edit['redirect'] = $baseUrlValue;
      user_login_finalize($account);

      // Update user fields here.
      $hook1 = 'oauth2_login_field_mapping';
      $implementations = \Drupal::moduleHandler()
        ->getImplementations($hook1);
      $user_updated = FALSE;
      foreach ($implementations as $implementation) {
        $func = $implementation . '_' . $hook1;
        $mapping = $func();
        foreach ($mapping as $fieldmap) {
          $user_updated = TRUE;
          $user
            ->set($fieldmap['local'], self::getnestedattribute($resourceOwner, $fieldmap['remote']));
        }
      }
      $disable_role_override = \Drupal::config('oauth2_login.settings')
        ->get('miniorange_disable_attribute');
      if (!$disable_role_override) {

        // Do role override
        $selected_role = \Drupal::config('oauth2_login.settings')
          ->get('miniorange_oauth_default_mapping');
        $user
          ->addRole($selected_role);
        $user_updated = TRUE;
      }
      if ($user_updated) {
        $user
          ->save();
      }
      $redirect = \Drupal::config('miniorange_oauth_client.settings')
        ->get('miniorange_oauth_redirect_url');
    }
    $response = new RedirectResponse($redirect);
    $response
      ->send();
    return new Response();
  }
  function testattrmappingconfig($nestedprefix, $resourceOwnerDetails) {
    foreach ($resourceOwnerDetails as $key => $resource) {
      if (is_array($resource) || is_object($resource)) {
        if (!empty($nestedprefix)) {
          $nestedprefix .= ".";
        }
        self::testattrmappingconfig($nestedprefix . $key, $resource);
      }
      else {
        echo "<tr style='text-align:center;'><td style='font-weight:bold;border:2px solid #949090;padding:2%;'>";
        if (!empty($nestedprefix)) {
          echo $nestedprefix . ".";
        }
        echo $key . "</td><td style='font-weight:bold;padding:2%;border:2px solid #949090; word-wrap:break-word;'>" . $resource . "</td></tr>";
      }
    }
  }

  /**
   * This function is used to get some specific values from the resource
   */
  function getnestedattribute($resource, $key) {
    if (empty($key)) {
      return "";
    }
    $keys = explode(".", $key);
    $currentkey = "";
    if (sizeof($keys) > 1) {
      $currentkey = $keys[0];
      if (isset($resource[$currentkey])) {
        return self::getnestedattribute($resource[$currentkey], str_replace($currentkey . ".", "", $key));
      }
    }
    else {
      $currentkey = $keys[0];
      if (isset($resource[$currentkey])) {
        if (is_array($resource[$currentkey])) {
          $resource = $resource[$currentkey];
          return $resource[0];
        }
        else {
          return $resource[$currentkey];
        }
      }
    }
  }

  /**
   * Handling Test Configuration Flow
   */
  public function test_mo_config() {
    user_cookie_save([
      "mo_oauth_test" => TRUE,
    ]);
    AuthorizationEndpoint::mo_oauth_client_initiateLogin();
    return new Response();
  }
  public function reset_mo_config() {
    handler::reset_mo_config();
  }

  /**
   * Initiating OAuth SSO flow
   */
  public function miniorange_oauth_client_mologin() {
    global $base_url;
    user_cookie_save([
      "mo_oauth_test" => FALSE,
    ]);
    $enable_login = \Drupal::config('oauth2_login.settings')
      ->get('miniorange_oauth_enable_login_with_oauth');
    if ($enable_login) {
      AuthorizationEndpoint::mo_oauth_client_initiateLogin();
      return new Response();
    }
    else {
      \Drupal::messenger()
        ->addMessage(t('Please enable <b>Login with OAuth</b> to initiate the SSO.'), 'error');
      return new RedirectResponse($base_url);
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 40
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
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.
miniorange_oauth_clientController::getnestedattribute function This function is used to get some specific values from the resource
miniorange_oauth_clientController::get_oauth_timestamp public static function This function is used to get the timestamp value
miniorange_oauth_clientController::miniorange_oauth_client_feedback_func public function
miniorange_oauth_clientController::miniorange_oauth_client_mologin public function Initiating OAuth SSO flow
miniorange_oauth_clientController::miniorange_oauth_client_mo_login public function
miniorange_oauth_clientController::reset_mo_config public function
miniorange_oauth_clientController::testattrmappingconfig function
miniorange_oauth_clientController::test_mo_config public function Handling Test Configuration Flow
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.