68 lines
1.8 KiB
PHP
68 lines
1.8 KiB
PHP
<?php
|
|
require_once __DIR__ . '/../config.php';
|
|
session_start_safe();
|
|
|
|
// user denied access
|
|
if (isset($_GET['error'])) {
|
|
header('Location: ../index.php?error=' . urlencode($_GET['error']));
|
|
exit;
|
|
}
|
|
|
|
// CSRF check
|
|
if (
|
|
empty($_GET['state']) ||
|
|
empty($_SESSION['oauth_state']) ||
|
|
!hash_equals($_SESSION['oauth_state'], $_GET['state'])
|
|
) {
|
|
session_destroy();
|
|
http_response_code(400);
|
|
echo 'Invalid state parameter. Possible CSRF attack. <a href="../index.php">Back</a>';
|
|
exit;
|
|
}
|
|
|
|
if (empty($_GET['code'])) {
|
|
header('Location: ../index.php?error=missing_code');
|
|
exit;
|
|
}
|
|
|
|
$verifier = $_SESSION['pkce_verifier'];
|
|
unset($_SESSION['pkce_verifier'], $_SESSION['oauth_state']);
|
|
|
|
$post = http_build_query([
|
|
'grant_type' => 'authorization_code',
|
|
'client_id' => CLIENT_ID,
|
|
'redirect_uri' => REDIRECT_URI,
|
|
'code' => $_GET['code'],
|
|
'code_verifier' => $verifier,
|
|
]);
|
|
|
|
$ch = curl_init(TOKEN_URI);
|
|
curl_setopt_array($ch, [
|
|
CURLOPT_POST => true,
|
|
CURLOPT_POSTFIELDS => $post,
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
|
|
CURLOPT_SSL_VERIFYPEER => !DEV_MODE,
|
|
]);
|
|
$body = curl_exec($ch);
|
|
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
$curlError = curl_error($ch);
|
|
|
|
$data = json_decode($body, true);
|
|
|
|
if ($curlError || $status !== 200 || empty($data['access_token'])) {
|
|
$_SESSION['token_debug'] = [
|
|
'curl_error' => $curlError ?: null,
|
|
'http_status' => $status,
|
|
'response_body' => $body,
|
|
];
|
|
header('Location: ../index.php?error=token_failed');
|
|
exit;
|
|
}
|
|
|
|
$_SESSION['access_token'] = $data['access_token'];
|
|
$_SESSION['token_expires'] = time() + ($data['expires_in'] ?? 3600);
|
|
|
|
header('Location: ../index.php');
|
|
exit;
|