diff --git a/social_login.info.yml b/social_login.info.yml
index 41a1c79..ea43b65 100644
--- a/social_login.info.yml
+++ b/social_login.info.yml
@@ -3,6 +3,7 @@ type: module
 description: 'Allows your users to register and login with 40+ social networks like for example Twitter, Facebook, Paypal, LinkedIn, Instagram, Vimeo, Google and Yahoo'
 package: 'OneAll Social Login'
 core: 8.x
+core_version_requirement: ^8 || ^9
 configure: social_login.admin_settings
 #dependencies:
 libraries:
diff --git a/social_login.module b/social_login.module
index fc1d095..e4f3876 100644
--- a/social_login.module
+++ b/social_login.module
@@ -4,11 +4,16 @@
  * @file
  * Contains the hook functions used by the OneAll Social Login Module.
  */
+
+use Drupal\Core\Database\Database;
+use Drupal\Core\File\FileSystemInterface;
+use Drupal\Core\Link;
 use Drupal\social_login\Event\SocialLoginUserLinkedEvent;
 use Drupal\field\Entity\FieldConfig;
 use Drupal\Core\Routing\RouteMatchInterface;
 use Drupal\Core\Form\FormStateInterface;
 use Drupal\Core\Url;
+use Drupal\user\UserInterface;
 use GuzzleHttp\Exception\RequestException;
 use GuzzleHttp\Exception\ConnectException;
 
@@ -56,7 +61,7 @@ function social_login_form_user_form_alter(&$form, FormStateInterface $form_stat
 function social_login_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
 
   // Clear leftover session.
-  if (isset($_SESSION) && isset($_SESSION['social_login_session_open'])) {
+  if (isset($_SESSION['social_login_session_open'])) {
     social_login_clear_session();
   }
   social_login_show_providers($form, $form_state, 'login_page');
@@ -68,7 +73,7 @@ function social_login_form_user_login_form_alter(&$form, FormStateInterface $for
 function social_login_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {
 
   // Check if we come from a valid session.
-  if (isset($_SESSION) && !empty($_SESSION['social_login_session_open']) && !empty($_SESSION['social_login_social_data'])) {
+  if (!empty($_SESSION['social_login_session_open']) && !empty($_SESSION['social_login_social_data'])) {
 
     // To ensure that the SESSION data is used for registration once.
     $_SESSION['social_login_session_open'] = 0;
@@ -438,7 +443,7 @@ function social_login_user_insert($account) {
           default :
 
             // No approval required.
-            if (Drupal::config('user.settings')->get('register') == USER_REGISTER_VISITORS)
+            if (Drupal::config('user.settings')->get('register') == UserInterface::REGISTER_VISITORS)
             {
               // Activate.
               $account->activate();
@@ -493,9 +498,13 @@ function social_login_user_login($account) {
             if ($account->id() != $uid)
             {
               // Add user message.
-              drupal_set_message(t('Sorry, but this @provider account is already linked to another user on this website.', [
-                  '@provider' => $provider
-              ]), 'error');
+              $message = t('Sorry, but this @provider account is already linked to another user on this website.',
+                ['@provider' => $provider]
+              );
+              $messenger = \Drupal::messenger();
+              if (isset($message)) {
+                $messenger->addMessage($message, 'error');
+              }
             }
           }
           // Not linked.
@@ -510,9 +519,13 @@ function social_login_user_login($account) {
                 $event_dispatcher->dispatch(SocialLoginUserLinkedEvent::EVENT_NAME, $event);
 
                 // Add user message.
-                drupal_set_message(t('Your @provider account has been linked to your account. You may now use @provider to login.', [
-                    '@provider' => $provider
-                ]), 'status');
+              $message = t('Your @provider account has been linked to your account. You may now use @provider to login.', [
+                '@provider' => $provider
+              ]);
+              $messenger = \Drupal::messenger();
+              if (isset($message)) {
+                $messenger->addMessage($message, 'status');
+              }
             }
           }
         }
@@ -526,11 +539,14 @@ function social_login_user_login($account) {
  * Implements hook_user_delete().
  */
 function social_login_user_delete($account) {
-  $aids = db_query("SELECT aid FROM {oneall_social_login_authmap} WHERE uid = :userid", [':userid' => $account->id()])->fetchCol();
+  $aids = Database::getConnection()
+    ->query("SELECT aid FROM {oneall_social_login_authmap} WHERE uid = :userid",
+      [':userid' => $account->id()])
+    ->fetchCol();
   if (is_array($aids)) {
     foreach ($aids as $aid) {
-      db_delete('oneall_social_login_identities')->condition('aid', $aid)->execute();
-      db_delete('oneall_social_login_authmap')->condition('aid', $aid)->execute();
+      Database::getConnection()->delete('oneall_social_login_identities')->condition('aid', $aid)->execute();
+      Database::getConnection()->delete('oneall_social_login_authmap')->condition('aid', $aid)->execute();
     }
   }
 }
@@ -582,7 +598,7 @@ function social_login_curl_lookup_real_url($url, $max_redirects = 3, $timeout =
 
   // Follow the location?
   if (in_array($curl_status['http_code'], [301,302]) && $max_redirects > 0) {
-    list ($header) = explode("\r\n\r\n", $curl_result, 2);
+    [$header] = explode("\r\n\r\n", $curl_result, 2);
     if (preg_match("/(Location:|URI:)[^(\n)]*/", $header, $matches)) {
       $url_tmp = trim(str_replace($matches[1], "", $matches[0]));
       $url_parsed = parse_url($url_tmp);
@@ -748,13 +764,13 @@ function social_login_link_social_network_avatar($social_data, $account) {
       $field = FieldConfig::loadByName('user', 'user', 'user_picture');
       $token_service = Drupal::service('token');
       $file_dir = $token_service->replace($field->getSetting('file_directory'));
-      $picture_directory = file_default_scheme() . '://' . $file_dir;
+      $picture_directory = \Drupal::config('system.file')->get('default_scheme') . '://' . $file_dir;
 
       // Prepare the picture directory.
-      if (file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY)) {
+      if (\Drupal::service('file_system')->prepareDirectory($picture_directory, FileSystemInterface::CREATE_DIRECTORY)) {
 
         // Base name of the file.
-        $file_base_name = $picture_directory . '/picture-' . $account->id() . '-' . REQUEST_TIME;
+        $file_base_name = $picture_directory . '/picture-' . $account->id() . '-' . Drupal::time()->getRequestTime();;
 
         // Check which api connection handler should be used.
         $handler = (!empty($settings['http_handler']) ? $settings['http_handler'] : 'curl');
@@ -765,8 +781,8 @@ function social_login_link_social_network_avatar($social_data, $account) {
 
         // Save the picture data locally.
         $tmp_name = $file_base_name . '.tmp';
-        $tmp_path = file_stream_wrapper_uri_normalize($tmp_name);
-        $tmp_file = file_save_data($http_result['http_data'], $tmp_path, FILE_EXISTS_REPLACE);
+        $tmp_path = \Drupal::service('stream_wrapper_manager')->normalizeUri($tmp_name);
+        $tmp_file = file_save_data($http_result['http_data'], $tmp_path, FileSystemInterface::EXISTS_REPLACE);
 
         if ($tmp_file === FALSE) {
           Drupal::logger('social_login')->error('Could not save user avatar to @path', ['@path' => $tmp_path]);
@@ -777,11 +793,11 @@ function social_login_link_social_network_avatar($social_data, $account) {
         if (($file_info = getimagesize($tmp_path)) !== FALSE) {
 
           // Rename the temporary file to the correct extension.
-          list (, , $type) = $file_info;
+          [, , $type] = $file_info;
           $real_name = $file_base_name . image_type_to_extension($type);
-          $real_path = file_stream_wrapper_uri_normalize($real_name);
+          $real_path = \Drupal::service('stream_wrapper_manager')->normalizeUri($real_name);
 
-          $real_file = file_move($tmp_file, $real_path, FILE_EXISTS_REPLACE);
+          $real_file = file_move($tmp_file, $real_path, FileSystemInterface::EXISTS_REPLACE);
 
           // file_move does not update the destination filename:
           $real_file->setFilename(Drupal::service('file_system')->basename($real_path));
@@ -842,22 +858,22 @@ function social_login_redirect ($target = '', $data = '')
 
         // Drupal Homepage.
         case 'drupal.home':
-            $redirect_to = \Drupal::url('<front>');
+            $redirect_to = Url::fromRoute('<front>');
             break;
 
         // Drupal Login.
         case 'drupal.login':
-            $redirect_to = \Drupal::url('user.login');
+            $redirect_to = Url::fromRoute('user.login');
             break;
 
         // Drupal Registration.
         case 'drupal.register':
-            $redirect_to = \Drupal::url('user.register');
+            $redirect_to = Url::fromRoute('user.register');
             break;
 
         // Drupal Profile.
         case 'drupal.profile':
-            $redirect_to = \Drupal::url('user.page');
+            $redirect_to = Url::fromRoute('user.page');
             break;
 
         // Custom URL.
@@ -874,7 +890,7 @@ function social_login_redirect ($target = '', $data = '')
                 {
                     // Homepage.
                     case 'home':
-                        $redirect_to = \Drupal::url('<front>');
+                        $redirect_to = Url::fromRoute('<front>');
                     break;
 
                     // Back to previous page.
@@ -885,7 +901,7 @@ function social_login_redirect ($target = '', $data = '')
                         }
                         else
                         {
-                            $redirect_to = \Drupal::url('<front>');
+                            $redirect_to = Url::fromRoute('<front>');
                         }
                    break;
 
@@ -897,7 +913,7 @@ function social_login_redirect ($target = '', $data = '')
                        }
                        else
                        {
-                           $redirect_to = \Drupal::url('<front>');
+                           $redirect_to = Url::fromRoute('<front>');
                        }
                   break;
                 }
@@ -914,7 +930,7 @@ function social_login_redirect ($target = '', $data = '')
             {
                 // Homepage.
                 case 'home':
-                    $redirect_to = \Drupal::url('<front>');
+                    $redirect_to = Url::fromRoute('<front>');
                     break;
 
                 // Back to previous page.
@@ -925,7 +941,7 @@ function social_login_redirect ($target = '', $data = '')
                     }
                     else
                     {
-                        $redirect_to = \Drupal::url('<front>');
+                        $redirect_to = Url::fromRoute('<front>');
                     }
                     break;
 
@@ -937,7 +953,7 @@ function social_login_redirect ($target = '', $data = '')
                     }
                     else
                     {
-                        $redirect_to = \Drupal::url('<front>');
+                        $redirect_to = Url::fromRoute('<front>');
                     }
                     break;
             }
@@ -954,8 +970,9 @@ function social_login_redirect ($target = '', $data = '')
  * Unlinks an identity_token from an existing user account.
  */
 function social_login_unmap_identity_token($identity_token) {
-  db_delete('oneall_social_login_identities')->condition('identity_token', $identity_token)->execute();
-
+  Database::getConnection()->delete('oneall_social_login_identities')
+    ->condition('identity_token', $identity_token)
+    ->execute();
   // TODO: remove authmap records, when no identity left?
 }
 
@@ -965,33 +982,48 @@ function social_login_unmap_identity_token($identity_token) {
 function social_login_map_identity_token_to_user_token($account, $identity_token, $user_token, $provider_name) {
 
   // Start transaction.
-  $db_transaction = db_transaction();
+  $db_transaction =  Database::getConnection()->startTransaction();
 
   try {
     // Update internal authmaps.
     // This code is adapted from D7 former user_set_authmap().
     if ($user_token) {
-      db_merge('oneall_social_login_authmap')->key(['uid' => $account->id()])->fields(['user_token' => $user_token])->execute();
+      Database::getConnection()
+        ->merge('oneall_social_login_authmap')
+        ->key(['uid' => $account->id()])
+        ->fields(['user_token' => $user_token])
+        ->execute();
     }
     else {
-      db_delete('oneall_social_login_authmap')->condition('uid', $account->id())->execute();
+      Database::getConnection()
+        ->delete('oneall_social_login_authmap')
+        ->condition('uid', $account->id())
+        ->execute();;
     }
 
     // Get the new authmap identifier.
-    $aid = db_select('oneall_social_login_authmap', 'a')->fields('a', ['aid'])->condition('user_token', $user_token, '=')->execute()->fetchField();
-
+    $aid = Database::getConnection()
+      ->select('oneall_social_login_authmap', 'a')
+      ->fields('a', ['aid'])
+      ->condition('user_token', $user_token, '=')
+      ->execute()
+      ->fetchField();
     if (is_numeric($aid)) {
 
       // Remove duplicate identities.
-      db_delete('oneall_social_login_identities')->condition('aid', $aid)->condition('identity_token', $identity_token)->execute();
-
+      Database::getConnection()
+        ->delete('oneall_social_login_identities')
+        ->condition('aid', $aid)
+        ->condition('identity_token', $identity_token)
+        ->execute();
       // Add identity.
-      db_insert('oneall_social_login_identities')->fields([
-        'aid' => $aid,
-        'identity_token' => $identity_token,
-        'provider_name' => $provider_name
-      ])->execute();
-
+      Database::getConnection()
+        ->insert('oneall_social_login_identities')
+        ->fields([
+          'aid' => $aid,
+          'identity_token' => $identity_token,
+          'provider_name' => $provider_name
+        ])->execute();;
       // Success.
       return TRUE;
     }
@@ -1021,7 +1053,9 @@ function social_login_get_user_for_user_token($user_token) {
  * Return the uid for a user_token.
  */
 function social_login_get_uid_for_user_token($user_token) {
-  $uid = db_query("SELECT uid FROM {oneall_social_login_authmap} WHERE user_token = :token", [':token' => $user_token])->fetchField();
+  $uid = Database::getConnection()
+    ->query("SELECT uid FROM {oneall_social_login_authmap} WHERE user_token = :token", [':token' => $user_token])
+    ->fetchField();
   return (is_numeric($uid) ? $uid : FALSE);
 }
 
@@ -1029,7 +1063,9 @@ function social_login_get_uid_for_user_token($user_token) {
  * Return the user_token for a uid.
  */
 function social_login_get_user_token_for_uid($uid) {
-  $user_token = db_query("SELECT user_token FROM {oneall_social_login_authmap} WHERE uid = :uid", [':uid' => $uid])->fetchField();
+  $user_token = Database::getConnection()
+    ->query("SELECT user_token FROM {oneall_social_login_authmap} WHERE uid = :uid", [':uid' => $uid])
+    ->fetchField();
   return (!empty($user_token) ? $user_token : FALSE);
 }
 
@@ -1106,7 +1142,7 @@ function social_login_get_settings() {
   $settings['enabled_providers'] = [];
 
   // Read settings.
-  $results = db_query("SELECT setting, value FROM {oneall_social_login_settings}");
+  $results = Database::getConnection()->query("SELECT setting, value FROM {oneall_social_login_settings}");
   foreach ($results as $result) {
     $settings[$result->setting] = $result->value;
     if (substr($result->setting, 0, 8) == 'provider' && !empty($result->value)) {
@@ -1122,7 +1158,7 @@ function social_login_get_settings() {
 function social_login_preprocess_page(&$vars, $hook) {
   if (is_array($vars['page']) && isset($vars['page']) && isset($vars['page']['footer'])) {
     if (isset($vars['page']['footer']['system_powered-by']) && isset($vars['page']['footer']['system_powered-by']['#markup'])) {
-      $vars['page']['footer']['system_powered-by']['#markup'] .= '&nbsp; | &nbsp;' . Drupal::l(t('Social Login'), Url::fromUri('http://www.oneall.com/services/social-login/')) . ' ' . t('powered by') . ' ' . Drupal::l('OneAll', Url::fromUri('http://www.oneall.com/'));
+      $vars['page']['footer']['system_powered-by']['#markup'] .= '&nbsp; | &nbsp;' . Link::fromTextAndUrl(t('Social Login'), Url::fromUri('http://www.oneall.com/services/social-login/'))->toString() . ' ' . t('powered by') . ' ' . Link::fromTextAndUrl('OneAll', Url::fromUri('http://www.oneall.com/'))->toString();
     }
   }
 }
diff --git a/src/Controller/SocialLoginController.php b/src/Controller/SocialLoginController.php
index c7046a5..c7db7eb 100644
--- a/src/Controller/SocialLoginController.php
+++ b/src/Controller/SocialLoginController.php
@@ -2,9 +2,12 @@
 
 namespace Drupal\social_login\Controller;
 
+use Drupal\user\Entity\User;
+use Drupal\user\UserInterface;
+use Symfony\Component\DependencyInjection\ContainerInterface;
 use Drupal\Component\Serialization\Json;
 use Drupal\Core\Controller\ControllerBase;
-use Drupal\Core\Url;
+use Drupal\Core\Messenger\MessengerInterface;
 
 use Drupal\social_login\Event\SocialLoginUserCreatedEvent;
 use Drupal\social_login\Event\SocialLoginUserLoginEvent;
@@ -13,662 +16,619 @@ use Drupal\social_login\Event\SocialLoginUserLinkedEvent;
 /**
  * Contains the callback handler used by the OneAll Social Login Module.
  */
-class SocialLoginController extends ControllerBase
-{
-    /**
-     * This is the callback handler (referenced by routing.yml).
-     */
-    public function callbackHandler()
-    {
-        // Read Settings.
-        $settings = social_login_get_settings();
-
-        // No need to do anything if we haven't received these arguments.
-        if (isset($_POST) && !empty($_POST['connection_token']) && !empty($_POST['oa_action']) && in_array($_POST['oa_action'], ['social_login', 'social_link']))
-        {
-            // Add system log.
-            \Drupal::logger('social_login')->notice('Callback handler called using connection_token @connection_token.', [
-                '@connection_token' => $_POST['connection_token']
-            ]);
-
-            // Clear session.
-            social_login_clear_session();
-
-            // API Connection Credentials.
-            $api_subdomain = (!empty($settings['api_subdomain']) ? $settings['api_subdomain'] : '');
-            $api_key = (!empty($settings['api_key']) ? $settings['api_key'] : '');
-            $api_secret = (!empty($settings['api_secret']) ? $settings['api_secret'] : '');
-
-            // API Connection Handler.
-            $handler = (!empty($settings['http_handler']) ? $settings['http_handler'] : 'curl');
-            $handler = ($handler == 'fsockopen' ? 'fsockopen' : 'curl');
-
-            // API Connection Protocol.
-            $protocol = (!empty($settings['http_protocol']) ? $settings['http_protocol'] : 'https');
-            $protocol = ($protocol == 'http' ? 'http' : 'https');
-
-            // Automatic or manual registration?
-            $registration_method = (!empty($settings['registration_method']) ? $settings['registration_method'] : '');
-            $registration_method = (in_array($registration_method, ['manual', 'auto_random_email', 'auto_manual_email']) ? $registration_method : 'manual');
-
-            // Require approval?
-            $registration_approval = (!empty($settings['registration_approval']) ? $settings['registration_approval'] : '');
-            $registration_approval = (in_array($registration_approval, ['inherit', 'disable', 'enable']) ? $registration_approval : 'inherit');
-
-            // Retrieved connection_token.
-            $token = trim($_POST['connection_token']);
-
-            // Settings missing.
-            if (empty($api_subdomain) || empty($api_key) || empty($api_secret)) {
-
-                // User message.
-                drupal_set_message($this->t('OneAll Social Login is not setup correctly, please request the administrator to verify the API Settings'), 'error');
-
-                // Add log.
-                \Drupal::logger('social_login')->error('Unable to use Social Login, the API Settings are not filled out correctly.');
-
-                // Redirect to homepage.
-                return social_login_redirect ('drupal.home');
-            }
-            // Settings filled out.
-            else
-            {
-                // Request connection details.
-                $data = social_login_do_api_request($handler, $protocol . '://' . $api_subdomain . '.api.oneall.com/connections/' . $token . '.json', [
-                    'api_key' => $api_key,
-                    'api_secret' => $api_secret
-                ]);
-
-                if (is_array($data) && !empty($data['http_data']))
-                {
-                    // Decode result.
-                    $social_data = Json::decode($data['http_data']);
-
-                    // Everything seems to be ok.
-                    if (is_array($social_data) && isset($social_data['response']) && isset($social_data['response']['result']['status']['code']))
-                    {
-                        // Retrieve the response data.
-                        $data = $social_data['response']['result']['data'];
-
-                        // Success
-                        if ($social_data['response']['result']['status']['code'] == 200)
-                        {
-                            // Save the social network data in a session.
-                            $_SESSION['social_login_session_open'] = 1;
-                            $_SESSION['social_login_social_data'] = serialize($social_data);
-
-                            // Unique user_token.
-                            $user_token = $data['user']['user_token'];
-
-                            // Extract identity.
-                            $identity = $data['user']['identity'];
-
-                            // Unique identity_token.
-                            $identity_token = $identity['identity_token'];
-
-                            // Social Network that has been used to connect.
-                            $provider_name = (!empty($identity['source']['name']) ? $identity['source']['name'] : $this->t('Unkown'));
-
-                            // Try restoring the user for the token.
-                            $user_for_token = social_login_get_user_for_user_token($user_token);
-
-                            // Existing user.
-                            if (is_object($user_for_token) && !empty($user_for_token->id()))
-                            {
-                                // Existing User Token: Social Login.
-                                if ($data['plugin']['key'] == 'social_login')
-                                {
-                                    // Make sure that the user has not been blocked.
-                                    $name = $user_for_token->get('name')->value;
-
-                                    // The user is not blocked.
-                                    if (!user_is_blocked($name))
-                                    {
-                                        // Login the user.
-                                        user_login_finalize($user_for_token);
-
-                                        // Dispatches SocialLoginUserLoginEvent event.
-                                        $event = new SocialLoginUserLoginEvent ($user_for_token, $data);
-                                        $event_dispatcher = \Drupal::service('event_dispatcher');
-                                        $event_dispatcher->dispatch(SocialLoginUserLoginEvent::EVENT_NAME, $event);
-
-                                        // Clear session.
-                                        social_login_clear_session();
-
-                                        // Redirect to specified page.
-                                        return social_login_redirect ('settings.login', $user_for_token->id());
-                                    }
-                                    // The user is blocked.
-                                    else
-                                    {
-                                        // User message.
-                                        drupal_set_message($this->t('Your account is blocked.'), 'error');
-
-                                        // Clear session.
-                                        social_login_clear_session();
-
-                                        // Redirect to home.
-                                        return social_login_redirect ('drupal.home');
-                                    }
-                                }
-                                // Existing User Token: Social Link.
-                                elseif ($data['plugin']['key'] == 'social_link')
-                                {
-                                    // The user must be logged in.
-                                    $session = \Drupal::currentUser();
-
-                                    // User is logged in.
-                                    if (is_object($session) && $session->isAuthenticated())
-                                    {
-                                        // Load user.
-                                        $user = \Drupal::entityTypeManager()->getStorage('user')->load($session->id());
-
-                                        // The existing token does not match the current user!
-                                        if ($user_for_token->id() != $user->id())
-                                        {
-                                            drupal_set_message($this->t('This @social_network account is already linked to another user.', [
-                                                '@social_network' => $provider_name
-                                            ]), 'error');
-                                        }
-                                        // The existing token matches the current user!
-                                        else
-                                        {
-                                            // Link identity.
-                                            if ($data['plugin']['data']['action'] == 'link_identity')
-                                            {
-                                                // Add mapping.
-                                                if (social_login_map_identity_token_to_user_token($user, $identity_token, $user_token, $provider_name))
-                                                {
-                                                    // Dispatches SocialLoginUserLinkedEvent event.
-                                                    $event = new SocialLoginUserLinkedEvent ($user, $data);
-                                                    $event_dispatcher = \Drupal::service('event_dispatcher');
-                                                    $event_dispatcher->dispatch(SocialLoginUserLinkedEvent::EVENT_NAME, $event);
-
-                                                    // Add user message.
-                                                    drupal_set_message($this->t('The @social_network account has been linked to your account.', [
-                                                        '@social_network' => $provider_name
-                                                    ]), 'status');
-
-                                                    // Add log.
-                                                    \Drupal::logger('social_login')->notice('@name has linked his @provider account, identity @identity_token.', [
-                                                        '@name' => $user->getAccountName(),
-                                                        '@provider' => $provider_name,
-                                                        '@identity_token' => $identity_token
-                                                    ]);
-                                                }
-                                            }
-                                            // Unlink identity.
-                                            else
-                                            {
-                                                // Remove mapping.
-                                                social_login_unmap_identity_token($identity_token);
-
-                                                // Add user message.
-                                                drupal_set_message($this->t('The social network account has been unlinked from your account.'), 'status');
-
-                                                // Add log.
-                                                \Drupal::logger('social_login')->notice('@name has unlinked a social network account, identity @identity_token.', [
-                                                    '@name' => $user->getAccountName(),
-                                                    '@identity_token' => $identity_token
-                                                ]);
-                                            }
-
-                                            // Clear session.
-                                            social_login_clear_session();
-                                        }
-
-                                        // Redirect to previous page.
-                                        if (!empty($_GET['origin']))
-                                        {
-                                            return social_login_redirect ('custom.url', $_GET['origin']);
-                                        }
-                                        // Redirect to profile page.
-                                        else
-                                        {
-                                            return social_login_redirect ('drupal.profile');
-                                        }
-                                    }
-                                    // User is not logged in.
-                                    else
-                                    {
-                                        drupal_set_message($this->t('You must be logged in to perform this action.'), 'error');
-
-                                        // Clear session.
-                                        social_login_clear_session();
-
-                                        // Redirect to home.
-                                        return social_login_redirect ('drupal.home');
-                                    }
-                                }
-                            }
-                            // New User.
-                            else
-                            {
-                                // No Existing User Token: Social Link.
-                                if ($data['plugin']['key'] == 'social_link')
-                                {
-                                    // The user should be logged in.
-                                    $session = \Drupal::currentUser();
-
-                                    // User is logged in.
-                                    if (is_object($session) && $session->isAuthenticated())
-                                    {
-                                        // Load user.
-                                        $user = \Drupal::entityTypeManager()->getStorage('user')->load($session->id());
-
-                                        // Link identity.
-                                        if ($data['plugin']['data']['action'] == 'link_identity')
-                                        {
-                                            // Add mapping.
-                                            if (social_login_map_identity_token_to_user_token($user, $identity_token, $user_token, $provider_name))
-                                            {
-                                                // Dispatches SocialLoginUserLinkedEvent event.
-                                                $event = new SocialLoginUserLinkedEvent ($user, $data);
-                                                $event_dispatcher = \Drupal::service('event_dispatcher');
-                                                $event_dispatcher->dispatch(SocialLoginUserLinkedEvent::EVENT_NAME, $event);
-
-                                                // Add user message.
-                                                drupal_set_message($this->t('The @social_network account has been linked to your account.', [
-                                                    '@social_network' => $provider_name
-                                                ]), 'status');
-
-                                                // Add log.
-                                                \Drupal::logger('social_login')->notice('@name has linked his @provider account, identity @identity_token.', [
-                                                    '@name' => $user->getAccountName(),
-                                                    '@provider' => $provider_name,
-                                                    '@identity_token' => $identity_token
-                                                ]);
-                                            }
-                                        }
-                                        // Unlink identity.
-                                        else
-                                        {
-                                            // Remove mapping.
-                                            social_login_unmap_identity_token($identity_token);
-
-                                            // Add user message.
-                                            drupal_set_message($this->t('The social network account has been unlinked from your account.'), 'status');
-                                        }
-
-                                        // Clear session.
-                                        social_login_clear_session();
-
-                                        // Redirect to previous page.
-                                        if (!empty($_GET['origin']))
-                                        {
-                                             return social_login_redirect ('custom.url', $_GET['origin']);
-                                        }
-                                        // Redirect to profile page.
-                                        else
-                                        {
-                                            return social_login_redirect ('drupal.profile');
-                                        }
-                                    }
-                                    // User is not logged in.
-                                    else
-                                    {
-                                        // Add user message.
-                                        drupal_set_message($this->t('You must be logged in to perform this action.'), 'error');
-
-                                        // Clear session.
-                                        social_login_clear_session();
-
-                                        // Redirect to home.
-                                        return social_login_redirect ('drupal.home');
-                                    }
-                                }
-                                // No Existing User: Social Login (Default)
-                                else
-                                {
-                                    // New users may register.
-                                    if (\Drupal::config('user.settings')->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY)
-                                    {
-                                        // Extract the user's email address.
-                                        $user_email = '';
-                                        $user_email_is_verified = null;
-                                        $user_email_is_random = null;
-
-                                        // Do we have any emails in the profile data?
-                                        if (isset($identity['emails']) && is_array($identity['emails']))
-                                        {
-                                            // Extract email address.
-                                            foreach ($identity['emails'] AS $email)
-                                            {
-                                               $user_email = $email['value'];
-                                               $user_email_is_verified = (!empty($email['is_verified']) ? true : false);
-                                               $user_email_is_random = false;
-
-                                               // Stop once we have found a verified email address.
-                                               if ($user_email_is_verified)
-                                               {
-                                                   break;
-                                               }
-                                            }
-                                        }
-
-                                        // The admin has chosen the automatic registration.
-                                        if ($registration_method != 'manual')
-                                        {
-                                            // No email address / Email address already exists.
-                                            if (empty($user_email) || social_login_get_uid_for_email($user_email) !== false)
-                                            {
-                                                // The admin wants users to fill out their email manually.
-                                                if ($registration_method == 'auto_manual_email')
-                                                {
-                                                    // We have to fall back to the default registration.
-                                                    $registration_method = 'manual';
-                                                }
-                                                // The admin has enabled the usage of random emails.
-                                                else
-                                                {
-                                                    // Create a bogus email.
-                                                    $user_email = social_login_create_random_email();
-
-                                                    // Flag - is used further down.
-                                                    $user_email_is_random = true;
-                                                }
-                                            }
-                                        }
-
-                                        // Automatic registration is enabled.
-                                        if ($registration_method != 'manual')
-                                        {
-                                            // If something goes wrong fall back to manual registration.
-                                            $registration_method = 'manual';
-
-                                            // Extract firstname.
-                                            $user_first_name = (!empty($identity['name']['givenName']) ? $identity['name']['givenName'] : '');
-
-                                            // Extract lastname.
-                                            $user_last_name = (!empty($identity['name']['familyName']) ? $identity['name']['familyName'] : '');
-
-                                            // Forge login.
-                                            $user_login = '';
-                                            if (!empty($identity['preferredUsername']))
-                                            {
-                                                $user_login = $identity['preferredUsername'];
-                                            }
-                                            elseif (!empty($identity['displayName']))
-                                            {
-                                                $user_login = $identity['displayName'];
-                                            }
-                                            elseif (!empty($identity['name']['formatted']))
-                                            {
-                                                $user_login = $identity['name']['formatted'];
-                                            }
-                                            else
-                                            {
-                                                $user_login = trim($user_first_name . ' ' . $user_last_name);
-                                            }
-
-                                            // The username cannot begin/end with a space.
-                                            $user_login = trim ($user_login);
-
-                                            // The username cannot contain multiple spaces in a row.
-                                            $user_login = preg_replace('!\s+!', ' ', $user_login);
-
-                                            // Setup username.
-                                            if (strlen(trim($user_login)) == 0)
-                                            {
-                                                $user_login = $provider_name . $this->t('User');
-                                            }
-
-                                            // Forge unique username.
-                                            if (social_login_get_uid_for_name(trim($user_login)) !== false)
-                                            {
-                                                $i = 1;
-                                                while (social_login_get_uid_for_name($user_login.$i) !== false)
-                                                {
-                                                    $i++;
-                                                }
-                                                $user_login = $user_login.$i;
-                                            }
-
-                                            // Forge password.
-                                            $user_password = user_password(8);
-
-                                            // Check the approval setting.
-                                            switch ($registration_approval)
-                                            {
-                                                // No approval required.
-                                                case 'disable':
-                                                    $user_status = 1;
-                                                    break;
-
-                                                // Manual approval required.
-                                                case 'enable':
-                                                    $user_status = 0;
-                                                    break;
-
-                                                // Use the system-wide setting.
-                                                default:
-                                                    $user_status = ((\Drupal::config('user.settings')->get('register') == USER_REGISTER_VISITORS) ? 1 : 0);
-                                                    break;
-                                            }
-
-                                            // Real user accounts get the authenticated user role.
-                                            $user_roles = [];
-
-                                            // Make sure at least one module implements our hook.
-                                            if (count(\Drupal::moduleHandler()->getImplementations('social_login_default_user_roles')) > 0)
-                                            {
-                                                // Call modules that implement the hook.
-                                                $user_roles = \Drupal::moduleHandler()->invokeAll('social_login_default_user_roles', $user_roles);
-                                            }
-
-                                            // Setup the user fields.
-                                            $user_fields = [
-                                                'name' => $user_login,
-                                                'mail' => $user_email,
-                                                'pass' => $user_password,
-                                                'status' => $user_status,
-                                                'init' => $user_email,
-                                                'roles' => $user_roles
-                                            ];
-
-                                            // Create a new user.
-                                            $account = \Drupal\user\Entity\User::create($user_fields);
-                                            $account->save();
-
-                                            // The new account has been created correctly.
-                                            if ($account !== false)
-                                            {
-                                                // Dispatches SocialLoginUserCreatedEvent event.
-                                                $event = new SocialLoginUserCreatedEvent ($account, $data);
-                                                $event_dispatcher = \Drupal::service('event_dispatcher');
-                                                $event_dispatcher->dispatch(SocialLoginUserCreatedEvent::EVENT_NAME, $event);
-
-                                                // Add log.
-                                                \Drupal::logger('social_login')->notice('@name has registered using @provider (@identity_token).', [
-                                                    '@name' => $user_login,
-                                                    '@provider' => $provider_name,
-                                                    '@identity_token' => $identity_token
-                                                ]);
-
-                                                // Disable Drupal legacy registration.
-                                                $registration_method = 'auto';
-
-                                                // Log the new user in.
-                                                if (($user = \Drupal\user\Entity\User::load($account->id(), true)) != null)
-                                                {
-                                                    // Login.
-                                                    user_login_finalize($user);
-
-                                                    // Dispatches SocialLoginUserLoginEvent event.
-                                                    $event = new SocialLoginUserLoginEvent ($user, $data);
-                                                    $event_dispatcher = \Drupal::service('event_dispatcher');
-                                                    $event_dispatcher->dispatch(SocialLoginUserLoginEvent::EVENT_NAME, $event);
-
-                                                    // Send email, but only if it's not a random address.
-                                                    if ($user_email_is_random !== true)
-                                                    {
-
-                                                        // No approval is required.
-                                                        if ($user_status == 1)
-                                                        {
-                                                            // Notif user.
-                                                            _user_mail_notify('register_no_approval_required', $user);
-
-                                                            // Add message.
-                                                            drupal_set_message($this->t('You have successfully created an account and linked it with your @social_network account.', [
-                                                                '@social_network' => $provider_name
-                                                            ]), 'status');
-
-                                                            // Redirect.
-                                                            return social_login_redirect ('settings.register', $user->id());
-                                                        }
-                                                        // Approval is required.
-                                                        else
-                                                        {
-                                                            // Notify user.
-                                                            _user_mail_notify('register_pending_approval', $user);
-
-                                                            // Add message.
-                                                            drupal_set_message($this->t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />You will receive an email once your account has been approved and you can then login with your @social_network account.', [
-                                                                '@social_network' => $provider_name
-                                                            ]), 'status');
-
-                                                            // Redirect.
-                                                            return social_login_redirect ('drupal.home');
-                                                        }
-                                                    }
-                                                    // Random email used.
-                                                    else
-                                                    {
-                                                        // Add message.
-                                                        drupal_set_message($this->t('You have successfully created an account and linked it with your @provider account.', [
-                                                            '@provider' => $provider_name
-                                                        ]), 'status');
-
-                                                        // Redirect.
-                                                        return social_login_redirect ('settings.register', $user->id());
-                                                    }
-                                                }
-                                                // For some reason we could not load the user.
-                                                else
-                                                {
-                                                    // Add user message.
-                                                    drupal_set_message($this->t('Error while logging you in, please try to login manually.'), 'error');
-
-                                                    // Add system log.
-                                                    \Drupal::logger('social_login')->error('Could not load user @name. User tried to registered using @provider (@identity_token).', [
-                                                        '@name' => $user_login,
-                                                        '@provider' => $provider_name,
-                                                        '@identity_token' => $identity_token
-                                                    ]);
-
-                                                    // Redirect to login page to login manually.
-                                                    return social_login_redirect ('drupal.login');
-                                                }
-                                            }
-                                            // An error occured during user_save().
-                                            else
-                                            {
-                                                // Add user message.
-                                                drupal_set_message($this->t('Error while creating your user account, please try to register manually.'), 'error');
-
-                                                // Add system log.
-                                                \Drupal::logger('social_login')->error('Could not save account for user @name. User tried to registered using @provider (@identity_token).', [
-                                                    '@name' => $user_login,
-                                                    '@provider' => $provider_name,
-                                                    '@identity_token' => $identity_token
-                                                ]);
-
-                                                // Redirect to registration page to register manually.
-                                                return social_login_redirect ('drupal.register');
-                                            }
-                                        }
-
-                                        // Use the legacy registration form?
-                                        if ($registration_method == 'manual')
-                                        {
-                                            // Go to the registration page (+ prepopulate form).
-                                            return social_login_redirect ('drupal.register');
-                                        }
-                                    }
-                                    // Registration is disabled.
-                                    else
-                                    {
-                                        // Add log.
-                                        \Drupal::logger('social_login')->error('Could not create account for user @name. Only admins may create accounts. User tried to registered using @provider (@identity_token).', [
-                                            '@name' => $user_login,
-                                            '@provider' => $provider_name,
-                                            '@identity_token' => $identity_token
-                                        ]);
-
-                                        // Add message.
-                                        drupal_set_message($this->t('Only site administrators can create new user accounts.'), 'error');
-
-                                        // Return to homepage.
-                                        return social_login_redirect ('drupal.home');
-                                    }
-                                }
-                            }
-                        }
-                        // Error
-                        else
-                        {
-                            // Success
-                            if ($social_data['response']['request']['status']['code'] == 400)
-                            {
-                                // Link identity.
-                                if ($data['plugin']['data']['action'] == 'link_identity')
-                                {
-                                    // Already linked.
-                                    if ($data['plugin']['data']['reason'] == 'identity_is_linked_to_another_user')
-                                    {
-                                        // Add user message.
-                                        drupal_set_message($this->t('This social network account is already linked to another user. First logout and then login with that social network account.'), 'error');
-
-                                        // Redirect to previous page.
-                                        if (!empty($_GET['origin']))
-                                        {
-                                            return social_login_redirect ('custom.url', $_GET['origin']);
-                                        }
-                                        // Redirect to profile page.
-                                        else
-                                        {
-                                            return social_login_redirect ('drupal.profile');
-                                        }
-                                    }
-                                }
-                            }
-                        }
+class SocialLoginController extends ControllerBase {
+
+  protected $messenger;
+
+  /**
+   * Constructor for the Social Login Controller.
+   *
+   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
+   *   Messenger service interface.
+   */
+  public function __construct(MessengerInterface $messenger) {
+    $this->messenger = $messenger;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function create(ContainerInterface $container) {
+    return new static(
+      $container->get('messenger')
+     );
+  }
+
+  /**
+   * This is the callback handler (referenced by routing.yml).
+   */
+  public function callbackHandler() {
+    // Read Settings.
+    $settings = social_login_get_settings();
+
+    // No need to do anything if we haven't received these arguments.
+    if (isset($_POST) && !empty($_POST['connection_token']) && !empty($_POST['oa_action']) && in_array($_POST['oa_action'], ['social_login', 'social_link'])) {
+      // Add system log.
+      \Drupal::logger('social_login')->notice('Callback handler called using connection_token @connection_token.', [
+        '@connection_token' => $_POST['connection_token'],
+      ]);
+
+      // Clear session.
+      social_login_clear_session();
+
+      // API Connection Credentials.
+      $api_subdomain = (!empty($settings['api_subdomain']) ? $settings['api_subdomain'] : '');
+      $api_key = (!empty($settings['api_key']) ? $settings['api_key'] : '');
+      $api_secret = (!empty($settings['api_secret']) ? $settings['api_secret'] : '');
+
+      // API Connection Handler.
+      $handler = (!empty($settings['http_handler']) ? $settings['http_handler'] : 'curl');
+      $handler = ($handler == 'fsockopen' ? 'fsockopen' : 'curl');
+
+      // API Connection Protocol.
+      $protocol = (!empty($settings['http_protocol']) ? $settings['http_protocol'] : 'https');
+      $protocol = ($protocol == 'http' ? 'http' : 'https');
+
+      // Automatic or manual registration?
+      $registration_method = (!empty($settings['registration_method']) ? $settings['registration_method'] : '');
+      $registration_method = (in_array($registration_method, ['manual', 'auto_random_email', 'auto_manual_email']) ? $registration_method : 'manual');
+
+      // Require approval?
+      $registration_approval = (!empty($settings['registration_approval']) ? $settings['registration_approval'] : '');
+      $registration_approval = (in_array($registration_approval, ['inherit', 'disable', 'enable']) ? $registration_approval : 'inherit');
+
+      // Retrieved connection_token.
+      $token = trim($_POST['connection_token']);
+
+      // Settings missing.
+      if (empty($api_subdomain) || empty($api_key) || empty($api_secret)) {
+
+        // User message.
+        if (isset($message)) {
+          $this->messenger->addMessage($this->t('OneAll Social Login is not setup correctly, please request the administrator to verify the API Settings', 'error'));
+        }
+        // Add log.
+        \Drupal::logger('social_login')->error('Unable to use Social Login, the API Settings are not filled out correctly.');
+
+        // Redirect to homepage.
+        return social_login_redirect('drupal.home');
+      }
+      // Settings filled out.
+      else {
+        // Request connection details.
+        $data = social_login_do_api_request($handler, $protocol . '://' . $api_subdomain . '.api.oneall.com/connections/' . $token . '.json', [
+          'api_key' => $api_key,
+          'api_secret' => $api_secret,
+        ]);
+
+        if (is_array($data) && !empty($data['http_data'])) {
+          // Decode result.
+          $social_data = Json::decode($data['http_data']);
+
+          // Everything seems to be ok.
+          if (is_array($social_data) && isset($social_data['response']) && isset($social_data['response']['result']['status']['code'])) {
+            // Retrieve the response data.
+            $data = $social_data['response']['result']['data'];
+
+            // Success.
+            if ($social_data['response']['result']['status']['code'] == 200) {
+              // Save the social network data in a session.
+              $_SESSION['social_login_session_open'] = 1;
+              $_SESSION['social_login_social_data'] = serialize($social_data);
+
+              // Unique user_token.
+              $user_token = $data['user']['user_token'];
+
+              // Extract identity.
+              $identity = $data['user']['identity'];
+
+              // Unique identity_token.
+              $identity_token = $identity['identity_token'];
+
+              // Social Network that has been used to connect.
+              $provider_name = (!empty($identity['source']['name']) ? $identity['source']['name'] : $this->t('Unkown'));
+
+              // Try restoring the user for the token.
+              $user_for_token = social_login_get_user_for_user_token($user_token);
+
+              // Existing user.
+              if (is_object($user_for_token) && !empty($user_for_token->id())) {
+                // Existing User Token: Social Login.
+                if ($data['plugin']['key'] == 'social_login') {
+                  // Make sure that the user has not been blocked.
+                  $name = $user_for_token->get('name')->value;
+
+                  // The user is not blocked.
+                  if (!user_is_blocked($name)) {
+                    // Login the user.
+                    user_login_finalize($user_for_token);
+
+                    // Dispatches SocialLoginUserLoginEvent event.
+                    $event = new SocialLoginUserLoginEvent($user_for_token, $data);
+                    $event_dispatcher = \Drupal::service('event_dispatcher');
+                    $event_dispatcher->dispatch(SocialLoginUserLoginEvent::EVENT_NAME, $event);
+
+                    // Clear session.
+                    social_login_clear_session();
+
+                    // Redirect to specified page.
+                    return social_login_redirect('settings.login', $user_for_token->id());
+                  }
+                  // The user is blocked.
+                  else {
+                    // User message.
+                    $this->messenger->addMessage($this->t('Your account is blocked.'), 'error');
+
+                    // Clear session.
+                    social_login_clear_session();
+
+                    // Redirect to home.
+                    return social_login_redirect('drupal.home');
+                  }
+                }
+                // Existing User Token: Social Link.
+                elseif ($data['plugin']['key'] == 'social_link') {
+                  // The user must be logged in.
+                  $session = \Drupal::currentUser();
+
+                  // User is logged in.
+                  if (is_object($session) && $session->isAuthenticated()) {
+                    // Load user.
+                    $user = \Drupal::entityTypeManager()->getStorage('user')->load($session->id());
+
+                    // The existing token does not match the current user!
+                    if ($user_for_token->id() != $user->id()) {
+                      $this->messenger->addMessage($this->t('This @social_network account is already linked to another user.', [
+                        '@social_network' => $provider_name,
+                      ]), 'error');
                     }
-                    // Invalid response.
-                    else
-                    {
+                    // The existing token matches the current user!
+                    else {
+                      // Link identity.
+                      if ($data['plugin']['data']['action'] == 'link_identity') {
+                        // Add mapping.
+                        if (social_login_map_identity_token_to_user_token($user, $identity_token, $user_token, $provider_name)) {
+                          // Dispatches SocialLoginUserLinkedEvent event.
+                          $event = new SocialLoginUserLinkedEvent($user, $data);
+                          $event_dispatcher = \Drupal::service('event_dispatcher');
+                          $event_dispatcher->dispatch(SocialLoginUserLinkedEvent::EVENT_NAME, $event);
+
+                          // Add user message.
+                          $this->messenger->addMessage($this->t('The @social_network account has been linked to your account.', [
+                            '@social_network' => $provider_name,
+                          ]), 'status');
+
+                          // Add log.
+                          \Drupal::logger('social_login')->notice('@name has linked his @provider account, identity @identity_token.', [
+                            '@name' => $user->getAccountName(),
+                            '@provider' => $provider_name,
+                            '@identity_token' => $identity_token,
+                          ]);
+                        }
+                      }
+                      // Unlink identity.
+                      else {
+                        // Remove mapping.
+                        social_login_unmap_identity_token($identity_token);
+
                         // Add user message.
-                        drupal_set_message($this->t('OneAll Social Login is not setup correctly, please request the administrator to verify the API Settings'), 'error');
+                        $this->messenger->addMessage($this->t('The social network account has been unlinked from your account.'), 'status');
 
                         // Add log.
-                        \Drupal::logger('social_login')->error('Invalid RESPONSE received from OneAll API.');
+                        \Drupal::logger('social_login')->notice('@name has unlinked a social network account, identity @identity_token.', [
+                          '@name' => $user->getAccountName(),
+                          '@identity_token' => $identity_token,
+                        ]);
+                      }
+
+                      // Clear session.
+                      social_login_clear_session();
+                    }
 
-                        // Return to homepage.
-                        return social_login_redirect ('drupal.home');
+                    // Redirect to previous page.
+                    if (!empty($_GET['origin'])) {
+                      return social_login_redirect('custom.url', $_GET['origin']);
+                    }
+                    // Redirect to profile page.
+                    else {
+                      return social_login_redirect('drupal.profile');
                     }
+                  }
+                  // User is not logged in.
+                  else {
+                    $this->messenger->addMessage($this->t('You must be logged in to perform this action.'), 'error');
+
+                    // Clear session.
+                    social_login_clear_session();
+
+                    // Redirect to home.
+                    return social_login_redirect('drupal.home');
+                  }
                 }
-                else
-                {
+              }
+              // New User.
+              else {
+                // No Existing User Token: Social Link.
+                if ($data['plugin']['key'] == 'social_link') {
+                  // The user should be logged in.
+                  $session = \Drupal::currentUser();
+
+                  // User is logged in.
+                  if (is_object($session) && $session->isAuthenticated()) {
+                    // Load user.
+                    $user = \Drupal::entityTypeManager()->getStorage('user')->load($session->id());
+
+                    // Link identity.
+                    if ($data['plugin']['data']['action'] == 'link_identity') {
+                      // Add mapping.
+                      if (social_login_map_identity_token_to_user_token($user, $identity_token, $user_token, $provider_name)) {
+                        // Dispatches SocialLoginUserLinkedEvent event.
+                        $event = new SocialLoginUserLinkedEvent($user, $data);
+                        $event_dispatcher = \Drupal::service('event_dispatcher');
+                        $event_dispatcher->dispatch(SocialLoginUserLinkedEvent::EVENT_NAME, $event);
+
+                        // Add user message.
+                        $this->messenger->addMessage($this->t('The @social_network account has been linked to your account.', [
+                          '@social_network' => $provider_name,
+                        ]), 'status');
+
+                        // Add log.
+                        \Drupal::logger('social_login')->notice('@name has linked his @provider account, identity @identity_token.', [
+                          '@name' => $user->getAccountName(),
+                          '@provider' => $provider_name,
+                          '@identity_token' => $identity_token,
+                        ]);
+                      }
+                    }
+                    // Unlink identity.
+                    else {
+                      // Remove mapping.
+                      social_login_unmap_identity_token($identity_token);
+
+                      // Add user message.
+                      $this->messenger->addMessage($this->t('The social network account has been unlinked from your account.'), 'status');
+                    }
+
+                    // Clear session.
+                    social_login_clear_session();
+
+                    // Redirect to previous page.
+                    if (!empty($_GET['origin'])) {
+                      return social_login_redirect('custom.url', $_GET['origin']);
+                    }
+                    // Redirect to profile page.
+                    else {
+                      return social_login_redirect('drupal.profile');
+                    }
+                  }
+                  // User is not logged in.
+                  else {
                     // Add user message.
-                    drupal_set_message($this->t('OneAll Social Login is not setup correctly, please request the administrator to verify the API Settings'), 'error');
+                    $this->messenger->addMessage($this->t('You must be logged in to perform this action.'), 'error');
+
+                    // Clear session.
+                    social_login_clear_session();
 
+                    // Redirect to home.
+                    return social_login_redirect('drupal.home');
+                  }
+                }
+                // No Existing User: Social Login (Default)
+                else {
+                  // New users may register.
+                  if (\Drupal::config('user.settings')->get('register') != UserInterface::REGISTER_ADMINISTRATORS_ONLY) {
+                    // Extract the user's email address.
+                    $user_email = '';
+                    $user_email_is_verified = NULL;
+                    $user_email_is_random = NULL;
+
+                    // Do we have any emails in the profile data?
+                    if (isset($identity['emails']) && is_array($identity['emails'])) {
+                      // Extract email address.
+                      foreach ($identity['emails'] as $email) {
+                        $user_email = $email['value'];
+                        $user_email_is_verified = (!empty($email['is_verified']) ? TRUE : FALSE);
+                        $user_email_is_random = FALSE;
+
+                        // Stop once we have found a verified email address.
+                        if ($user_email_is_verified) {
+                          break;
+                        }
+                      }
+                    }
+
+                    // The admin has chosen the automatic registration.
+                    if ($registration_method != 'manual') {
+                      // No email address / Email address already exists.
+                      if (empty($user_email) || social_login_get_uid_for_email($user_email) !== FALSE) {
+                        // The admin wants users to
+                        // fill out their email manually.
+                        if ($registration_method == 'auto_manual_email') {
+                          // We have to fall back to the default registration.
+                          $registration_method = 'manual';
+                        }
+                        // The admin has enabled the usage of random emails.
+                        else {
+                          // Create a bogus email.
+                          $user_email = social_login_create_random_email();
+
+                          // Flag - is used further down.
+                          $user_email_is_random = TRUE;
+                        }
+                      }
+                    }
+
+                    // Automatic registration is enabled.
+                    if ($registration_method != 'manual') {
+                      // If something goes wrong
+                      // fall back to manual registration.
+                      $registration_method = 'manual';
+
+                      // Extract firstname.
+                      $user_first_name = (!empty($identity['name']['givenName']) ? $identity['name']['givenName'] : '');
+
+                      // Extract lastname.
+                      $user_last_name = (!empty($identity['name']['familyName']) ? $identity['name']['familyName'] : '');
+
+                      // Forge login.
+                      $user_login = '';
+                      if (!empty($identity['preferredUsername'])) {
+                        $user_login = $identity['preferredUsername'];
+                      }
+                      elseif (!empty($identity['displayName'])) {
+                        $user_login = $identity['displayName'];
+                      }
+                      elseif (!empty($identity['name']['formatted'])) {
+                        $user_login = $identity['name']['formatted'];
+                      }
+                      else {
+                        $user_login = trim($user_first_name . ' ' . $user_last_name);
+                      }
+
+                      // The username cannot begin/end with a space.
+                      $user_login = trim($user_login);
+
+                      // The username cannot contain multiple spaces in a row.
+                      $user_login = preg_replace('!\s+!', ' ', $user_login);
+
+                      // Setup username.
+                      if (strlen(trim($user_login)) == 0) {
+                        $user_login = $provider_name . $this->t('User');
+                      }
+
+                      // Forge unique username.
+                      if (social_login_get_uid_for_name(trim($user_login)) !== FALSE) {
+                        $i = 1;
+                        while (social_login_get_uid_for_name($user_login . $i) !== FALSE) {
+                          $i++;
+                        }
+                        $user_login = $user_login . $i;
+                      }
+
+                      // Forge password.
+                      $user_password = user_password(8);
+
+                      // Check the approval setting.
+                      switch ($registration_approval) {
+                        // No approval required.
+                        case 'disable':
+                          $user_status = 1;
+                          break;
+
+                        // Manual approval required.
+                        case 'enable':
+                          $user_status = 0;
+                          break;
+
+                        // Use the system-wide setting.
+                        default:
+                          $user_status = ((\Drupal::config('user.settings')->get('register') == UserInterface::REGISTER_VISITORS) ? 1 : 0);
+                          break;
+                      }
+
+                      // Real user accounts get the authenticated user role.
+                      $user_roles = [];
+
+                      // Make sure at least one module implements our hook.
+                      if (count(\Drupal::moduleHandler()->getImplementations('social_login_default_user_roles')) > 0) {
+                        // Call modules that implement the hook.
+                        $user_roles = \Drupal::moduleHandler()->invokeAll('social_login_default_user_roles', $user_roles);
+                      }
+
+                      // Setup the user fields.
+                      $user_fields = [
+                        'name' => $user_login,
+                        'mail' => $user_email,
+                        'pass' => $user_password,
+                        'status' => $user_status,
+                        'init' => $user_email,
+                        'roles' => $user_roles,
+                      ];
+
+                      // Create a new user.
+                      $account = User::create($user_fields);
+                      $account->save();
+
+                      // The new account has been created correctly.
+                      if ($account !== FALSE) {
+                        // Dispatches SocialLoginUserCreatedEvent event.
+                        $event = new SocialLoginUserCreatedEvent($account, $data);
+                        $event_dispatcher = \Drupal::service('event_dispatcher');
+                        $event_dispatcher->dispatch(SocialLoginUserCreatedEvent::EVENT_NAME, $event);
+
+                        // Add log.
+                        \Drupal::logger('social_login')->notice('@name has registered using @provider (@identity_token).', [
+                          '@name' => $user_login,
+                          '@provider' => $provider_name,
+                          '@identity_token' => $identity_token,
+                        ]);
+
+                        // Disable Drupal legacy registration.
+                        $registration_method = 'auto';
+
+                        // Log the new user in.
+                        if (($user = User::load($account->id(), TRUE)) != NULL) {
+                          // Login.
+                          user_login_finalize($user);
+
+                          // Dispatches SocialLoginUserLoginEvent event.
+                          $event = new SocialLoginUserLoginEvent($user, $data);
+                          $event_dispatcher = \Drupal::service('event_dispatcher');
+                          $event_dispatcher->dispatch(SocialLoginUserLoginEvent::EVENT_NAME, $event);
+
+                          // Send email, but only if it's not a random address.
+                          if ($user_email_is_random !== TRUE) {
+                            // No approval is required.
+                            if ($user_status == 1) {
+                              // Notif user.
+                              _user_mail_notify('register_no_approval_required', $user);
+
+                              // Add message.
+                              $this->messenger->addMessage($this->t('You have successfully created an account and linked it with your @social_network account.', [
+                                '@social_network' => $provider_name,
+                              ]), 'status');
+
+                              // Redirect.
+                              return social_login_redirect('settings.register', $user->id());
+                            }
+                            // Approval is required.
+                            else {
+                              // Notify user.
+                              _user_mail_notify('register_pending_approval', $user);
+
+                              // Add message.
+                              $this->messenger->addMessage($this->t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />You will receive an email once your account has been approved and you can then login with your @social_network account.', [
+                                '@social_network' => $provider_name,
+                              ]), 'status');
+
+                              // Redirect.
+                              return social_login_redirect('drupal.home');
+                            }
+                          }
+                          // Random email used.
+                          else {
+                            // Add message.
+                            $this->messenger->addMessage($this->t('You have successfully created an account and linked it with your @provider account.', [
+                              '@provider' => $provider_name,
+                            ]), 'status');
+
+                            // Redirect.
+                            return social_login_redirect('settings.register', $user->id());
+                          }
+                        }
+                        // For some reason we could not load the user.
+                        else {
+                          // Add user message.
+                          $this->messenger->addMessage($this->t('Error while logging you in, please try to login manually.'), 'error');
+
+                          // Add system log.
+                          \Drupal::logger('social_login')->error('Could not load user @name. User tried to registered using @provider (@identity_token).', [
+                            '@name' => $user_login,
+                            '@provider' => $provider_name,
+                            '@identity_token' => $identity_token,
+                          ]);
+
+                          // Redirect to login page to login manually.
+                          return social_login_redirect('drupal.login');
+                        }
+                      }
+                      // An error occured during user_save().
+                      else {
+                        // Add user message.
+                        $this->messenger->addMessage($this->t('Error while creating your user account, please try to register manually.'), 'error');
+
+                        // Add system log.
+                        \Drupal::logger('social_login')->error('Could not save account for user @name. User tried to registered using @provider (@identity_token).', [
+                          '@name' => $user_login,
+                          '@provider' => $provider_name,
+                          '@identity_token' => $identity_token,
+                        ]);
+
+                        // Redirect to registration page to register manually.
+                        return social_login_redirect('drupal.register');
+                      }
+                    }
+
+                    // Use the legacy registration form?
+                    if ($registration_method == 'manual') {
+                      // Go to the registration page (+ prepopulate form).
+                      return social_login_redirect('drupal.register');
+                    }
+                  }
+                  // Registration is disabled.
+                  else {
                     // Add log.
-                    \Drupal::logger('social_login')->error('Invalid JSON received from OneAll API.');
+                    \Drupal::logger('social_login')->error('Could not create account for user @name. Only admins may create accounts. User tried to registered using @provider (@identity_token).', [
+                      '@name' => $user_login,
+                      '@provider' => $provider_name,
+                      '@identity_token' => $identity_token,
+                    ]);
+
+                    // Add message.
+                    $this->messenger->addMessage($this->t('Only site administrators can create new user accounts.'), 'error');
 
                     // Return to homepage.
-                    return social_login_redirect ('drupal.home');
+                    return social_login_redirect('drupal.home');
+                  }
                 }
+              }
             }
-        }
-        // Invalid callback arguments.
-        else
-        {
+            // Error.
+            else {
+              // Success.
+              if ($social_data['response']['request']['status']['code'] == 400) {
+                // Link identity.
+                if ($data['plugin']['data']['action'] == 'link_identity') {
+                  // Already linked.
+                  if ($data['plugin']['data']['reason'] == 'identity_is_linked_to_another_user') {
+                    // Add user message.
+                    $this->messenger->addMessage($this->t('This social network account is already linked to another user. First logout and then login with that social network account.'), 'error');
+
+                    // Redirect to previous page.
+                    if (!empty($_GET['origin'])) {
+                      return social_login_redirect('custom.url', $_GET['origin']);
+                    }
+                    // Redirect to profile page.
+                    else {
+                      return social_login_redirect('drupal.profile');
+                    }
+                  }
+                }
+              }
+            }
+          }
+          // Invalid response.
+          else {
+            // Add user message.
+            $this->messenger->addMessage($this->t('OneAll Social Login is not setup correctly, please request the administrator to verify the API Settings'), 'error');
+
+            // Add log.
+            \Drupal::logger('social_login')->error('Invalid RESPONSE received from OneAll API.');
+
             // Return to homepage.
-            return social_login_redirect ('drupal.home');
+            return social_login_redirect('drupal.home');
+          }
         }
+        else {
+          // Add user message.
+          $this->messenger->addMessage($this->t('OneAll Social Login is not setup correctly, please request the administrator to verify the API Settings'), 'error');
 
-        // Some other unhandled case.
-        return social_login_redirect ('drupal.home');
+          // Add log.
+          \Drupal::logger('social_login')->error('Invalid JSON received from OneAll API.');
+
+          // Return to homepage.
+          return social_login_redirect('drupal.home');
+        }
+      }
     }
+    // Invalid callback arguments.
+    else {
+      // Return to homepage.
+      return social_login_redirect('drupal.home');
+    }
+
+    // Some other unhandled case.
+    return social_login_redirect('drupal.home');
+  }
+
 }
diff --git a/src/Event/SocialLoginUserCreatedEvent.php b/src/Event/SocialLoginUserCreatedEvent.php
index cb995e2..276b5a7 100644
--- a/src/Event/SocialLoginUserCreatedEvent.php
+++ b/src/Event/SocialLoginUserCreatedEvent.php
@@ -2,61 +2,61 @@
 
 namespace Drupal\social_login\Event;
 
+use Drupal\user\Entity\User;
 use Symfony\Component\EventDispatcher\Event;
 
 /**
  * Class SocialLoginUserCreatedEvent.
  */
-class SocialLoginUserCreatedEvent extends Event
-{
-    // The name of this event.
-    const EVENT_NAME = 'social_login_user_created';
-
-    // The Drupal user account that was created.
-    public $account;
-
-    // The retrieved social network profile data.
-    public $social_network_profile_data;
-
-    /**
-     * Constructor.
-     */
-    public function __construct(\Drupal\user\Entity\User $account, $social_network_profile_data)
-    {
-        $this->set_account($account);
-        $this->set_social_network_profile_data($social_network_profile_data);
-    }
-
-    /**
-     * Sets the social network profile data.
-     */
-    public function set_social_network_profile_data($social_network_profile_data)
-    {
-        $this->social_network_profile_data = $social_network_profile_data;
-    }
-
-    /**
-     * Returns the social network profile data.
-     */
-    public function get_social_network_profile_data()
-    {
-        return $this->social_network_profile_data;
-    }
-
-    /**
-     * Sets the user account.
-     */
-    public function set_account(\Drupal\user\Entity\User $account)
-    {
-        $this->account = $account;
-    }
-
-    /**
-     * Returns the user account.
-     */
-    public function get_account()
-    {
-        return $this->account;
-    }
-
-}
\ No newline at end of file
+class SocialLoginUserCreatedEvent extends Event {
+  // The name of this event.
+  const EVENT_NAME = 'social_login_user_created';
+
+  /**
+   * The Drupal user account that was created.
+   */
+  public $account;
+
+  /**
+   * The retrieved social network profile data.
+   *
+   */
+  public $social_network_profile_data;
+
+  /**
+   * Constructor.
+   */
+  public function __construct(User $account, $social_network_profile_data) {
+    $this->set_account($account);
+    $this->set_social_network_profile_data($social_network_profile_data);
+  }
+
+  /**
+   * Sets the social network profile data.
+   */
+  public function set_social_network_profile_data($social_network_profile_data) {
+    $this->social_network_profile_data = $social_network_profile_data;
+  }
+
+  /**
+   * Returns the social network profile data.
+   */
+  public function get_social_network_profile_data() {
+    return $this->social_network_profile_data;
+  }
+
+  /**
+   * Sets the user account.
+   */
+  public function set_account(User $account) {
+    $this->account = $account;
+  }
+
+  /**
+   * Returns the user account.
+   */
+  public function get_account() {
+    return $this->account;
+  }
+
+}
diff --git a/src/Event/SocialLoginUserLinkedEvent.php b/src/Event/SocialLoginUserLinkedEvent.php
index 43ddc67..4a50b63 100644
--- a/src/Event/SocialLoginUserLinkedEvent.php
+++ b/src/Event/SocialLoginUserLinkedEvent.php
@@ -2,61 +2,60 @@
 
 namespace Drupal\social_login\Event;
 
+use Drupal\user\Entity\User;
 use Symfony\Component\EventDispatcher\Event;
 
 /**
  * Class SocialLoginUserLinkedEvent.
  */
-class SocialLoginUserLinkedEvent extends Event
-{
-    // The name of this event.
-    const EVENT_NAME = 'social_login_user_linked';
-
-    // The Drupal user account that was logged in.
-    public $account;
-
-    // The retrieved social network profile data.
-    public $social_network_profile_data;
-
-    /**
-     * Constructor.
-     */
-    public function __construct(\Drupal\user\Entity\User $account, $social_network_profile_data)
-    {
-        $this->set_account($account);
-        $this->set_social_network_profile_data($social_network_profile_data);
-    }
-
-    /**
-     * Sets the social network profile data.
-     */
-    public function set_social_network_profile_data($social_network_profile_data)
-    {
-        $this->social_network_profile_data = $social_network_profile_data;
-    }
-
-    /**
-     * Returns the social network profile data.
-     */
-    public function get_social_network_profile_data()
-    {
-        return $this->social_network_profile_data;
-    }
-
-    /**
-     * Sets the user account.
-     */
-    public function set_account(\Drupal\user\Entity\User $account)
-    {
-        $this->account = $account;
-    }
-
-    /**
-     * Returns the user account.
-     */
-    public function get_account()
-    {
-        return $this->account;
-    }
-
-}
\ No newline at end of file
+class SocialLoginUserLinkedEvent extends Event {
+  // The name of this event.
+  const EVENT_NAME = 'social_login_user_linked';
+
+  /**
+   * The Drupal user account that was logged in.
+   */
+  public $account;
+
+  /**
+   * The retrieved social network profile data.
+   */
+  public $social_network_profile_data;
+
+  /**
+   * Constructor.
+   */
+  public function __construct(User $account, $social_network_profile_data) {
+    $this->set_account($account);
+    $this->set_social_network_profile_data($social_network_profile_data);
+  }
+
+  /**
+   * Sets the social network profile data.
+   */
+  public function set_social_network_profile_data($social_network_profile_data) {
+    $this->social_network_profile_data = $social_network_profile_data;
+  }
+
+  /**
+   * Returns the social network profile data.
+   */
+  public function get_social_network_profile_data() {
+    return $this->social_network_profile_data;
+  }
+
+  /**
+   * Sets the user account.
+   */
+  public function set_account(User $account) {
+    $this->account = $account;
+  }
+
+  /**
+   * Returns the user account.
+   */
+  public function get_account() {
+    return $this->account;
+  }
+
+}
diff --git a/src/Event/SocialLoginUserLoginEvent.php b/src/Event/SocialLoginUserLoginEvent.php
index 69424e4..5eafef1 100644
--- a/src/Event/SocialLoginUserLoginEvent.php
+++ b/src/Event/SocialLoginUserLoginEvent.php
@@ -2,61 +2,60 @@
 
 namespace Drupal\social_login\Event;
 
+use Drupal\user\Entity\User;
 use Symfony\Component\EventDispatcher\Event;
 
 /**
  * Class SocialLoginUserLoginEvent.
  */
-class SocialLoginUserLoginEvent extends Event
-{
-    // The name of this event.
-    const EVENT_NAME = 'social_login_user_login';
-
-    // The Drupal user account that has linked the social network account.
-    public $account;
-
-    // The retrieved social network profile data.
-    public $social_network_profile_data;
-
-    /**
-     * Constructor.
-     */
-    public function __construct(\Drupal\user\Entity\User $account, $social_network_profile_data)
-    {
-        $this->set_account($account);
-        $this->set_social_network_profile_data($social_network_profile_data);
-    }
-
-    /**
-     * Sets the social network profile data.
-     */
-    public function set_social_network_profile_data($social_network_profile_data)
-    {
-        $this->social_network_profile_data = $social_network_profile_data;
-    }
-
-    /**
-     * Returns the social network profile data.
-     */
-    public function get_social_network_profile_data()
-    {
-        return $this->social_network_profile_data;
-    }
-
-    /**
-     * Sets the user account.
-     */
-    public function set_account(\Drupal\user\Entity\User $account)
-    {
-        $this->account = $account;
-    }
-
-    /**
-     * Returns the user account.
-     */
-    public function get_account()
-    {
-        return $this->account;
-    }
-
-}
\ No newline at end of file
+class SocialLoginUserLoginEvent extends Event {
+  // The name of this event.
+  const EVENT_NAME = 'social_login_user_login';
+
+  /**
+   * The Drupal user account that has linked the social network account.
+   */
+  public $account;
+
+  /**
+   * The retrieved social network profile data.
+   */
+  public $social_network_profile_data;
+
+  /**
+   * Constructor.
+   */
+  public function __construct(User $account, $social_network_profile_data) {
+    $this->set_account($account);
+    $this->set_social_network_profile_data($social_network_profile_data);
+  }
+
+  /**
+   * Sets the social network profile data.
+   */
+  public function set_social_network_profile_data($social_network_profile_data) {
+    $this->social_network_profile_data = $social_network_profile_data;
+  }
+
+  /**
+   * Returns the social network profile data.
+   */
+  public function get_social_network_profile_data() {
+    return $this->social_network_profile_data;
+  }
+
+  /**
+   * Sets the user account.
+   */
+  public function set_account(User $account) {
+    $this->account = $account;
+  }
+
+  /**
+   * Returns the user account.
+   */
+  public function get_account() {
+    return $this->account;
+  }
+
+}
diff --git a/src/Form/SocialLoginAdminSettings.php b/src/Form/SocialLoginAdminSettings.php
index 85db77c..3ac22b5 100644
--- a/src/Form/SocialLoginAdminSettings.php
+++ b/src/Form/SocialLoginAdminSettings.php
@@ -2,6 +2,8 @@
 
 namespace Drupal\social_login\Form;
 
+use Drupal;
+use Drupal\Core\Database\Database;
 use Drupal\Core\Form\ConfigFormBase;
 use Drupal\Core\Form\FormStateInterface;
 use Drupal\Component\Utility\Html;
@@ -46,7 +48,7 @@ class SocialLoginAdminSettings extends ConfigFormBase {
     ];
 
     // Default value for handler.
-    if ($form_state->getValue(['http_handler',])) {
+    if ($form_state->getValue(['http_handler'])) {
       $default = $form_state->getValue([
         'http_handler',
       ]);
@@ -112,28 +114,26 @@ class SocialLoginAdminSettings extends ConfigFormBase {
     ];
 
     // Existing account.
-    if ( ! empty ($settings['api_subdomain']))
-    {
-        $form['social_login_api_settings'] = [
-          '#type' => 'fieldset',
-          '#title' => $this->t('API Settings'),
-          '#id' => 'social_login_api_settings',
-          '#description' => $this->t('<br /><a href="@setup_social_login" target="_blank"><strong>Access API credentials</strong></a>', [
-            '@setup_social_login' => 'https://app.oneall.com/applications/',
-          ]),
-        ];
+    if (!empty($settings['api_subdomain'])) {
+      $form['social_login_api_settings'] = [
+        '#type' => 'fieldset',
+        '#title' => $this->t('API Settings'),
+        '#id' => 'social_login_api_settings',
+        '#description' => $this->t('<br /><a href="@setup_social_login" target="_blank"><strong>Access API credentials</strong></a>', [
+          '@setup_social_login' => 'https://app.oneall.com/applications/',
+        ]),
+      ];
     }
     // New account.
-    else
-    {
-        $form['social_login_api_settings'] = [
-            '#type' => 'fieldset',
-            '#title' => $this->t('API Settings'),
-            '#id' => 'social_login_api_settings',
-            '#description' => $this->t('<br /><a href="@setup_social_login" target="_blank" class="button button--primary"><strong>Create a free account and generate my API credentials</strong></a>', [
-                '@setup_social_login' => 'https://app.oneall.com/signup/dp',
-            ]),
-        ];
+    else {
+      $form['social_login_api_settings'] = [
+        '#type' => 'fieldset',
+        '#title' => $this->t('API Settings'),
+        '#id' => 'social_login_api_settings',
+        '#description' => $this->t('<br /><a href="@setup_social_login" target="_blank" class="button button--primary"><strong>Create a free account and generate my API credentials</strong></a>', [
+          '@setup_social_login' => 'https://app.oneall.com/signup/dp',
+        ]),
+      ];
     }
 
     // API Subdomain.
@@ -304,46 +304,46 @@ class SocialLoginAdminSettings extends ConfigFormBase {
 
     // Redirection settings.
     $form['social_login_settings_redirection'] = [
-        '#type' => 'fieldset',
-        '#title' => $this->t('Redirection settings'),
+      '#type' => 'fieldset',
+      '#title' => $this->t('Redirection settings'),
     ];
 
     $form['social_login_settings_redirection']['redirect_login_path'] = [
-        '#type' => 'select',
-        '#default_value' => (empty($settings['redirect_login_path']) ? 'home' : $settings['redirect_login_path']),
-        '#title' => $this->t('When existing users login with Social Login ...'),
-        '#options' => [
-            'home' => $this->t('... redirect them to the homepage (Default)'),
-            'same' => $this->t('... redirect them back to the same page'),
-            'custom' => $this->t('... redirect them to the url below:'),
-        ],
+      '#type' => 'select',
+      '#default_value' => (empty($settings['redirect_login_path']) ? 'home' : $settings['redirect_login_path']),
+      '#title' => $this->t('When existing users login with Social Login ...'),
+      '#options' => [
+        'home' => $this->t('... redirect them to the homepage (Default)'),
+        'same' => $this->t('... redirect them back to the same page'),
+        'custom' => $this->t('... redirect them to the url below:'),
+      ],
     ];
 
     $form['social_login_settings_redirection']['redirect_login_custom_uri'] = [
-        '#type' => 'textfield',
-        '#default_value' => (!isset($settings['redirect_login_custom_uri']) ? '' : $settings['redirect_login_custom_uri']),
-        '#size' => 100,
-        '#maxlength' => 100,
-        '#description' => $this->t('You can use the placeholder {userid} in the URL. It is automatically replaced by the id of the user who has logged in.'),
+      '#type' => 'textfield',
+      '#default_value' => (!isset($settings['redirect_login_custom_uri']) ? '' : $settings['redirect_login_custom_uri']),
+      '#size' => 100,
+      '#maxlength' => 100,
+      '#description' => $this->t('You can use the placeholder {userid} in the URL. It is automatically replaced by the id of the user who has logged in.'),
     ];
 
     $form['social_login_settings_redirection']['redirect_register_path'] = [
-        '#type' => 'select',
-        '#default_value' => (empty($settings['redirect_register_path']) ? 'home' : $settings['redirect_register_path']),
-        '#title' => $this->t('When new users signup with Social Login ...'),
-        '#options' => [
-            'home' => $this->t('... redirect them to the homepage (Default)'),
-            'same' => $this->t('... redirect them back to the same page'),
-            'custom' => $this->t('... redirect them to the url below:'),
-        ],
+      '#type' => 'select',
+      '#default_value' => (empty($settings['redirect_register_path']) ? 'home' : $settings['redirect_register_path']),
+      '#title' => $this->t('When new users signup with Social Login ...'),
+      '#options' => [
+        'home' => $this->t('... redirect them to the homepage (Default)'),
+        'same' => $this->t('... redirect them back to the same page'),
+        'custom' => $this->t('... redirect them to the url below:'),
+      ],
     ];
 
     $form['social_login_settings_redirection']['redirect_register_custom_uri'] = [
-        '#type' => 'textfield',
-        '#default_value' => (!isset($settings['redirect_register_custom_uri']) ? '' : $settings['redirect_register_custom_uri']),
-        '#size' => 100,
-        '#maxlength' => 100,
-        '#description' => $this->t('You can use the placeholder {userid} in the URL. It is automatically replaced by the id of the user who has logged in.'),
+      '#type' => 'textfield',
+      '#default_value' => (!isset($settings['redirect_register_custom_uri']) ? '' : $settings['redirect_register_custom_uri']),
+      '#size' => 100,
+      '#maxlength' => 100,
+      '#description' => $this->t('You can use the placeholder {userid} in the URL. It is automatically replaced by the id of the user who has logged in.'),
     ];
 
     // Enable the social networks/identity providers.
@@ -410,60 +410,62 @@ class SocialLoginAdminSettings extends ConfigFormBase {
     // Remove Drupal stuff.
     $form_state->cleanValues();
 
-    // Settings
+    // Settings.
     $settings = $form_state->getValues();
 
     // API Subdomain.
-    if ( ! empty ($settings['subdomain'])) {
-        // The subdomain is always in lower-case.
-        $settings['subdomain'] = strtolower(trim($settings['subdomain']));
+    if (!empty($settings['subdomain'])) {
+      // The subdomain is always in lower-case.
+      $settings['subdomain'] = strtolower(trim($settings['subdomain']));
 
-        // Wrapper for full domains.
-        if (preg_match("/([a-z0-9\-]+)\.api\.oneall\.com/i", $settings['subdomain'], $matches)) {
-            $settings['subdomain'] = trim($matches[1]);
-        }
+      // Wrapper for full domains.
+      if (preg_match("/([a-z0-9\-]+)\.api\.oneall\.com/i", $settings['subdomain'], $matches)) {
+        $settings['subdomain'] = trim($matches[1]);
+      }
     }
 
     // Redirection \ signin.
-    if ( ! empty ($settings['redirect_login_path'])) {
-        if ($settings['redirect_login_path'] != 'custom') {
-            $settings['redirect_login_custom_uri'] = '';
-        } else {
-            if (empty ($settings['redirect_login_custom_uri'])) {
-                $settings['redirect_login_path'] = 'home';
-            }
+    if (!empty($settings['redirect_login_path'])) {
+      if ($settings['redirect_login_path'] != 'custom') {
+        $settings['redirect_login_custom_uri'] = '';
+      }
+      else {
+        if (empty($settings['redirect_login_custom_uri'])) {
+          $settings['redirect_login_path'] = 'home';
         }
+      }
     }
 
     // Redirection \ signup.
-    if ( ! empty ($settings['redirect_register_path'])) {
-        if ($settings['redirect_register_path'] != 'custom') {
-            $settings['redirect_register_custom_uri'] = '';
-        } else {
-            if (empty ($settings['redirect_register_custom_uri'])) {
-                $settings['redirect_register_path'] = 'home';
-            }
+    if (!empty($settings['redirect_register_path'])) {
+      if ($settings['redirect_register_path'] != 'custom') {
+        $settings['redirect_register_custom_uri'] = '';
+      }
+      else {
+        if (empty($settings['redirect_register_custom_uri'])) {
+          $settings['redirect_register_path'] = 'home';
         }
+      }
     }
 
     // Save values.
-    foreach ($settings AS $setting => $value) {
+    foreach ($settings as $setting => $value) {
 
       // Clean.
       $value = trim($value);
 
       // Check if settings already exists.
-      $oaslsid = db_select('oneall_social_login_settings', 'o')->fields('o', ['oaslsid',])->condition('setting', $setting, '=')->execute()->fetchField();
+      $oaslsid = Database::getConnection()->select('oneall_social_login_settings', 'o')->fields('o', ['oaslsid'])->condition('setting', $setting, '=')->execute()->fetchField();
       if (is_numeric($oaslsid)) {
         // Update setting.
-        db_update('oneall_social_login_settings')->fields(['value' => $value])->condition('oaslsid', $oaslsid, '=')->execute();
+        Database::getConnection()->update('oneall_social_login_settings')->fields(['value' => $value])->condition('oaslsid', $oaslsid, '=')->execute();
       }
       else {
         // Add setting.
-        db_insert('oneall_social_login_settings')->fields(['setting' => $setting, 'value' => $value])->execute();
+        Database::getConnection()->insert('oneall_social_login_settings')->fields(['setting' => $setting, 'value' => $value])->execute();
       }
     }
-    drupal_set_message(t('Settings saved successfully'), 'status social_login');
+    $this->messenger->addMessage(t('Settings saved successfully'), 'status social_login');
 
     // Clear cache.
     \Drupal::cache()->deleteAll();
@@ -471,9 +473,9 @@ class SocialLoginAdminSettings extends ConfigFormBase {
 
 }
 
-///////////////////////////////////////////////////////////////////////////////
+//
 // AJAX CALLBACKS
-///////////////////////////////////////////////////////////////////////////////
+// .
 
 /**
  * Form callback to autodetect the API connection handler.
@@ -485,26 +487,22 @@ function ajax_api_connection_autodetect($form, FormStateInterface $form_state) {
   $http_protocol = '';
 
   // CURL+HTTPS Works.
-  if (\social_login_check_curl('https'))
-  {
+  if (\social_login_check_curl('https')) {
     $http_handler = 'curl';
     $http_protocol = 'https';
   }
   // FSOCKOPEN+HTTPS Works.
-  elseif (\social_login_check_fsockopen('https'))
-  {
+  elseif (\social_login_check_fsockopen('https')) {
     $http_handler = 'fsockopen';
     $http_protocol = 'https';
   }
   // CURL+HTTP Works.
-  elseif (\social_login_check_curl('http'))
-  {
+  elseif (\social_login_check_curl('http')) {
     $http_handler = 'curl';
     $http_protocol = 'http';
   }
   // FSOCKOPEN+HTTP Works.
-  elseif (\social_login_check_fsockopen('http'))
-  {
+  elseif (\social_login_check_fsockopen('http')) {
     $http_handler = 'fsockopen';
     $http_protocol = 'http';
   }
@@ -513,14 +511,14 @@ function ajax_api_connection_autodetect($form, FormStateInterface $form_state) {
   if (!empty($http_handler)) {
     $form['social_login_api_connection']['http_handler']['#value'] = $http_handler;
     $form['social_login_api_connection']['http_protocol']['#value'] = $http_protocol;
-    drupal_set_message(t('Autodetected @handler on port @port - do not forget to save your changes!', [
+    Drupal::messenger()->addMessage(t('Autodetected @handler on port @port - do not forget to save your changes!', [
       '@handler' => ($http_handler == 'curl' ? 'PHP cURL' : 'PHP fsockopen'),
       '@port' => ($http_protocol == 'http' ? '80/HTTP' : '443/HTTPS'),
     ]), 'status social_login');
   }
   // Nothing works.
   else {
-    drupal_set_message(t('Sorry, but the autodetection failed. Please try to open port 80/443 for outbound requests and install PHP cURL/fsockopen.'), 'error social_login');
+    Drupal::messenger()->addMessage(t('Sorry, but the autodetection failed. Please try to open port 80/443 for outbound requests and install PHP cURL/fsockopen.'), 'error social_login');
   }
   return $form['social_login_api_connection'];
 }
@@ -559,7 +557,7 @@ function ajax_check_api_connection_settings($form, FormStateInterface $form_stat
 
     // Wrong syntax.
     if (!preg_match("/^[a-z0-9\-]+$/i", $api_subdomain)) {
-      $error_message = $this->t('The subdomain has a wrong syntax! Have you filled it out correctly?');
+      $error_message = t('The subdomain has a wrong syntax! Have you filled it out correctly?');
     }
     // Syntax seems to be OK.
     else {
@@ -604,10 +602,10 @@ function ajax_check_api_connection_settings($form, FormStateInterface $form_stat
 
   // Error.
   if (!empty($success_message)) {
-    drupal_set_message($success_message, 'status social_login');
+    Drupal::messenger()->addMessage($success_message, 'status social_login');
   }
   else {
-    drupal_set_message($error_message, 'error social_login');
+    Drupal::messenger()->addMessage($error_message, 'error social_login');
   }
   return $form['social_login_api_settings'];
 }
diff --git a/src/Form/SocialLoginBlock.php b/src/Form/SocialLoginBlock.php
index dd7464e..dcdda4c 100644
--- a/src/Form/SocialLoginBlock.php
+++ b/src/Form/SocialLoginBlock.php
@@ -6,87 +6,83 @@ use Drupal;
 use Drupal\Core\Form\FormBase;
 use Drupal\Core\Form\FormStateInterface;
 use Drupal\Core\Url;
-use Symfony\Component\HttpFoundation\Request;
 
 /**
  * Builds the form for the Social Login block.
  */
-class SocialLoginBlock extends FormBase
-{
-    /**
-     * Determines the ID of the form.
-     */
-    public function getFormId()
-    {
-        return 'social_login_block_form';
-    }
-
-    /**
-     * Gets the configuration names that will be editable.
-     */
-    public function getEditableConfigNames()
-    {
-        return [];
-    }
-
-    /**
-     * Form submission handler.
-     */
-    public function submitForm(array &$form, FormStateInterface $form_state)
-    {
-    }
-
-    /**
-     * Form constructor.
-     */
-    public function buildForm(array $form, FormStateInterface $form_state)
-    {
-        // Are we using HTTPs?
-        $is_https = Drupal::request()->isSecure();
-
-        // Read Settings.
-        $settings = \social_login_get_settings();
-
-        // Container.
-        $containerid = 'social_login_providers_' . rand(99999, 9999999);
-
-        // Add library.
-        social_login_add_js_plugin($form, $settings['api_subdomain']);
-
-        // Get the current url.
-        $current_uri = \social_login_get_current_url($is_https);
-
-        // Build callback url.
-        $callback_uri = Url::fromRoute('social_login.controller', [], [
-            'absolute' => true,
-            'query' => [
-                'origin' => $current_uri
-            ]
-        ])->toString();
-
-        // Social login form.
-        $form['social_login'] = [
-            '#theme' => 'provider_container',
-            '#label' => $settings['login_page_caption'],
-            '#weight' => 0,
-            '#containerid' => $containerid,
-            '#plugintype' => 'social_login',
-            '#providers' => $settings['enabled_providers'],
-            '#token' => '',
-            '#callbackuri' => $callback_uri,
-            // The cache tag is the callback uri (redirect to the same page).
-            '#cache' => [
-                'contexts' => [
-                    'url'
-                ]
-            ]
-        ];
-
-        // Prevent caching.
-        $renderer = \Drupal::service('renderer');
-        $renderer->addCacheableDependency($form, $callback_uri);
-
-        // Done.
-        return $form;
-    }
+class SocialLoginBlock extends FormBase {
+
+  /**
+   * Determines the ID of the form.
+   */
+  public function getFormId() {
+    return 'social_login_block_form';
+  }
+
+  /**
+   * Gets the configuration names that will be editable.
+   */
+  public function getEditableConfigNames() {
+    return [];
+  }
+
+  /**
+   * Form submission handler.
+   */
+  public function submitForm(array &$form, FormStateInterface $form_state) {
+  }
+
+  /**
+   * Form constructor.
+   */
+  public function buildForm(array $form, FormStateInterface $form_state) {
+    // Are we using HTTPs?
+    $is_https = Drupal::request()->isSecure();
+
+    // Read Settings.
+    $settings = \social_login_get_settings();
+
+    // Container.
+    $containerid = 'social_login_providers_' . rand(99999, 9999999);
+
+    // Add library.
+    social_login_add_js_plugin($form, $settings['api_subdomain']);
+
+    // Get the current url.
+    $current_uri = \social_login_get_current_url($is_https);
+
+    // Build callback url.
+    $callback_uri = Url::fromRoute('social_login.controller', [], [
+      'absolute' => TRUE,
+      'query' => [
+        'origin' => $current_uri,
+      ],
+    ])->toString();
+
+    // Social login form.
+    $form['social_login'] = [
+      '#theme' => 'provider_container',
+      '#label' => $settings['login_page_caption'],
+      '#weight' => 0,
+      '#containerid' => $containerid,
+      '#plugintype' => 'social_login',
+      '#providers' => $settings['enabled_providers'],
+      '#token' => '',
+      '#callbackuri' => $callback_uri,
+          // The cache tag is the callback uri (redirect to the same page).
+      '#cache' => [
+        'contexts' => [
+          'url',
+        ],
+      ],
+    ];
+
+    // Prevent caching.
+    $renderer = \Drupal::service('renderer');
+    $renderer->addCacheableDependency($form, $callback_uri);
+
+    // Done.
+    return $form;
+  }
+
 }
diff --git a/src/Plugin/Block/SocialLoginBlock.php b/src/Plugin/Block/SocialLoginBlock.php
index e11c7a4..f3c6c6a 100644
--- a/src/Plugin/Block/SocialLoginBlock.php
+++ b/src/Plugin/Block/SocialLoginBlock.php
@@ -25,6 +25,12 @@ class SocialLoginBlock extends BlockBase {
 
   /**
    * Indicates whether the block should be shown.
+   *
+   * @param \Drupal\Core\Session\AccountInterface $account
+   *   Instance of the user's account.
+   *
+   * @return \Drupal\Core\Access\AccessResult
+   *   Returns access result for the account.
    */
   public function blockAccess(AccountInterface $account) {
     return AccessResult::allowedIf($account->isAnonymous());
@@ -36,4 +42,5 @@ class SocialLoginBlock extends BlockBase {
   public function build() {
     return \Drupal::formBuilder()->getForm('Drupal\social_login\Form\SocialLoginBlock');
   }
+
 }
