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

WIP Get guilds after authentication #1

Open
wants to merge 1 commit into
base: discord
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 27 additions & 4 deletions src/AuthenticationProvider/DiscordAuth.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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'
] );

Expand Down Expand Up @@ -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;
Expand All @@ -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<int, array<string, mixed>>
*/
private function getUserGuilds( AccessToken $token ): array {
$request = $this->provider->getAuthenticatedRequest(
AbstractProvider::METHOD_GET, $this->getUserGuildsUrl(),
$token
);

return $this->provider->getParsedResponse($request);
}

}