Skip to content

Commit

Permalink
Add Twitter OAuth2 provider (#574)
Browse files Browse the repository at this point in the history
  • Loading branch information
dehbka committed Jan 24, 2022
1 parent 4e6f7e4 commit ea9288a
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/SocialiteManager.php
Expand Up @@ -13,6 +13,7 @@
use Laravel\Socialite\Two\GitlabProvider;
use Laravel\Socialite\Two\GoogleProvider;
use Laravel\Socialite\Two\LinkedInProvider;
use Laravel\Socialite\Two\TwitterProvider as TwitterOAuth2Provider;
use League\OAuth1\Client\Server\Twitter as TwitterServer;

class SocialiteManager extends Manager implements Contracts\Factory
Expand Down Expand Up @@ -112,6 +113,20 @@ protected function createGitlabDriver()
)->setHost($config['host'] ?? null);
}

/**
* Create an instance of the specified driver.
*
* @return \Laravel\Socialite\Two\AbstractProvider
*/
protected function createTwitterOAuth2Driver()
{
$config = $this->config->get('services.twitter');

return $this->buildProvider(
TwitterOAuth2Provider::class, $config
);
}

/**
* Build an OAuth 2 provider instance.
*
Expand Down
71 changes: 71 additions & 0 deletions src/Two/TwitterProvider.php
@@ -0,0 +1,71 @@
<?php

namespace Laravel\Socialite\Two;

use Illuminate\Support\Arr;

class TwitterProvider extends AbstractProvider
{
/**
* The scopes being requested.
*
* @var array
*/
protected $scopes = ['users.read', 'tweet.read'];

/**
* Indicates if PKCE should be used.
*
* @var bool
*/
protected $usesPKCE = true;

/**
* The separating character for the requested scopes.
*
* @var string
*/
protected $scopeSeparator = ' ';

/**
* {@inheritdoc}
*/
public function getAuthUrl($state)
{
return $this->buildAuthUrlFromBase('https://twitter.com/i/oauth2/authorize', $state);
}

/**
* {@inheritdoc}
*/
protected function getTokenUrl()
{
return 'https://api.twitter.com/2/oauth2/token';
}

/**
* {@inheritdoc}
*/
protected function getUserByToken($token)
{
$response = $this->getHttpClient()->get('https://api.twitter.com/2/users/me', [
'headers' => ['Authorization' => 'Bearer '.$token],
'query' => ['user.fields' => 'profile_image_url'],
]);

return Arr::get(json_decode($response->getBody(), true), 'data');
}

/**
* {@inheritdoc}
*/
protected function mapUserToObject(array $user)
{
return (new User)->setRaw($user)->map([
'id' => $user['id'],
'nickname' => $user['username'],
'name' => $user['name'],
'avatar' => $user['profile_image_url'],
]);
}
}

0 comments on commit ea9288a

Please sign in to comment.