-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgoogle_callback.php
More file actions
73 lines (61 loc) · 2.51 KB
/
google_callback.php
File metadata and controls
73 lines (61 loc) · 2.51 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
session_start();
require 'google-config.php';
if (isset($_GET['code'])) {
try {
// Fetch the token with the authorization code
$token = $google_client->fetchAccessTokenWithAuthCode($_GET['code']);
// Check if there's an error fetching the access token
if (isset($token['error'])) {
throw new Exception("Error fetching access token: " . $token['error']);
}
// Set access token in the client
$google_client->setAccessToken($token['access_token']);
// Get profile info from Google
$google_oauth = new Google_Service_Oauth2($google_client);
$google_account_info = $google_oauth->userinfo->get();
// Extract required user info
$email = $google_account_info->email;
$first_name = $google_account_info->givenName;
$last_name = $google_account_info->familyName;
$token = $google_account_info->id;
$picture = $google_account_info->picture;
$verified_email = $google_account_info->verifiedEmail ? 1 : 0;
// Database connection
$conn = new mysqli('localhost', 'root', '', 'petiverse');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Check if the user already exists
$stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
// User already exists, log them in
$stmt->bind_result($id);
$stmt->fetch();
$_SESSION['user_id'] = $id;
$_SESSION['username'] = $first_name;
header("Location: index.php");
} else {
// New Google user, register them
$stmt = $conn->prepare("INSERT INTO users (first_name, last_name, email, token, verifiedEmail, picture) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $first_name, $last_name, $email, $token, $verified_email, $picture);
if ($stmt->execute()) {
$_SESSION['user_id'] = $conn->insert_id;
$_SESSION['username'] = $first_name;
header("Location: index.php");
} else {
echo "Error: " . $stmt->error;
}
}
$stmt->close();
$conn->close();
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
} else {
echo "Google sign-in failed.";
}
?>