-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgoogle_callback.php
More file actions
58 lines (49 loc) · 1.75 KB
/
google_callback.php
File metadata and controls
58 lines (49 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
require 'vendor/autoload.php';
include "db.php";
session_start();
$client = new Google_Client();
$client->setClientId('YOUR_CLIENT_ID_HERE');
$client->setClientSecret('YOUR_CLIENT_SECRET_HERE');
$client->setRedirectUri('http://localhost/BookStore/google_callback.php');
$client->addScope("email");
$client->addScope("profile");
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
// ✅ Check for token errors
if (isset($token['error'])) {
echo "Error fetching token: " . htmlspecialchars($token['error']);
exit();
}
$client->setAccessToken($token);
$oauth = new Google_Service_Oauth2($client);
$google_user = $oauth->userinfo->get();
$google_id = $google_user->id;
$name = $google_user->name;
$email = $google_user->email;
// ✅ Check if user already exists in database
$stmt = $conn->prepare("SELECT id, role FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
if ($row = $result->fetch_assoc()) {
$_SESSION["user_id"] = $row["id"];
$_SESSION["user_name"] = $name;
$_SESSION["email"] = $email;
$_SESSION["role"] = $row["role"];
}
else {
// ✅ Insert new user with Google
$stmt = $conn->prepare("INSERT INTO users (name, email, password, is_verified, role) VALUES (?, ?, '', 1, 'user')");
$stmt->bind_param("ss", $name, $email);
$stmt->execute();
$_SESSION["user_id"] = $conn->insert_id;
$_SESSION["user_name"] = $name;
$_SESSION["email"] = $email;
$_SESSION["role"] = "user";
}
header("Location: index.php");
exit();
} else {
echo "No authorization code received from Google.";
}