-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGoogleController.php
More file actions
58 lines (47 loc) · 2.15 KB
/
GoogleController.php
File metadata and controls
58 lines (47 loc) · 2.15 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
use JSONms\Controllers\RestfulController;
class GoogleController extends RestfulController {
public function callbackAction() {
$code = $_GET['code'];
$state = $_GET['state'];
// Google Client Configuration
$client = new Google_Client();
$client->setClientId($_ENV['GOOGLE_OAUTH_CLIENT_ID']); // Replace with your Client ID
$client->setClientSecret($_ENV['GOOGLE_OAUTH_CLIENT_SECRET']); // Replace with your Client Secret
$client->setRedirectUri($_ENV['GOOGLE_OAUTH_CALLBACK_URL']); // Replace with your redirect URI
// Authenticate the user
if (!empty($code)) {
$token = $client->fetchAccessTokenWithAuthCode($code);
$client->setAccessToken($token['access_token']);
$oauth2 = new Google_Service_Oauth2($client);
$userInfo = $oauth2->userinfo->get();
// Check if user already exists
$stmt = $this->query('get-user-by-google-id', [
'id' => $userInfo->id,
]);
if ($stmt->rowCount() > 0) {
// User exists, fetch data
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$userId = $user['id'];
} else {
// User does not exist, insert new user
$this->query('insert-user', [
'id' => $userInfo->id,
'name' => $userInfo->name,
'email' => $userInfo->email,
'avatar' => $userInfo->picture
]);
$userId = $this->getLastInsertedId(); // Get the new user's ID
}
// Store user information in the session
$_SESSION['user_id'] = $userId;
$_SESSION['access_token'] = $token['access_token'];
// Redirect to a protected page or dashboard
$decodedState = json_decode(urldecode($state), true);
header('Location: ' . $_ENV['INTERFACE_EDITOR_URL'] . $decodedState['path']);
exit;
} else {
throwError(400, "Error during authentication.");
}
}
}