This project is not covered by Drupal’s security advisory policy.

Social auth Drupal simple OAuth module integrates social_auth and simple_oauth module, Provide single sign on function. server need install simple_oauth

install

composer require "drupal/social_auth_drupal_simple_oauth"

HOOK

use Symfony\Component\HttpFoundation\RedirectResponse;

function mymodule_social_auth_simple_oauth($data, $sdk) {
  $userId = $data->getId();
  $httpClient = \Drupal::httpClient();
  $config = \Drupal::configFactory()->get('social_auth_drupal_simple_oauth.settings');

  // server need enable restui module.
  // http://myserver.com/user/1
   $userInfo = $httpClient
    ->get($config->get('base_url') . '/user/' . $userId, [
      'query' => [
        '_format'      => 'json',
      ],
      'headers' => [
        'Authorization' => 'Bearer ' . $sdk->getAccessToken()->__toString()
      ]
    ])
    ->getBody()->getContents();

  $userInfo = \GuzzleHttp\json_decode($userInfo, TRUE);

  if (isset($userInfo['@context']['@language'])) {
    $userInfo = $userInfo[$userInfo['@context']['@language']];
  }

  $userInfo = array_map(function ($info) {
    if (count($info) == 1 && isset($info[0]['value'])) {
      return $info[0]['value'];
    }
  }, $userInfo);

  if (!isset($userInfo['mail'])) {
    exit('can\t get mail field');
  }

  $user = autoCreateUser($userInfo);

  if (!$user) {
    exit('user not found');
  }

  user_login_finalize($user);

  $destination = $controller->getDataHander()->get('login_destination');

  // If there was a destination parameter.
  if ($destination) {
    // Deletes the session key.
    $controller->dataHandler->set('login_destination', NULL);

    return new RedirectResponse(Url::fromUserInput($destination)->toString());
  }

  $response = new RedirectResponse(\Drupal\Core\Url::fromRoute('user.page')->toString());
  $response->send();
}

function autoCreateUser($userInfo) {
  $mail = $userInfo['mail'];
  $name = $userInfo['name'];
  $timezone = $userInfo['timezone'];

  $user = user_load_by_mail($mail);

  if (!$user) {
    if (user_load_by_name($name)) {
      $name = explode('@', $mail)[0] . $name;
    }
    $user = \Drupal\user\Entity\User::create([
      'name' => $name,
      'mail' => $mail,
      'status' => 1,
      'timezone' => $timezone,
    ]);
    $user->save();
  }
  return $user;
}

Project information

  • caution Seeking new maintainer
    The current maintainers are looking for new people to take ownership.
  • Module categories: Developer Tools
  • Created by xiukun.zhou on , updated
  • shield alertThis project is not covered by the security advisory policy.
    Use at your own risk! It may have publicly disclosed vulnerabilities.

Releases