77 lines
2.7 KiB
PHP
77 lines
2.7 KiB
PHP
<?php
|
|
require_once 'vendor/autoload.php';
|
|
require_once 'db/config.php';
|
|
session_start();
|
|
|
|
$social_logins = require 'config/social_logins.php';
|
|
$google_config = $social_logins['google'];
|
|
|
|
$client = new Google_Client();
|
|
$client->setClientId($google_config['client_id']);
|
|
$client->setClientSecret($google_config['client_secret']);
|
|
$client->setRedirectUri($google_config['redirect_uri']);
|
|
|
|
if (isset($_GET['code'])) {
|
|
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
|
|
$client->setAccessToken($token['access_token']);
|
|
|
|
// get profile info
|
|
$google_oauth = new Google_Service_Oauth2($client);
|
|
$google_account_info = $google_oauth->userinfo->get();
|
|
$email = $google_account_info->email;
|
|
$name = $google_account_info->name;
|
|
$google_id = $google_account_info->id;
|
|
|
|
try {
|
|
$pdo = db();
|
|
|
|
// Check if user exists with this google id
|
|
$stmt = $pdo->prepare('SELECT u.* FROM users u JOIN user_social_logins usl ON u.id = usl.user_id WHERE usl.provider = ? AND usl.provider_id = ?');
|
|
$stmt->execute(['google', $google_id]);
|
|
$user = $stmt->fetch();
|
|
|
|
if ($user) {
|
|
// User exists, log them in
|
|
$_SESSION['user_id'] = $user['id'];
|
|
$_SESSION['username'] = $user['username'];
|
|
$_SESSION['role'] = $user['role'];
|
|
} else {
|
|
// User does not exist, create a new user
|
|
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = ?');
|
|
$stmt->execute([$email]);
|
|
$user_exists = $stmt->fetch();
|
|
|
|
if ($user_exists) {
|
|
// A user with this email already exists, but not linked to this google id.
|
|
// For simplicity, we will just link them.
|
|
$user_id = $user_exists['id'];
|
|
} else {
|
|
// Create a new user
|
|
$stmt = $pdo->prepare("INSERT INTO users (username, role) VALUES (?, ?)");
|
|
$stmt->execute([$email, 'customer']);
|
|
$user_id = $pdo->lastInsertId();
|
|
}
|
|
|
|
// Link the social login
|
|
$stmt = $pdo->prepare("INSERT INTO user_social_logins (user_id, provider, provider_id) VALUES (?, ?, ?)");
|
|
$stmt->execute([$user_id, 'google', $google_id]);
|
|
|
|
// Log the new user in
|
|
$_SESSION['user_id'] = $user_id;
|
|
$_SESSION['username'] = $email;
|
|
$_SESSION['role'] = 'customer';
|
|
}
|
|
|
|
header('Location: profile.php');
|
|
exit;
|
|
|
|
} catch (PDOException $e) {
|
|
$_SESSION['flash_message'] = ['type' => 'danger', 'message' => 'Database error: ' . $e->getMessage()];
|
|
header('Location: login.php');
|
|
exit;
|
|
}
|
|
} else {
|
|
header('Location: login.php');
|
|
exit;
|
|
}
|