54 lines
2.4 KiB
PHP
54 lines
2.4 KiB
PHP
<?php
|
|
session_start();
|
|
require_once '../config/db.php';
|
|
require_once '../includes/functions.php';
|
|
|
|
require_once '../vendor/autoload.php';
|
|
|
|
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
|
|
header("location: ../index.php");
|
|
exit;
|
|
}
|
|
|
|
if (isset($_GET['code'])) {
|
|
$client_id = get_setting($pdo_sys, 'google_client_id');
|
|
$client_secret = get_setting($pdo_sys, 'google_client_secret');
|
|
|
|
$client = new Google\Client();
|
|
$client->setClientId($client_id);
|
|
$client->setClientSecret($client_secret);
|
|
|
|
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
|
|
$host = $_SERVER['HTTP_HOST'];
|
|
$base_dir = dirname(dirname($_SERVER['PHP_SELF']));
|
|
$redirect_uri = $protocol . "://" . $host . $base_dir . "/auth/google_callback.php";
|
|
$redirect_uri = str_replace('//auth', '/auth', $redirect_uri);
|
|
|
|
$client->setRedirectUri($redirect_uri);
|
|
|
|
try {
|
|
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
|
|
|
|
if (!isset($token['error'])) {
|
|
if (isset($token['refresh_token'])) {
|
|
save_setting($pdo_sys, 'google_refresh_token', $token['refresh_token'], $_SESSION['fullname']);
|
|
add_log($pdo_sys, $_SESSION['cid'], $_SESSION['fullname'], 'Google Auth', 'Successfully connected and received refresh token');
|
|
|
|
$_SESSION['settings_msg'] = "เชื่อมต่อบัญชี Google สำเร็จแล้ว!";
|
|
} else {
|
|
$_SESSION['settings_error'] = "ไม่ได้รับ Refresh Token กรณีเคยอนุญาตสิทธิ์ไปแล้ว กรุณาไปที่ Google Account > Security > Third-party apps เพื่อลบสิทธิ์ออกก่อน แล้วลองเชื่อมต่อใหม่อีกครั้ง";
|
|
}
|
|
} else {
|
|
$_SESSION['settings_error'] = "เกิดข้อผิดพลาดในการรับ Token: " . $token['error'];
|
|
}
|
|
} catch (Exception $e) {
|
|
$_SESSION['settings_error'] = "เกิดข้อผิดพลาด: " . $e->getMessage();
|
|
}
|
|
} else if (isset($_GET['error'])) {
|
|
$_SESSION['settings_error'] = "ถูกปฏิเสธการเข้าถึง: " . $_GET['error'];
|
|
}
|
|
|
|
header("location: ../settings.php");
|
|
exit;
|
|
?>
|