Initial commit
This commit is contained in:
82
src/login/LoginHandler.php
Normal file
82
src/login/LoginHandler.php
Normal file
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace App\login;
|
||||
|
||||
use Exception;
|
||||
use RuntimeException;
|
||||
use UnexpectedValueException;
|
||||
use Wohali\OAuth2\Client\Provider\Discord;
|
||||
use Wohali\OAuth2\Client\Provider\DiscordResourceOwner;
|
||||
|
||||
class LoginHandler
|
||||
{
|
||||
|
||||
private Discord $provider;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->provider = new Discord(
|
||||
[
|
||||
'clientId' => OAUTH_CLIENTID,
|
||||
'clientSecret' => OAUTH_SECRET,
|
||||
'redirectUri' => OAUTH_REDIRECT_URI,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
public function handle() :void
|
||||
{
|
||||
if (!isset($_GET['code'])) {
|
||||
// Step 1. Get authorization code
|
||||
$authUrl = $this->provider->getAuthorizationUrl([
|
||||
'scope' => ['identify', 'guilds'],
|
||||
]);
|
||||
|
||||
|
||||
$_SESSION['oauth2state'] = $this->provider->getState();
|
||||
header('Location: '.$authUrl);
|
||||
die();
|
||||
}
|
||||
|
||||
if (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
|
||||
unset($_SESSION['oauth2state']);
|
||||
|
||||
throw new RuntimeException('Invalid OAuth state');
|
||||
}
|
||||
|
||||
$token = $this->provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
|
||||
|
||||
try {
|
||||
/** @var DiscordResourceOwner $user */
|
||||
$user = $this->provider->getResourceOwner($token);
|
||||
|
||||
echo '<h2>Resource owner details:</h2>';
|
||||
printf('Hello %s#%s!<br/><br/>', $user->getUsername(), $user->getDiscriminator());
|
||||
var_export($user->toArray());
|
||||
|
||||
$_SESSION['logged_in'] = true;
|
||||
|
||||
$url = $this->provider->getResourceOwnerDetailsUrl($token).'/guilds';
|
||||
$request = $this->provider->getAuthenticatedRequest(Discord::METHOD_GET, $url, $token);
|
||||
$response = $this->provider->getParsedResponse($request);
|
||||
|
||||
if (is_array($response) === false) {
|
||||
throw new UnexpectedValueException(
|
||||
'Invalid response received from Authorization Server. Expected JSON.'
|
||||
);
|
||||
}
|
||||
|
||||
if (in_array(DISCORD_GUILD_ID, array_column($response, 'id')) === true) {
|
||||
$_SESSION['logged_in'] = true;
|
||||
redirect($_SESSION['return_uri']);
|
||||
die();
|
||||
}
|
||||
|
||||
redirect('/denied');
|
||||
} catch (Exception $e) {
|
||||
// Failed to get user details
|
||||
handle_error($e);
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user