Open sebastianmarco55 opened 1 month ago
To implement Google sign-in functionality on your website, we need to make changes to both the front-end and back-end of the application. This involves adding a Google sign-in button, handling the sign-in process, and managing user sessions. The changes will be made across multiple files to ensure a seamless integration.
css/style.css
Add styles for the Google sign-in button to ensure it matches the website's design.
/* Add this at the end of your css/style.css file */
/* Google Sign-In Button Styles */
.google-signin-btn {
display: inline-flex;
align-items: center;
justify-content: center;
background-color: #4285F4; /* Google's brand color */
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 4px;
font-size: 16px;
font-weight: 500;
cursor: pointer;
transition: background-color 0.3s ease;
}
.google-signin-btn:hover {
background-color: #357ae8; /* Slightly darker shade for hover effect */
}
.google-signin-btn img {
margin-right: 8px; /* Space between Google logo and text */
}
.google-signin-btn:focus {
outline: none;
box-shadow: 0 0 0 3px rgba(66, 133, 244, 0.5); /* Focus ring */
}
footer.php
Include the Google API script and initialize the Google API with your client ID.
<div class="container-fluid bg-dark text-light mt-5 py-5 wow fadeInUp" data-wow-delay="0.1s">
<div class="container pt-5">
<div class="row g-5">
<!-- Existing content -->
</div>
</div>
</div>
<div class="container-fluid bg-primary text-light py-4">
<div class="container">
<div class="row g-5">
<div class="col-md-6 text-center text-md-start">
<p class="mb-md-0">
©2024
<a class="text-white border-bottom" href="#">Tetra.</a>Toate
drepturile rezervate.
</p>
</div>
<div class="col-md-6 text-center text-md-end">
<p class="mb-0">
Proiectat de
<a class="text-white border-bottom" href="">BMS</a>
</p>
</div>
</div>
</div>
</div>
<!-- Google API Script -->
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script>
function onLoad() {
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: 'YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com'
});
});
}
</script>
<script src="path/to/your/js/main.js"></script>
</body>
</html>
index.html
Add the Google sign-in button and handle the sign-in process.
<head>
...
<!-- Google API Script -->
<script src="https://apis.google.com/js/platform.js" async defer></script>
<meta name="google-signin-client_id" content="YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com">
...
</head>
<body>
...
<!-- Google Sign-In Button -->
<div class="g-signin2" data-onsuccess="onSignIn"></div>
...
<!-- Handle Google Sign-In -->
<script>
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
var id_token = googleUser.getAuthResponse().id_token;
fetch('/backend/auth.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ token: id_token }),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
}
</script>
</body>
header.php
Add a link or button for users to sign in with Google and update the navigation bar to reflect the user's sign-in status.
<nav class="navbar navbar-expand-lg bg-white navbar-light shadow-sm py-3 py-lg-0 px-3 px-lg-0">
<a href="index.html" class="navbar-brand ms-lg-5">
<h1 class="display-5 m-0 text-primary2">
<img src="img/favicon2.png" alt="" style="width: 60%; border-radius: 10px; background-color: rgb(21, 59, 95); padding-left: 10px; padding-right: 10px;" />
</h1>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<div class="navbar-nav ms-auto py-0">
<a href="index.html" class="nav-item nav-link">Acasă</a>
<a href="about.html" class="nav-item nav-link active">Despre noi</a>
<a href="service.html" class="nav-item nav-link">Servicii</a>
<a href="career.html" class="nav-item nav-link">Cariera</a>
<a href="contact.html" class="nav-item nav-link">Contact</a>
<a href="tel:+123456789" class="nav-item nav-link nav-contact bg-secondary text-white px-5 ms-lg-5">
<i class="bi bi-telephone-outbound me-2"></i>+40 731 200 520
</a>
<?php if (isset($_SESSION['user'])): ?>
<a href="logout.php" class="nav-item nav-link">Logout</a>
<?php else: ?>
<a href="#" id="google-signin-button" class="nav-item nav-link">Sign in with Google</a>
<?php endif; ?>
</div>
</div>
</nav>
<!-- Include Google API script -->
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script>
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
var id_token = googleUser.getAuthResponse().id_token;
var xhr = new XMLHttpRequest();
xhr.open('POST', 'backend/auth.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
console.log('Signed in as: ' + xhr.responseText);
location.reload();
};
xhr.send('idtoken=' + id_token);
}
function renderButton() {
gapi.signin2.render('google-signin-button', {
'scope': 'profile email',
'width': 200,
'height': 50,
'longtitle': true,
'theme': 'dark',
'onsuccess': onSignIn
});
}
gapi.load('auth2', function() {
gapi.auth2.init().then(function() {
renderButton();
});
});
</script>
js/main.js
Add JavaScript code to handle the Google sign-in process and manage user authentication.
(function ($) {
"use strict";
// Initiate the wowjs
new WOW().init();
// Sticky Navbar
$(window).scroll(function () {
if ($(this).scrollTop() > 40) {
$(".navbar").addClass("sticky-top");
} else {
$(".navbar").removeClass("sticky-top");
}
});
// Dropdown on mouse hover
$(document).ready(function () {
function toggleNavbarMethod() {
if ($(window).width() > 992) {
$(".navbar .dropdown")
.on("mouseover", function () {
$(".dropdown-toggle", this).trigger("click");
})
.on("mouseout", function () {
$(".dropdown-toggle", this).trigger("click").blur();
});
} else {
$(".navbar .dropdown").off("mouseover").off("mouseout");
}
}
toggleNavbarMethod();
$(window).resize(toggleNavbarMethod);
});
// Back to top button
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$(".back-to-top").fadeIn("slow");
} else {
$(".back-to-top").fadeOut("slow");
}
});
$(".back-to-top").click(function () {
$("html, body").animate({ scrollTop: 0 }, 1500, "easeInOutExpo");
return false;
});
// Testimonials carousel
$(".testimonial-carousel").owlCarousel({
autoplay: true,
smartSpeed: 1500,
margin: 45,
dots: true,
loop: true,
center: true,
responsive: {
0: {
items: 1,
},
576: {
items: 1,
},
768: {
items: 2,
},
992: {
items: 3,
},
},
});
})(jQuery);
const dropContainer = document.getElementById("dropcontainer");
const fileInput = document.getElementById("images");
dropContainer.addEventListener(
"dragover",
(e) => {
// prevent default to allow drop
e.preventDefault();
},
false
);
dropContainer.addEventListener("dragenter", () => {
dropContainer.classList.add("drag-active");
});
dropContainer.addEventListener("dragleave", () => {
dropContainer.classList.remove("drag-active");
});
dropContainer.addEventListener("drop", (e) => {
e.preventDefault();
dropContainer.classList.remove("drag-active");
fileInput.files = e.dataTransfer.files;
});
("use strict");
const select = document.querySelector(".select");
const options_list = document.querySelector(".options-list");
const options = document.querySelectorAll(".option");
//show & hide options list
select.addEventListener("click", () => {
options_list.classList.toggle("active");
select.querySelector(".fa-angle-down").classList.toggle("fa-angle-up");
});
//select option
options.forEach((option) => {
option.addEventListener("click", () => {
options.forEach((option) => {
option.classList.remove("selected");
});
select.querySelector("span").innerHTML = option.innerHTML;
option.classList.add("selected");
options_list.classList.toggle("active");
select.querySelector(".fa-angle-down").classList.toggle("fa-angle-up");
});
});
// Google Sign-In
function onLoad() {
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: 'YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com',
});
});
}
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
var id_token = googleUser.getAuthResponse().id_token;
fetch('/backend/auth.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ token: id_token }),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
}
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
backend/user.php
Handle user management logic, including storing user information and managing sessions.
require_once 'vendor/autoload.php';
$client = new Google_Client();
$client->setClientId('YOUR_GOOGLE_CLIENT_ID');
$client->setClientSecret('YOUR_GOOGLE_CLIENT_SECRET');
$client->setRedirectUri('YOUR_REDIRECT_URI');
$client->addScope('email');
$client->addScope('profile');
session_start();
function getGoogleAuthUrl() {
global $client;
return $client->createAuthUrl();
}
function authenticateGoogleUser($code) {
global $client;
$token = $client->fetchAccessTokenWithAuthCode($code);
$client->setAccessToken($token['access_token']);
$google_oauth = new Google_Service_Oauth2($client);
$google_account_info = $google_oauth->userinfo->get();
$email = $google_account_info->email;
$name = $google_account_info->name;
storeUser($email, $name);
}
function storeUser($email, $name) {
$conn = new mysqli('localhost', 'username', 'password', 'database');
$result = $conn->query("SELECT * FROM users WHERE email = '$email'");
if ($result->num_rows == 0) {
$conn->query("INSERT INTO users (email, name) VALUES ('$email', '$name')");
}
$_SESSION['user_email'] = $email;
$_SESSION['user_name'] = $name;
header('Location: dashboard.php');
}
function logout() {
session_start();
session_unset();
session_destroy();
header('Location: index.php');
}
if (isset($_GET['login'])) {
header('Location: ' . getGoogleAuthUrl());
}
if (isset($_GET['code'])) {
authenticateGoogleUser($_GET['code']);
}
if (isset($_GET['logout'])) {
logout();
}
backend/auth.php
Handle server-side code for verifying tokens and managing user sessions.
<?php
require_once 'vendor/autoload.php';
session_start();
class GoogleAuth {
private $client;
public function __construct() {
$this->client = new Google_Client();
$this->client->setClientId('YOUR_GOOGLE_CLIENT_ID');
$this->client->setClientSecret('YOUR_GOOGLE_CLIENT_SECRET');
$this->client->setRedirectUri('YOUR_REDIRECT_URI');
$this->client->addScope('email');
$this->client->addScope('profile');
}
public function verifyIdToken($idToken) {
try {
$payload = $this->client->verifyIdToken($idToken);
if ($payload) {
$userid = $payload['sub'];
return $payload;
} else {
return false;
}
} catch (Exception $e) {
return false;
}
}
public function manageUserSession($payload) {
$user = getOrCreateUser($payload);
if ($user) {
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['name'];
$_SESSION['user_email'] = $user['email'];
return true;
}
return false;
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$idToken = $_POST['id_token'];
$googleAuth = new GoogleAuth();
$payload = $googleAuth->verifyIdToken($idToken);
if ($payload) {
if ($googleAuth->manageUserSession($payload)) {
echo json_encode(['status' => 'success']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Failed to manage user session']);
}
} else {
echo json_encode(['status' => 'error', 'message' => 'Invalid ID token']);
}
}
?>
This setup will allow users to sign in using their Google accounts and manage their sessions effectively.
Click here to create a Pull Request with the proposed solution
Files used for this task:
` tag to ensure it loads after the rest of the page content. 2. **Initialize the Google API**: Add a script to initialize the Google API with your client ID. Here's how you can modify the `footer.php` file: ```php
What - description of what you me to do Example: Hey @autopilot implement a Google sign-in on my website. Make changes to the front end and the back end of the application
Why - explain why this is important Example: I want to allow users to signup and login using their Google account