From cd9f41dca060e8125f83344d7f52016940debbaf Mon Sep 17 00:00:00 2001 From: Morne Alberts Date: Sun, 21 Aug 2022 11:38:52 +0200 Subject: [PATCH] Get guilds after authentication --- src/AuthenticationProvider/DiscordAuth.php | 31 +++++++++++++++++++--- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/src/AuthenticationProvider/DiscordAuth.php b/src/AuthenticationProvider/DiscordAuth.php index 400ad3e..54f6c88 100644 --- a/src/AuthenticationProvider/DiscordAuth.php +++ b/src/AuthenticationProvider/DiscordAuth.php @@ -16,8 +16,11 @@ namespace WSOAuth\AuthenticationProvider; +use League\OAuth2\Client\Provider\AbstractProvider; +use League\OAuth2\Client\Token\AccessToken; use MediaWiki\User\UserIdentity; use Wohali\OAuth2\Client\Provider\Discord; +use Wohali\OAuth2\Client\Provider\DiscordResourceOwner; /** * Class DiscordAuth @@ -45,7 +48,7 @@ public function __construct( string $clientId, string $clientSecret, ?string $au */ public function login( ?string &$key, ?string &$secret, ?string &$authUrl ): bool { $authUrl = $this->provider->getAuthorizationUrl( [ - 'scope' => [ 'identify', 'email' ], + 'scope' => [ 'identify', 'email', 'guilds' ], 'prompt' => 'none' ] ); @@ -77,13 +80,16 @@ public function getUser( string $key, string $secret, &$errorMessage ) { try { $token = $this->provider->getAccessToken( 'authorization_code', [ 'code' => $_GET['code'] ] ); + $guilds = $this->getUserGuilds( $token ); + // TODO: check allowed guilds + + /** @var DiscordResourceOwner $user */ $user = $this->provider->getResourceOwner( $token ); - $userArray = $user->toArray(); return [ 'name' => $user->getId(), - 'realname' => $userArray['username'], - 'email' => $userArray['email'] + 'realname' => $user->getUsername(), + 'email' => $user->getEmail() ]; } catch ( \Exception $e ) { return false; @@ -95,4 +101,21 @@ public function getUser( string $key, string $secret, &$errorMessage ) { */ public function saveExtraAttributes( int $id ): void { } + + private function getUserGuildsUrl(): string { + return $this->provider->apiDomain . '/users/@me/guilds'; + } + + /** + * @return array> + */ + private function getUserGuilds( AccessToken $token ): array { + $request = $this->provider->getAuthenticatedRequest( + AbstractProvider::METHOD_GET, $this->getUserGuildsUrl(), + $token + ); + + return $this->provider->getParsedResponse($request); + } + }