sebastianmarco55 / tetra2.github.io

0 stars 0 forks source link

Task Tile #2

Open sebastianmarco55 opened 1 month ago

sebastianmarco55 commented 1 month ago

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

codeautopilot[bot] commented 1 month ago

Potential solution

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.

How to implement

Front-End Changes

1. 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 */
}

2. 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">
          &copy;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>

3. 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>

4. 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>

5. 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.');
  });
}

Back-End Changes

1. 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();
}

2. 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']);
    }
}
?>

Summary

  1. Front-End Changes: Add styles, include Google API script, add Google sign-in button, and handle sign-in process.
  2. Back-End Changes: Handle user management logic, verify tokens, and manage user sessions.

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:

Changes on css/style.css To add styles for the Google sign-in button to ensure it matches the website's design, you can follow these steps: 1. **Define the Button Style**: Add a new CSS class for the Google sign-in button. This class should include styles that align with the overall design of your website. 2. **Use Variables for Consistency**: Utilize the existing CSS variables (e.g., `--primary`, `--secondary`) to maintain consistency with the current design. Here's a concrete proposal for the changes to be made in the `css/style.css` file: ```css /* 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 */ } ``` ### Explanation: - **`.google-signin-btn`**: This class styles the Google sign-in button with Google's brand color, white text, padding, border-radius, and a pointer cursor. - **Hover Effect**: The button changes to a slightly darker shade when hovered over. - **Image Margin**: If the button includes a Google logo, this ensures there's space between the logo and the text. - **Focus State**: Adds a focus ring for accessibility when the button is focused. ### Next Steps: 1. **Add the Google Sign-In Button**: Use this class in your HTML file where the Google sign-in button is implemented. 2. **Include Google Logo**: Optionally, include the Google logo within the button for better user recognition. This should ensure that the Google sign-in button is visually consistent with the rest of your website's design.
Changes on footer.php To ensure that the necessary scripts for Google sign-in are included in the footer for proper loading, you need to add the Google API script to the `footer.php` file. This script will allow the front-end to interact with Google's authentication services. Here's a concrete proposal to modify the `footer.php` file: 1. **Add the Google API Script**: Insert the Google API script just before the closing `` 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

©2024 Tetra.Toate drepturile rezervate.

Proiectat de BMS

``` ### Explanation: 1. **Google API Script**: The script `https://apis.google.com/js/platform.js` is included to load the Google API. 2. **Initialization Script**: The inline script initializes the Google API with your client ID. Replace `'YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com'` with your actual Google client ID. 3. **Loading Main JavaScript**: Ensure that your main JavaScript file (`main.js`) is loaded after the Google API script. This modification ensures that the Google sign-in functionality is properly loaded and initialized when the page is accessed.
Changes on index.html To implement Google sign-in on your website, you need to add the Google sign-in button and include the necessary Google API script in the `index.html` file. Here’s a step-by-step guide to achieve this: ### Step 1: Include the Google API Script Add the Google API script in the `` section of your `index.html` file. This script will load the Google Platform Library, which is necessary for Google sign-in. ```html ... ... ``` Replace `YOUR_GOOGLE_CLIENT_ID` with your actual Google Client ID. ### Step 2: Add the Google Sign-In Button Add the Google sign-in button in the appropriate place within the `` section of your `index.html` file. For example, you can add it in the navigation bar or a dedicated section for user authentication. ```html ...
... ``` ### Step 3: Handle the Sign-In Process You will need to handle the sign-in process using JavaScript. This involves defining the `onSignIn` function that will be called when a user successfully signs in. Add the following script at the end of the `` section, just before the closing `` tag: ```html ...
... ``` ### Summary 1. **Include the Google API Script**: Add the script in the `` section. 2. **Add the Google Sign-In Button**: Place the button in the `` section where you want it to appear. 3. **Handle the Sign-In Process**: Implement the `onSignIn` function to handle the sign-in process and send the ID token to your backend. This setup will allow users to sign in using their Google accounts. The next steps involve handling the ID token on the backend to verify the user and manage sessions, which will be addressed in the relevant backend files (`auth.php` and `user.php`).
Changes on backend/user.php To implement Google sign-in functionality in the `backend/user.php` file, you will need to handle user management logic, including storing user information and managing sessions. Here is a step-by-step guide to achieve this: 1. **Include Google API Client Library**: Ensure you have the Google API PHP Client Library installed. You can install it using Composer: ```sh composer require google/apiclient:^2.0 ``` 2. **Initialize Google Client**: Set up the Google Client in your `user.php` file. ```php 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'); ``` 3. **Handle Google Sign-In**: Create functions to handle the Google sign-in process, verify tokens, and manage user sessions. ```php session_start(); function getGoogleAuthUrl() { global $client; return $client->createAuthUrl(); } function authenticateGoogleUser($code) { global $client; $token = $client->fetchAccessTokenWithAuthCode($code); $client->setAccessToken($token['access_token']); // Get user 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; // Store user information and manage session storeUser($email, $name); } function storeUser($email, $name) { // Assuming you have a database connection setup $conn = new mysqli('localhost', 'username', 'password', 'database'); // Check if user already exists $result = $conn->query("SELECT * FROM users WHERE email = '$email'"); if ($result->num_rows == 0) { // Insert new user $conn->query("INSERT INTO users (email, name) VALUES ('$email', '$name')"); } // Set session variables $_SESSION['user_email'] = $email; $_SESSION['user_name'] = $name; // Redirect to a logged-in page header('Location: dashboard.php'); } ``` 4. **Logout Functionality**: Add a function to handle user logout. ```php function logout() { session_start(); session_unset(); session_destroy(); header('Location: index.php'); } ``` 5. **Usage Example**: Example of how to use these functions in your application. ```php // Redirect to Google for authentication if (isset($_GET['login'])) { header('Location: ' . getGoogleAuthUrl()); } // Handle Google callback if (isset($_GET['code'])) { authenticateGoogleUser($_GET['code']); } // Logout if (isset($_GET['logout'])) { logout(); } ``` This setup will allow your application to handle Google sign-in, store user information, and manage user sessions. Make sure to replace placeholders like `YOUR_GOOGLE_CLIENT_ID`, `YOUR_GOOGLE_CLIENT_SECRET`, and `YOUR_REDIRECT_URI` with actual values from your Google Developer Console.
Changes on backend/auth.php To implement server-side code for handling Google sign-in, verifying tokens, and managing user sessions in the `backend/auth.php` file, follow these steps: 1. **Include Google API Client Library**: Use Composer to install the Google API Client library. 2. **Set Up Google Client**: Initialize the Google Client with your credentials. 3. **Handle Token Verification**: Verify the ID token received from the client-side. 4. **Manage User Sessions**: Create or update user sessions based on the verified token. Here's a concrete implementation plan for `backend/auth.php`: ### Step 1: Install Google API Client Library First, ensure you have Composer installed. Then, run the following command in your project directory: ```sh composer require google/apiclient:^2.0 ``` ### Step 2: Initialize Google Client Create a function to initialize the Google Client with your credentials. ### Step 3: Verify ID Token Create a function to verify the ID token received from the client-side. ### Step 4: Manage User Sessions Create or update user sessions based on the verified token. ### Example Code for `backend/auth.php` ```php 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) { // Assuming you have a function to get or create a user in your database $user = getOrCreateUser($payload); if ($user) { $_SESSION['user_id'] = $user['id']; $_SESSION['user_name'] = $user['name']; $_SESSION['user_email'] = $user['email']; return true; } return false; } } // Example usage 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']); } } ?> ``` ### Explanation: 1. **GoogleAuth Class**: Initializes the Google Client with your credentials. 2. **verifyIdToken Method**: Verifies the ID token received from the client-side. 3. **manageUserSession Method**: Manages user sessions by creating or updating user information in your database. 4. **Example Usage**: Handles a POST request to verify the ID token and manage the user session. This implementation ensures that your server can handle Google sign-in, verify tokens, and manage user sessions effectively.
Changes on header.php To implement the Google sign-in functionality in the `header.php` file, you need to 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. Here’s a step-by-step guide to achieve this: 1. **Add Google Sign-In Button:** - Insert a Google sign-in button within the navigation bar. 2. **Update Navigation Bar Based on Sign-In Status:** - Use PHP to check if the user is signed in and update the navigation bar accordingly. Here is the modified `header.php` file with the necessary changes: ```php ``` ### Explanation: 1. **Google Sign-In Button:** - Added a placeholder `` tag with `id="google-signin-button"` for the Google sign-in button. - The button will be rendered by the Google API script. 2. **Sign-In Status Check:** - Used PHP to check if the user is signed in (`isset($_SESSION['user'])`). - Displayed a "Logout" link if the user is signed in. - Displayed the Google sign-in button if the user is not signed in. 3. **Google API Script:** - Included the Google API script. - Added JavaScript functions to handle the Google sign-in process (`onSignIn` and `renderButton`). 4. **Backend Communication:** - Sent the ID token to the backend (`backend/auth.php`) for verification and session management. This should cover the necessary changes to the `header.php` file for implementing Google sign-in functionality.
Changes on js/main.js To implement Google sign-in functionality in your application, you need to add JavaScript code to handle the Google sign-in process and manage user authentication. Below is a step-by-step guide on how to achieve this in the `js/main.js` file: ### Step-by-Step Implementation 1. **Load the Google API Script**: Ensure that the Google API script is included in your HTML file (`index.html`). This is necessary for the JavaScript code to interact with Google's authentication services. ```html ``` 2. **Initialize the Google API Client**: Add the following code to initialize the Google API client in your `js/main.js` file. This code should be executed once the Google API script has loaded. ```javascript function onLoad() { gapi.load('auth2', function() { gapi.auth2.init({ client_id: 'YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com', }); }); } ``` 3. **Add Google Sign-In Button**: Ensure that you have a Google sign-in button in your HTML file. This button will trigger the Google sign-in process. ```html
``` 4. **Handle Sign-In Success**: Add a function to handle the sign-in success event. This function will be called when a user successfully signs in with their Google account. ```javascript function onSignIn(googleUser) { var profile = googleUser.getBasicProfile(); console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead. console.log('Name: ' + profile.getName()); console.log('Image URL: ' + profile.getImageUrl()); console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present. // Send the ID token to your backend for verification and user session management 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); // Handle successful authentication (e.g., redirect to a dashboard) }) .catch((error) => { console.error('Error:', error); }); } ``` 5. **Sign-Out Functionality**: Optionally, you can add a sign-out function to allow users to sign out of their Google account. ```javascript function signOut() { var auth2 = gapi.auth2.getAuthInstance(); auth2.signOut().then(function () { console.log('User signed out.'); }); } ``` ### Complete Code for `js/main.js` ```javascript (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.'); }); } ``` ### Notes: - Replace `'YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com'` with your actual Google Client ID. - Ensure that the backend endpoint `/backend/auth.php` is properly set up to handle the token verification and user session management. This should cover the necessary changes to the `js/main.js` file to implement Google sign-in functionality.
_Disclaimer: This comment was entirely generated using AI. Be aware that the information provided may be incorrect._ Current plan usage: 28.41% **Have feedback or need help?** [Discord](https://discord.gg/r72ykfvyx7) [Documentation](https://docs.codeautopilot.com/) [support@codeautopilot.com](mailto:support@codeautopilot.com)