You are here

class TwitterAuthController in Open Social 8.6

Same name and namespace in other branches
  1. 8.9 modules/custom/social_auth_twitter/src/Controller/TwitterAuthController.php \Drupal\social_auth_twitter\Controller\TwitterAuthController
  2. 8 modules/custom/social_auth_twitter/src/Controller/TwitterAuthController.php \Drupal\social_auth_twitter\Controller\TwitterAuthController
  3. 8.2 modules/custom/social_auth_twitter/src/Controller/TwitterAuthController.php \Drupal\social_auth_twitter\Controller\TwitterAuthController
  4. 8.3 modules/custom/social_auth_twitter/src/Controller/TwitterAuthController.php \Drupal\social_auth_twitter\Controller\TwitterAuthController
  5. 8.4 modules/custom/social_auth_twitter/src/Controller/TwitterAuthController.php \Drupal\social_auth_twitter\Controller\TwitterAuthController
  6. 8.5 modules/custom/social_auth_twitter/src/Controller/TwitterAuthController.php \Drupal\social_auth_twitter\Controller\TwitterAuthController
  7. 8.7 modules/custom/social_auth_twitter/src/Controller/TwitterAuthController.php \Drupal\social_auth_twitter\Controller\TwitterAuthController
  8. 8.8 modules/custom/social_auth_twitter/src/Controller/TwitterAuthController.php \Drupal\social_auth_twitter\Controller\TwitterAuthController

Manages requests to Twitter API.

Hierarchy

Expanded class hierarchy of TwitterAuthController

File

modules/custom/social_auth_twitter/src/Controller/TwitterAuthController.php, line 16

Namespace

Drupal\social_auth_twitter\Controller
View source
class TwitterAuthController extends ControllerBase {

  /**
   * The network plugin manager.
   *
   * @var \Drupal\social_api\Plugin\NetworkManager
   */
  private $networkManager;

  /**
   * The Twitter authentication manager.
   *
   * @var \Drupal\social_auth_twitter\TwitterAuthManager
   */
  private $authManager;

  /**
   * The current request.
   *
   * @var \Drupal\social_auth\SocialAuthUserManager
   */
  private $request;

  /**
   * Contains access token to work with API.
   *
   * @var \Abraham\TwitterOAuth\TwitterOAuth
   */
  protected $accessToken;

  /**
   * Contains instance of PHP Library.
   *
   * @var \Abraham\TwitterOAuth\TwitterOAuth
   */
  protected $sdk;

  /**
   * TwitterAuthController constructor.
   */
  public function __construct(NetworkManager $network_manager, TwitterAuthManager $auth_manager, RequestStack $request_stack) {
    $this->networkManager = $network_manager;
    $this->authManager = $auth_manager;
    $this->request = $request_stack
      ->getCurrentRequest();
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.network.manager'), $container
      ->get('social_auth_twitter.auth_manager'), $container
      ->get('request_stack'));
  }

  /**
   * Returns the redirect response.
   *
   * @param string $type
   *   Type of action, "login" or "register".
   *
   * @return \Drupal\Core\Routing\TrustedRedirectResponse|\Symfony\Component\HttpFoundation\RedirectResponse
   *   Returns a RedirectResponse.
   */
  protected function getRedirectResponse($type) {
    $sdk = $this
      ->getSdk($type);
    if ($sdk instanceof RedirectResponse) {
      return $sdk;
    }
    $this->authManager
      ->setSdk($sdk);
    $url = $this->authManager
      ->getAuthenticationUrl($type);
    return new TrustedRedirectResponse($url);
  }

  /**
   * Response for path 'user/login/twitter'.
   *
   * Redirects the user to Twitter for authentication.
   */
  public function userLogin() {
    return $this
      ->getRedirectResponse('login');
  }

  /**
   * Authorizes the user after redirect from Twitter.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   Returns a RedirectResponse.
   */
  public function userLoginCallback() {
    $sdk = $this
      ->getSdk('login');
    if ($sdk instanceof RedirectResponse) {
      return $sdk;
    }
    $this->authManager
      ->setSdk($sdk);
    $profile = $this
      ->getProfile('register');
    if ($profile instanceof RedirectResponse) {
      return $profile;
    }

    // Check whether user account exists. If account already exists,
    // authorize the user and redirect him to the account page.
    $account = $this
      ->entityTypeManager()
      ->getStorage('user')
      ->loadByProperties([
      'twitter_id' => $profile->id,
    ]);
    if (!$account) {
      return $this
        ->redirect('social_auth_twitter.user_login_notice');
    }
    $account = current($account);
    if (!$account
      ->get('status')->value) {
      drupal_set_message($this
        ->t('Your account is blocked. Contact the site administrator.'), 'error');
      return $this
        ->redirect('user.login');
    }
    user_login_finalize($account);
    drupal_set_message(t('You are logged in'));
    return $this
      ->redirect('entity.user.canonical', [
      'user' => $account
        ->id(),
    ]);
  }

  /**
   * Response for path 'user/register/twitter'.
   *
   * Redirects the user to Twitter for registration.
   */
  public function userRegister() {
    return $this
      ->getRedirectResponse('register');
  }

  /**
   * Registers the new account after redirect from Twitter.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   Returns a RedirectResponse.
   */
  public function userRegisterCallback() {
    $sdk = $this
      ->getSdk('register');
    if ($sdk instanceof RedirectResponse) {
      return $sdk;
    }
    $this->authManager
      ->setSdk($sdk);
    $profile = $this
      ->getProfile('register');
    if ($profile instanceof RedirectResponse) {
      return $profile;
    }

    // Check whether user account exists. If account already exists,
    // authorize the user and redirect him to the account page.
    $account = $this
      ->entityTypeManager()
      ->getStorage('user')
      ->loadByProperties([
      'twitter_id' => $profile->id,
    ]);
    if ($account) {
      $account = current($account);
      if (!$account
        ->get('status')->value) {
        drupal_set_message($this
          ->t('You already have account on this site, but your account is blocked. Contact the site administrator.'), 'error');
        return $this
          ->redirect('user.register');
      }
      user_login_finalize($account);
      return $this
        ->redirect('entity.user.canonical', [
        'user' => $account
          ->id(),
      ]);
    }

    // Save email and name to storage to use for auto fill the registration
    // form.
    $data_handler = $this->networkManager
      ->createInstance('social_auth_twitter')
      ->getDataHandler();
    $data_handler
      ->set('access_token', $this->accessToken);
    $data_handler
      ->set('mail', NULL);
    $data_handler
      ->set('name', $this->authManager
      ->getUsername());
    drupal_set_message($this
      ->t('You are now connected with @network, please continue registration', [
      '@network' => $this
        ->t('Twitter'),
    ]));
    return $this
      ->redirect('user.register', [
      'provider' => 'twitter',
    ]);
  }

  /**
   * Returns the SDK instance or RedirectResponse when error occurred.
   *
   * @param string $type
   *   Type of action, "login" or "register".
   *
   * @return mixed|\Symfony\Component\HttpFoundation\RedirectResponse
   *   Returns an instance of the SDK or a Redirect Response.
   */
  public function getSdk($type) {
    if ($this->sdk) {
      return $this->sdk;
    }
    $network_manager = $this->networkManager
      ->createInstance('social_auth_twitter');
    if (!$network_manager
      ->isActive()) {
      drupal_set_message($this
        ->t('@network is disabled. Contact the site administrator', [
        '@network' => $this
          ->t('Twitter'),
      ]), 'error');
      return $this
        ->redirect('user.' . $type);
    }
    if (!($this->sdk = $network_manager
      ->getSdk())) {
      drupal_set_message($this
        ->t('@network Auth not configured properly. Contact the site administrator.', [
        '@network' => $this
          ->t('Twitter'),
      ]), 'error');
      return $this
        ->redirect('user.' . $type);
    }
    return $this->sdk;
  }

  /**
   * Loads access token, then loads profile.
   *
   * @param string $type
   *   The type.
   *
   * @return object
   *   Returns an object.
   */
  public function getProfile($type) {
    $sdk = $this
      ->getSdk($type);
    $data_handler = $this->networkManager
      ->createInstance('social_auth_twitter')
      ->getDataHandler();

    // Get the OAuth token from Twitter.
    if (!($oauth_token = $data_handler
      ->get('oauth_token')) || !($oauth_token_secret = $data_handler
      ->get('oauth_token_secret'))) {
      drupal_set_message($this
        ->t('@network login failed. Token is not valid.', [
        '@network' => $this
          ->t('Twitter'),
      ]), 'error');
      return $this
        ->redirect('user.' . $type);
    }
    $this->authManager
      ->setAccessToken([
      'oauth_token' => $oauth_token,
      'oauth_token_secret' => $oauth_token_secret,
    ]);

    // Gets the permanent access token.
    $this->accessToken = $sdk
      ->oauth('oauth/access_token', [
      'oauth_verifier' => $this->request
        ->get('oauth_verifier'),
    ]);
    $this->authManager
      ->setAccessToken([
      'oauth_token' => $this->accessToken['oauth_token'],
      'oauth_token_secret' => $this->accessToken['oauth_token_secret'],
    ]);

    // Get user's profile from Twitter API.
    if (!($profile = $this->authManager
      ->getProfile()) || !$this->authManager
      ->getAccountId()) {
      drupal_set_message($this
        ->t('@network login failed, could not load @network profile. Contact the site administrator.', [
        '@network' => $this
          ->t('Twitter'),
      ]), 'error');
      return $this
        ->redirect('user.' . $type);
    }
    return $profile;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TwitterAuthController::$accessToken protected property Contains access token to work with API.
TwitterAuthController::$authManager private property The Twitter authentication manager.
TwitterAuthController::$networkManager private property The network plugin manager.
TwitterAuthController::$request private property The current request.
TwitterAuthController::$sdk protected property Contains instance of PHP Library.
TwitterAuthController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
TwitterAuthController::getProfile public function Loads access token, then loads profile.
TwitterAuthController::getRedirectResponse protected function Returns the redirect response.
TwitterAuthController::getSdk public function Returns the SDK instance or RedirectResponse when error occurred.
TwitterAuthController::userLogin public function Response for path 'user/login/twitter'.
TwitterAuthController::userLoginCallback public function Authorizes the user after redirect from Twitter.
TwitterAuthController::userRegister public function Response for path 'user/register/twitter'.
TwitterAuthController::userRegisterCallback public function Registers the new account after redirect from Twitter.
TwitterAuthController::__construct public function TwitterAuthController constructor.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.