82 lines
2.6 KiB
PHP
82 lines
2.6 KiB
PHP
<?php
|
|
error_reporting(E_ALL);
|
|
ini_set('display_errors', 1);
|
|
file_put_contents('logs/debug.log', "Callback script started\n", FILE_APPEND);
|
|
|
|
session_start();
|
|
|
|
|
|
require_once 'google-config.php';
|
|
|
|
function log_error($message) {
|
|
$log_file = 'logs/google_auth.log';
|
|
$timestamp = date('Y-m-d H:i:s');
|
|
// Ensure the log directory exists
|
|
if (!is_dir(dirname($log_file))) {
|
|
mkdir(dirname($log_file), 0775, true);
|
|
}
|
|
file_put_contents($log_file, "[$timestamp] $message\n", FILE_APPEND);
|
|
}
|
|
|
|
if (isset($_GET['code'])) {
|
|
$code = $_GET['code'];
|
|
|
|
$token_url = 'https://oauth2.googleapis.com/token';
|
|
$token_params = [
|
|
'code' => $code,
|
|
'client_id' => GOOGLE_CLIENT_ID,
|
|
'client_secret' => GOOGLE_CLIENT_SECRET,
|
|
'redirect_uri' => GOOGLE_REDIRECT_URI,
|
|
'grant_type' => 'authorization_code'
|
|
];
|
|
|
|
$ch = curl_init($token_url);
|
|
curl_setopt($ch, CURLOPT_POST, true);
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($token_params));
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
|
|
$response = curl_exec($ch);
|
|
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
$curl_error = curl_error($ch);
|
|
curl_close($ch);
|
|
|
|
if ($curl_error) {
|
|
log_error("cURL Error: " . $curl_error);
|
|
echo "An error occurred. Please try again later. (Code: 1)";
|
|
exit();
|
|
}
|
|
|
|
if ($http_code == 200) {
|
|
$token_data = json_decode($response, true);
|
|
|
|
if (json_last_error() !== JSON_ERROR_NONE) {
|
|
log_error("Failed to decode JSON response: " . $response);
|
|
echo "An error occurred. Please try again later. (Code: 2)";
|
|
exit();
|
|
}
|
|
|
|
// Ensure the db directory exists
|
|
if (!is_dir(dirname('db/google_tokens.json'))) {
|
|
mkdir(dirname('db/google_tokens.json'), 0775, true);
|
|
}
|
|
|
|
if (file_put_contents('db/google_tokens.json', json_encode($token_data)) === false) {
|
|
log_error("Failed to write tokens to db/google_tokens.json");
|
|
echo "An error occurred. Please try again later. (Code: 3)";
|
|
exit();
|
|
}
|
|
|
|
$_SESSION['google_access_token'] = $token_data['access_token'];
|
|
|
|
header('Location: dashboard.php');
|
|
exit();
|
|
|
|
} else {
|
|
log_error("Error fetching access token. HTTP Code: " . $http_code . ", Response: " . $response);
|
|
echo "An error occurred while trying to connect to Google. Please check your credentials in setup.php and try again.";
|
|
}
|
|
} else {
|
|
log_error("Authorization code not found in callback.");
|
|
echo "Authorization code not found.";
|
|
}
|