Newer
Older
gnexus-auth-client-php / examples / plain-php / callback.php
@Eugene Sukhodolskiy Eugene Sukhodolskiy 12 hours ago 944 bytes Initial auth client package scaffold
<?php

declare(strict_types=1);

use GNexus\GAuth\Exception\GAuthException;

/** @var \GNexus\GAuth\Client\GAuthClient $client */
$client = require __DIR__ . '/bootstrap.php';

$code = isset($_GET['code']) ? (string) $_GET['code'] : '';
$state = isset($_GET['state']) ? (string) $_GET['state'] : '';

if ($code === '' || $state === '') {
    http_response_code(400);
    echo 'Missing callback parameters.';
    exit;
}

try {
    $tokenSet = $client->exchangeAuthorizationCode($code, $state);
    $user = $client->fetchUser($tokenSet->accessToken);
} catch (GAuthException $exception) {
    http_response_code(401);
    echo 'Authorization failed: ' . $exception->getMessage();
    exit;
}

$_SESSION['gauth_access_token'] = $tokenSet->accessToken;
$_SESSION['gauth_refresh_token'] = $tokenSet->refreshToken;
$_SESSION['gauth_user_id'] = $user->userId;
$_SESSION['gauth_user_email'] = $user->email;

header('Location: /protected.php');
exit;