pranayseela / TEKVENUE

TEKVENUE
0 stars 0 forks source link

Task Tile #3

Open pranayseela opened 2 months ago

pranayseela commented 2 months 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 2 months ago

Potential solution

To implement Google sign-in functionality on your website, we need to make changes to both the front end and the back end of the application. The front end will handle the user interaction and the initial sign-in process, while the back end will handle the verification of the Google token and manage user sessions.

How to implement

Backend Changes

File: backend/routes.js

  1. Import Necessary Modules: Import express and the custom authentication module (auth.js).
  2. Initialize Router: Create an instance of the Express router.
  3. Define Routes:
    • Google Sign-In Route: Redirects the user to Google's OAuth 2.0 authorization endpoint.
    • Google Sign-In Callback Route: Handles the callback from Google, verifies the token, and manages the user session.
  4. Export the Router: Export the router to be used in the main server file.
const express = require('express');
const { verifyGoogleToken } = require('./auth');

const router = express.Router();

router.get('/auth/google', (req, res) => {
  const googleSignInURL = 'https://accounts.google.com/o/oauth2/v2/auth?client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&response_type=code&scope=email profile';
  res.redirect(googleSignInURL);
});

router.get('/auth/google/callback', async (req, res) => {
  const { code } = req.query;

  try {
    const user = await verifyGoogleToken(code);
    // Handle user session (e.g., create a session, issue a JWT, etc.)
    res.status(200).json({ message: 'Sign-in successful', user });
  } catch (error) {
    res.status(400).json({ message: 'Sign-in failed', error: error.message });
  }
});

module.exports = router;

File: backend/auth.js

  1. Install Required Packages: Ensure you have google-auth-library and express-session installed.
  2. Set Up Google Auth Library: Initialize the Google Auth library to verify tokens.
  3. Create Session Management: Use express-session to manage user sessions.
  4. Verify Google Token: Write a function to verify the Google sign-in token.
  5. Handle User Sessions: Create functions to manage user sessions after successful token verification.
const { OAuth2Client } = require('google-auth-library');
const session = require('express-session');

const CLIENT_ID = 'YOUR_GOOGLE_CLIENT_ID';
const client = new OAuth2Client(CLIENT_ID);

const sessionMiddleware = session({
  secret: 'your_secret_key',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false }
});

async function verifyGoogleToken(token) {
  const ticket = await client.verifyIdToken({
    idToken: token,
    audience: CLIENT_ID,
  });
  const payload = ticket.getPayload();
  return payload;
}

async function handleGoogleSignIn(req, res) {
  const token = req.body.token;
  try {
    const userData = await verifyGoogleToken(token);
    req.session.user = {
      id: userData.sub,
      email: userData.email,
      name: userData.name,
    };
    res.status(200).send({ message: 'Sign-in successful', user: req.session.user });
  } catch (error) {
    res.status(401).send({ message: 'Invalid token', error: error.message });
  }
}

module.exports = {
  sessionMiddleware,
  handleGoogleSignIn,
};

Frontend Changes

File: js/main.js

  1. Load the Google API Script: Ensure the Google API script is included in your index.html file.
  2. Initialize the Google API Client: Add JavaScript code to initialize the Google API client.
  3. Handle the Sign-In Process: Implement functions to handle the sign-in process and manage user sessions.
;(function () {
  'use strict';

  function initializeGoogleSignIn() {
    gapi.load('auth2', function() {
      gapi.auth2.init({
        client_id: 'YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com'
      });
    });
  }

  function onSignIn(googleUser) {
    var profile = googleUser.getBasicProfile();
    var id_token = googleUser.getAuthResponse().id_token;
    $.ajax({
      type: 'POST',
      url: '/auth/google',
      data: { id_token: id_token },
      success: function(response) {
        console.log('User signed in successfully');
      },
      error: function(error) {
        console.log('Error signing in', error);
      }
    });
  }

  function signOut() {
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
      console.log('User signed out.');
    });
  }

  $(function(){
    initializeGoogleSignIn();
  });

  window.onSignIn = onSignIn;
  window.signOut = signOut;

}());

File: index.html

  1. Include the Google API Script: Add the Google API script to the <head> section.
  2. Add the Google Sign-In Button: Add a Google sign-in button to the body of your HTML file.
<!DOCTYPE html>
<html class="no-js">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>TEKVENUE</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="TEKVENUE" />
  <meta name="keywords" content="TEKVENUE" />
  <meta name="author" content="Pranay" />
  <link rel="shortcut icon" href="favicon.ico">
  <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,700' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="css/animate.css">
  <link rel="stylesheet" href="css/icomoon.css">
  <link rel="stylesheet" href="css/bootstrap.css">
  <link rel="stylesheet" href="css/owl.carousel.min.css">
  <link rel="stylesheet" href="css/owl.theme.default.min.css">
  <link rel="stylesheet" href="css/index.css">
  <script src="js/modernizr-2.6.2.min.js"></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 style="background-color:black;">
  <div class="box-wrap">
    <header role="banner" id="fh5co-header" style="background-color:black; margin-bottom:0em; padding-bottom:1em;">
      <div class="container" style="margin-left:0px;">
        <nav class="navbar navbar-default" style="background-color:black;">
          <div class="row" style="background-color:black;">
            <div class="col-md-3">
              <div class="fh5co-navbar-brand" style="line-height:0;">
                <img src="images/logo.jpg" alt="TEKVENUE" height="42" width="42">
                <a class="fh5co-logo" href="index.html" style="color:orange;">&nbsp; TEKVENUE</a>
                <p style="font-size:12px; color:deeppink; margin-left:72px;">The Place For The Technology</p>
              </div>
            </div>
            <div class="col-md-9 main-nav">
              <ul class="nav text-right">
                <li><a href="index.html" style="color:orange;">HOME</a></li>
                <li><a href="about.html" style="color:cornflowerblue;">About Us</a></li>
                <li><a href="services.html" style="color:deeppink;">Services</a></li>
                <li><a href="contact.html" style="color:green;">Contact Us</a></li>
              </ul>
            </div>
          </div>
        </nav>
      </div>
    </header>
    <div id="fh5co-intro-section" class="section-overlay animate-box" data-animate-effect="fadeIn">
      <img src="images/img_large_11.jpg" alt="TEKVENUE" height="400" width="100%">
    </div>
  </div>
  <div id="fh5co-media-section">
    <div class="container">
      <div class="row">
        <div class="col-md-7 animate-box" style="width:50%">
          <div class="fh5co-cover" style="background-image: url(images/work-1.jpg);">
            <div class="desc" style="position:relative;background:#996300;">
              <h1 style="color:white;text-decoration: underline;">Who we are</h1>
              <p>We are an Information Technology company focused on IT staffing and software project development.</p>
              <p>Tekvenue is a global leader when considering the best means of support of your business’s processes, data analytics, reporting systems, and information. Tying together the vast interconnected computing systems in today’s corporations is a challenging task even in the best of times. Ensuring that all systems involved in the process flow can “talk” to each other and keeping all departments, business units, and customers informed is part of Tekvenue’s commitment to Enterprise System Management (ESM).</p>
              <p>By leveraging the best minds in the fields of ESM, Tekvenue is uniquely positioned to structure your IT processes to maximize your return on investment.</p>
              <span>Learn More</span>
            </div>
          </div>
        </div>
        <div class="col-md-5 animate-box" style="width:50%">
          <div class="fh5co-cover" style="background-image: url(images/work-1.jpg);">
            <div class="desc" style="position:relative;background:#996300;">
              <h1 style="color:white;text-decoration: underline;">Our vision</h1>
              <p>Our vision is to become a leading technology company with strong focus on customer relationships, coherence with partners, and employee creativity.</p>
              <p>We serve clients in critical, technology-dependent industries such as health care, telecom, banking, finance, manufacturing, petroleum, retail, and beyond. We deploy our renowned staffing and IT solutions in the United States, India, and Canada. Contact us today and let us apply our years of experience in IT and business development to your technology needs.</p>
              <p>We love new projects! Let's get started.</p>
              <span>Learn More</span>
              </br>
              </br>
              </br>
              </br>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div id="fh5co-intro-section" style="bottom-padding:2em;">
    <div class="fh5co-intro-cover text-center animate-box" data-stellar-background-ratio="0.5" style="background:#996300;">
      <a href="#" class="btn">Our company will provide your business with the professional attention it deserves.</a>
    </div>
  </div>
  <div class="g-signin2" data-onsuccess="onSignIn"></div>
  <footer>
    <div id="footer">
      <div class="container">
        <div class="row">
          <div class="col-md-6 col-md-offset-3 text-center">
            <p>Copyright 2017 TEKVENUE <a href="#" style="color:orange;">TEKVENUE</a>. All Rights Reserved.</p>
            <p class="fh5co-social-icons">
              <a href="#"><i class="icon-twitter-with-circle"></i></a>
              <a href="#"><i class="icon-facebook-with-circle"></i></a>
              <a href="#"><i class="icon-instagram-with-circle"></i></a>
            </p>
          </div>
        </div>
      </div>
    </div>
  </footer>
  </div>
  <script src="js/jquery.min.js"></script>
  <script src="js/jquery.easing.1.3.js"></script>
  <script src="js/bootstrap.min.js"></script>
  <script src="js/owl.carousel.min.js"></script>
  <script src="js/jquery.waypoints.min.js"></script>
  <script src="js/jquery.stellar.min.js"></script>
  <script src="js/main.js"></script>
</body>
</html>

Explanation:

  1. Google API Script: This script loads the Google API client library.
  2. Google Sign-In Button: This adds a Google sign-in button to your webpage.

By following these steps, you will be able to integrate Google sign-in functionality into your application.

Click here to create a Pull Request with the proposed solution

Files used for this task:

Changes on backend/routes.js To handle Google sign-in requests and responses in the `backend/routes.js` file, you need to define routes that will manage the authentication flow. Here is a step-by-step plan to implement this: 1. **Import Necessary Modules**: Import the required modules such as `express` and the custom authentication module (`auth.js`). 2. **Initialize Router**: Create an instance of the Express router. 3. **Define Routes**: - **Google Sign-In Route**: A route to handle the Google sign-in request. - **Google Sign-In Callback Route**: A route to handle the response from Google after the user has signed in. 4. **Export the Router**: Export the router to be used in the main server file. Here is a concrete implementation of the plan: ```javascript // Import necessary modules const express = require('express'); const { verifyGoogleToken } = require('./auth'); // Assuming auth.js exports a function to verify Google tokens // Initialize router const router = express.Router(); // Route to handle Google sign-in request router.get('/auth/google', (req, res) => { // Redirect to Google sign-in page const googleSignInURL = 'https://accounts.google.com/o/oauth2/v2/auth?client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&response_type=code&scope=email profile'; res.redirect(googleSignInURL); }); // Route to handle Google sign-in callback router.get('/auth/google/callback', async (req, res) => { const { code } = req.query; try { // Verify the Google token const user = await verifyGoogleToken(code); // Handle user session (e.g., create a session, issue a JWT, etc.) // This part depends on your session management strategy res.status(200).json({ message: 'Sign-in successful', user }); } catch (error) { res.status(400).json({ message: 'Sign-in failed', error: error.message }); } }); // Export the router module.exports = router; ``` ### Explanation: - **Google Sign-In Route**: Redirects the user to Google's OAuth 2.0 authorization endpoint. - **Google Sign-In Callback Route**: Handles the callback from Google, verifies the token, and manages the user session. Make sure to replace `YOUR_CLIENT_ID` and `YOUR_REDIRECT_URI` with your actual Google OAuth 2.0 client ID and redirect URI. This implementation assumes that you have a function `verifyGoogleToken` in `auth.js` that takes the authorization code and verifies it with Google to obtain user information. You will need to implement this function separately.
Changes on backend/auth.js To handle the verification of Google sign-in tokens and manage user sessions, you can follow these steps to implement the necessary functionality in the `backend/auth.js` file: 1. **Install Required Packages**: Ensure you have the necessary packages installed. You will need `google-auth-library` for verifying Google tokens and `express-session` for managing user sessions. ```bash npm install google-auth-library express-session ``` 2. **Set Up Google Auth Library**: Initialize the Google Auth library to verify tokens. 3. **Create Session Management**: Use `express-session` to manage user sessions. 4. **Verify Google Token**: Write a function to verify the Google sign-in token. 5. **Handle User Sessions**: Create functions to manage user sessions after successful token verification. Here is a concrete implementation for `backend/auth.js`: ```javascript const { OAuth2Client } = require('google-auth-library'); const session = require('express-session'); // Initialize Google OAuth2 client const CLIENT_ID = 'YOUR_GOOGLE_CLIENT_ID'; const client = new OAuth2Client(CLIENT_ID); // Middleware to initialize session const sessionMiddleware = session({ secret: 'your_secret_key', resave: false, saveUninitialized: true, cookie: { secure: false } // Set to true if using HTTPS }); // Function to verify Google token async function verifyGoogleToken(token) { const ticket = await client.verifyIdToken({ idToken: token, audience: CLIENT_ID, }); const payload = ticket.getPayload(); return payload; } // Function to handle Google sign-in async function handleGoogleSignIn(req, res) { const token = req.body.token; try { const userData = await verifyGoogleToken(token); req.session.user = { id: userData.sub, email: userData.email, name: userData.name, }; res.status(200).send({ message: 'Sign-in successful', user: req.session.user }); } catch (error) { res.status(401).send({ message: 'Invalid token', error: error.message }); } } module.exports = { sessionMiddleware, handleGoogleSignIn, }; ``` ### Explanation: 1. **Google OAuth2 Client Initialization**: The `OAuth2Client` is initialized with your Google Client ID. 2. **Session Middleware**: `express-session` is configured to manage user sessions. 3. **Token Verification**: The `verifyGoogleToken` function verifies the Google sign-in token. 4. **Sign-in Handling**: The `handleGoogleSignIn` function verifies the token, creates a session for the user, and sends a response. ### Next Steps: - **Integrate Session Middleware**: Ensure that the session middleware is used in your Express app. - **Add Routes**: Use the `handleGoogleSignIn` function in your routes to handle sign-in requests. This setup will allow you to verify Google sign-in tokens and manage user sessions effectively.
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. This involves initializing the Google API client and managing the sign-in process. Below is a step-by-step guide to achieve this: ### Step-by-Step Implementation 1. **Load the Google API Script**: Ensure that the Google API script is included in your `index.html` file. This will allow you to use Google's authentication services. 2. **Initialize the Google API Client**: Add the necessary JavaScript code to initialize the Google API client in your `js/main.js` file. 3. **Handle the Sign-In Process**: Implement functions to handle the sign-in process and manage user sessions. ### Code Changes #### 1. Load the Google API Script Ensure that the following script is added to your `index.html` file: ```html ``` #### 2. Initialize the Google API Client and Handle Sign-In Add the following code to your `js/main.js` file: ```javascript ;(function () { 'use strict'; // Existing code... // Google Sign-In Initialization function initializeGoogleSignIn() { gapi.load('auth2', function() { // Initialize the Google auth2 library gapi.auth2.init({ client_id: 'YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com' }); }); } // Handle Google Sign-In 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 var id_token = googleUser.getAuthResponse().id_token; $.ajax({ type: 'POST', url: '/auth/google', data: { id_token: id_token }, success: function(response) { console.log('User signed in successfully'); // Handle successful sign-in }, error: function(error) { console.log('Error signing in', error); // Handle sign-in error } }); } // Sign-Out Function function signOut() { var auth2 = gapi.auth2.getAuthInstance(); auth2.signOut().then(function () { console.log('User signed out.'); }); } // Document on load. $(function(){ // Existing code... // Initialize Google Sign-In initializeGoogleSignIn(); }); // Expose the onSignIn function to the global scope window.onSignIn = onSignIn; window.signOut = signOut; }()); ``` ### Explanation 1. **initializeGoogleSignIn**: This function loads the Google auth2 library and initializes it with your client ID. 2. **onSignIn**: This function handles the sign-in process. It retrieves the user's profile information and sends the ID token to your backend for verification. 3. **signOut**: This function signs the user out of their Google account. ### Note - Replace `'YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com'` with your actual Google client ID. - Ensure that your backend is set up to handle the `/auth/google` route to verify the ID token and manage user sessions. By following these steps, you will be able to integrate Google sign-in functionality into your application.
Changes on index.html To implement Google sign-in on your website, you need to add a Google sign-in button and include the Google API script in your `index.html` file. Here’s a step-by-step guide on how to do this: ### Step-by-Step Implementation 1. **Include the Google API Script:** Add the Google API script to the `` section of your HTML file. This script will load the Google API client library. 2. **Add the Google Sign-In Button:** Add a Google sign-in button to the body of your HTML file where you want the button to appear. ### Updated `index.html` File Here is the updated `index.html` file with the necessary changes: ```html TEKVENUE
TEKVENUE

Who we are

We are an Information Technology company focused on IT staffing and software project development.

Tekvenue is a global leader when considering the best means of support of your business’s processes, data analytics, reporting systems, and information. Tying together the vast interconnected computing systems in today’s corporations is a challenging task even in the best of times. Ensuring that all systems involved in the process flow can “talk” to each other and keeping all departments, business units, and customers informed is part of Tekvenue’s commitment to Enterprise System Management (ESM).

By leveraging the best minds in the fields of ESM, Tekvenue is uniquely positioned to structure your IT processes to maximize your return on investment.

Learn More

Our vision

Our vision is to become a leading technology company with strong focus on customer relationships, coherence with partners, and employee creativity.

We serve clients in critical, technology-dependent industries such as health care, telecom, banking, finance, manufacturing, petroleum, retail, and beyond. We deploy our renowned staffing and IT solutions in the United States, India, and Canada. Contact us today and let us apply our years of experience in IT and business development to your technology needs.

We love new projects! Let's get started.

Learn More



``` ### Explanation: 1. **Google API Script:** ```html ``` - This script loads the Google API client library. - Replace `YOUR_GOOGLE_CLIENT_ID` with your actual Google client ID. 2. **Google Sign-In Button:** ```html
``` - This adds a Google sign-in button to your webpage. - The `data-onsuccess` attribute specifies the JavaScript function to call when the user successfully signs in. With these changes, your `index.html` file is now set up to include a Google sign-in button and the necessary Google API script. The next steps involve handling the sign-in process in your JavaScript and backend files.