Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.x] Add Twitter OAuth2 provider #574

Merged
merged 1 commit into from Jan 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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'],
]);
}
}