Home > Enterprise >  How to develop a Google sign in to extract details from Google analytics?
How to develop a Google sign in to extract details from Google analytics?

Time:12-16

I am extremely new to Google APIs so forgive me if I'm lack knowledge. I am trying to develop a Google sign-in, provided by Google documentations 2021, to allow any existing Google account links to Google Analytics which I need to extract the details such as ID Token of the google account and view ID from Google analytics as my main objective is to develop a dashboard to pull data from Google analytics based on viewID of the user Google account.

What I want to find out is if it's possible to automate or collect by extracting the ID token, user ID & view ID whenever a user signs in EJS. currently, I am calling the pages from the backend so the Google authentication and authorization are on the server-side.

I am open to suggestions and willing to ask for your contact for discussion.

Google sign in documentation
https://developers.google.com/identity/gsi/web/guides/display-button

helloAnalytics.ejs is a login page

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Hello Analytics Reporting API V4</title>
  <script src="https://accounts.google.com/gsi/client" async defer></script>
</head>

<body>
  <h1>Hello Analytics Reporting API V4</h1>


  <!-- displaying the google sign in button -->
  <div id="buttonDiv" onclick=></div>
</body>
<script>
  window.onload = function () {
    google.accounts.id.initialize({
      client_id: "<%- clientId %>",
      callback: handleCredentialResponse
    });
    google.accounts.id.renderButton(
      document.getElementById("buttonDiv"),
      { theme: "outline", size: "large" }  // customization attributes
    );
    google.accounts.id.prompt(); // also display the One Tap dialog
  }

  function handleCredentialResponse(response) {
    let t = response;
    // display the JWT token
    console.log("Encoded JWT ID token: "   t.credential);
  }
</script>

</html>

app.js server-side

app.get("/loginUAT", (req, res) => {
  let scope = [googleScope];
  const oauth2Client = new google.auth.OAuth2(
    clientId,
    clientSecret,
    redirectURI
  );

  let url = oauth2Client.generateAuthUrl({
    access_type: "offline",
    scope: scope,
    state: JSON.stringify({
      callbackUrl: req.body.callbackUrl,
      userID: req.body.userID,
    }),
  });

  console.log(url);

  request(url, (err, response, body) => {
    console.log(`error: ${err}`);
    console.log("statusCode", response && response.statusCode);
    res.send({ url });
  });
});

app.get("/dashboard", async (req, res) => {
  const queryURL = new urlParse(req.url);
  const code = queryParse.parse(queryURL.query).code;
  const oAuth2Client = new google.auth.OAuth2(
    clientId,
    clientSecret,
    redirectURI
  );

  const tokens = await oAuth2Client.getToken(code);
  console.log("token: "   tokens);

  let stepArray = [];

  try {
    const result = await axios({
      method: "POST",
      headers: {
        authorization: "Bearer "   tokens.tokens.access_token,
      },
      "Content-Type": "application/json",
      url: `https://analyticsreporting.googleapis.com/v4/reports:batchGet`,
      data: {
        reportRequests: [
          {
            viewId: viewId,
            dateRanges: [
              {
                startDate: "2021-06-15",
                endDate: "2021-06-30",
              },
            ],
            metrics: [
              {
                expression: "ga:sessions",
              },
            ],
            dimensions: [
              {
                name: "ga:browser",
              },
            ],
          },
        ],
      },
    });

    var newVisitor = result.data.reports[0].data.rows[0];
    console.log(newVisitor);
    var m = parseInt(newVisitor.metrics[0].values[0] * 1);
    console.log(m);
    // stepArray = result.data.reports
    res.render("dashboardtesting", {
      metrics: m,
    });
  } catch (e) {
    console.log(e);
  }
});

CodePudding user response:

if you want to get google auth code for node js, you can generate it with opensource https://github.com/DhiWise/dhiwise-nodejs

if you can't get it or use it, I will send you the full code

plz ping me if you are not able to get

CodePudding user response:

You can go through with google firebase for that by which you get token of google auth which you have to apply on your application for google auth

  • Related