35512-vm/google-callback.php
2025-11-08 21:16:26 +00:00

123 lines
4.3 KiB
PHP

<?php
session_start();
require_once 'db/config.php';
require_once 'auth-helpers.php';
$pdo = db();
// Fetch Google credentials from settings
try {
$stmt = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('google_client_id', 'google_client_secret')");
$settings_raw = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
$google_client_id = $settings_raw['google_client_id'] ?? '';
$google_client_secret = $settings_raw['google_client_secret'] ?? '';
} catch (PDOException $e) {
die('Database error fetching Google credentials.');
}
if (empty($google_client_id) || empty($google_client_secret)) {
die('Google API credentials are not configured. Please ask an administrator to set them up.');
}
if (!isset($_GET['code'])) {
header('Location: login.php?error=google_auth_failed');
exit;
}
$code = $_GET['code'];
$redirect_uri = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/google-callback.php';
// 1. Exchange authorization code for an access token
$token_url = 'https://oauth2.googleapis.com/token';
$token_params = [
'code' => $code,
'client_id' => $google_client_id,
'client_secret' => $google_client_secret,
'redirect_uri' => $redirect_uri,
'grant_type' => 'authorization_code'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $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);
curl_close($ch);
$token_data = json_decode($response, true);
if (!isset($token_data['access_token'])) {
// Log error: print_r($token_data);
header('Location: login.php?error=google_token_exchange_failed');
exit;
}
// 2. Get user info from Google
$userinfo_url = 'https://www.googleapis.com/oauth2/v2/userinfo';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $userinfo_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $token_data['access_token']]);
$userinfo_response = curl_exec($ch);
curl_close($ch);
$userinfo = json_decode($userinfo_response, true);
if (!isset($userinfo['email'])) {
// Log error: print_r($userinfo);
header('Location: login.php?error=google_userinfo_failed');
exit;
}
$user_email = $userinfo['email'];
$user_name = $userinfo['name'] ?? 'Google User';
// 3. Check if user exists in the database
try {
$stmt = $pdo->prepare("SELECT u.*, r.name as role_name FROM users u JOIN roles r ON u.role_id = r.id WHERE u.email = ?");
$stmt->execute([$user_email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
// 4. If user exists, log them in
if ($user) {
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['name'];
$_SESSION['user_role_id'] = $user['role_id'];
$_SESSION['user_role_name'] = $user['role_name'];
$_SESSION['user_role'] = $user['role_name']; // Backwards compatibility
header('Location: index.php');
exit;
}
// 5. If user does not exist, create a new user with the "Employee" role
$employee_role_id = 3; // Default to 'Employee' role (assuming ID 3)
$stmt_role = $pdo->prepare("SELECT id FROM roles WHERE name = ?");
$stmt_role->execute(['Employee']);
$role_id_from_db = $stmt_role->fetchColumn();
if ($role_id_from_db) {
$employee_role_id = $role_id_from_db;
}
// Generate a random password as it's required by the schema
$random_password = password_hash(bin2hex(random_bytes(16)), PASSWORD_DEFAULT);
$insert_stmt = $pdo->prepare("INSERT INTO users (name, email, password, role_id) VALUES (?, ?, ?, ?)");
$insert_stmt->execute([$user_name, $user_email, $random_password, $employee_role_id]);
$new_user_id = $pdo->lastInsertId();
// Log the new user in
$_SESSION['user_id'] = $new_user_id;
$_SESSION['user_name'] = $user_name;
$_SESSION['user_role_id'] = $employee_role_id;
$_SESSION['user_role_name'] = 'Employee';
$_SESSION['user_role'] = 'Employee';
header('Location: index.php?new_user=true');
exit;
} catch (PDOException $e) {
// Log error: $e->getMessage();
die('Database error during user processing. Please try again.');
}