setClientId(GOOGLE_CLIENT_ID); $client->setClientSecret(GOOGLE_CLIENT_SECRET); $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/auth_google_callback.php'); if (isset($_GET['code'])) { $token = $client->fetchAccessTokenWithAuthCode($_GET['code']); $client->setAccessToken($token['access_token']); $google_oauth = new Google_Service_Oauth2($client); $google_account_info = $google_oauth->userinfo->get(); $email = $google_account_info->email; $name = $google_account_info->name; $pdo = db(); $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?"); $stmt->execute([$email]); $user = $stmt->fetch(); if ($user) { // User exists, log them in $_SESSION['user_id'] = $user['id']; $_SESSION['user_name'] = $user['name']; $_SESSION['is_admin'] = $user['is_admin']; $_SESSION['role'] = $user['role']; header('Location: index.php'); exit(); } else { // User doesn't exist, create a new account $stmt = $pdo->prepare("INSERT INTO users (name, email, password, role) VALUES (?, ?, ?, ?)"); // We can't store an empty password, so we generate a random one. $random_password = bin2hex(random_bytes(16)); $stmt->execute([$name, $email, password_hash($random_password, PASSWORD_DEFAULT), 'customer']); $user_id = $pdo->lastInsertId(); $_SESSION['user_id'] = $user_id; $_SESSION['user_name'] = $name; $_SESSION['is_admin'] = 0; $_SESSION['role'] = 'customer'; header('Location: index.php'); exit(); } } else { header('Location: login.php?error=Google login failed'); exit(); }