70 lines
2.6 KiB
PHP
70 lines
2.6 KiB
PHP
<?php
|
|
require_once __DIR__ . '/vendor/autoload.php';
|
|
require_once __DIR__ . '/db/config.php';
|
|
require_once __DIR__ . '/ai/config.php';
|
|
|
|
session_start();
|
|
|
|
if ($_SERVER["REQUEST_METHOD"] == "POST") {
|
|
$credential = $_POST['credential'];
|
|
$client = new Google_Client(['client_id' => GOOGLE_CLIENT_ID]);
|
|
$payload = $client->verifyIdToken($credential);
|
|
|
|
if ($payload) {
|
|
$google_id = $payload['sub'];
|
|
$email = $payload['email'];
|
|
|
|
try {
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare("SELECT * FROM users WHERE google_id = ?");
|
|
$stmt->execute([$google_id]);
|
|
$user = $stmt->fetch();
|
|
|
|
if ($user) {
|
|
// User found with google_id, log them in
|
|
$_SESSION['user_id'] = $user['id'];
|
|
$_SESSION['user_email'] = $user['email'];
|
|
header("Location: index.php");
|
|
exit;
|
|
} else {
|
|
// No user with this google_id, check by email
|
|
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
|
|
$stmt->execute([$email]);
|
|
$user = $stmt->fetch();
|
|
|
|
if ($user) {
|
|
// User with this email exists, link google_id
|
|
$update_stmt = $pdo->prepare("UPDATE users SET google_id = ? WHERE id = ?");
|
|
$update_stmt->execute([$google_id, $user['id']]);
|
|
$_SESSION['user_id'] = $user['id'];
|
|
$_SESSION['user_email'] = $user['email'];
|
|
header("Location: index.php");
|
|
exit;
|
|
} else {
|
|
// No user with this email, create a new user
|
|
$password = bin2hex(random_bytes(16)); // Create a random password
|
|
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
|
|
$insert_stmt = $pdo->prepare("INSERT INTO users (email, password, google_id) VALUES (?, ?, ?)");
|
|
$insert_stmt->execute([$email, $hashed_password, $google_id]);
|
|
$user_id = $pdo->lastInsertId();
|
|
$_SESSION['user_id'] = $user_id;
|
|
$_SESSION['user_email'] = $email;
|
|
header("Location: index.php");
|
|
exit;
|
|
}
|
|
}
|
|
} catch (PDOException $e) {
|
|
// Handle DB error
|
|
header("Location: login.php?error=db_error");
|
|
exit;
|
|
}
|
|
} else {
|
|
// Invalid token
|
|
header("Location: login.php?error=invalid_token");
|
|
exit;
|
|
}
|
|
} else {
|
|
header("Location: login.php");
|
|
exit;
|
|
}
|
|
?>
|