34968-vm/auth_google_callback.php
Flatlogic Bot 42cfa7481c V19
2025-10-16 08:36:38 +00:00

54 lines
1.9 KiB
PHP

<?php
session_start();
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/includes/api_keys.php';
require_once __DIR__ . '/db/config.php';
$client = new Google_Client();
$client->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();
}