Coder Social home page Coder Social logo

Comments (3)

Maxim-Mazurok avatar Maxim-Mazurok commented on August 16, 2024

Same for Google Sheets Quickstart, got this email: "[Action Required] Migrate your OAuth out-of-band flow to an alternative method before Oct. 3, 2022"

from node-samples.

Maxim-Mazurok avatar Maxim-Mazurok commented on August 16, 2024

This is my solution (in getNewToken(), start server, resolve promise once we get code and stop the server; also uses open npm package to open auth link in browser):

import fs from "fs";
import { google } from "googleapis";
import { Credentials, OAuth2Client } from "google-auth-library";
import path from "path";
import http from "http";
import open from "open";
import { URL, URLSearchParams } from "url";

// If modifying these scopes, delete token.json.
const SCOPES = ["https://www.googleapis.com/auth/spreadsheets"];

// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = path.join(__dirname, "token.json");

// Load client secrets from a local file.
const CREDENTIALS_PATH = path.join(__dirname, "credentials.json");
const credentials = fs.readFileSync(CREDENTIALS_PATH, "utf-8");

/**
 * Create an OAuth2 client with the given credentials and returns it
 * @param {Object} credentials The authorization client credentials.
 */
const authorize = async (credentials: {
  installed: {
    client_id: string;
    project_id: string;
    auth_uri: string;
    token_uri: string;
    auth_provider_x509_cert_url: string;
    client_secret: string;
    redirect_uris: string[];
  };
}) => {
  const { client_secret, client_id, redirect_uris } = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
    client_id,
    client_secret,
    redirect_uris[0]
  );

  const getToken = async (): Promise<Credentials> => {
    if (fs.existsSync(TOKEN_PATH)) {
      // Check if we have previously stored a token.
      return JSON.parse(fs.readFileSync(TOKEN_PATH, "utf-8"));
    } else {
      return getNewToken(oAuth2Client);
    }
  };

  const token = await getToken();
  oAuth2Client.setCredentials(token);
  return oAuth2Client;
};

/**
 * Get and store new token after prompting for user authorization
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 */
const getNewToken = async (
  oAuth2Client: OAuth2Client
): Promise<Credentials> => {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: "offline",
    scope: SCOPES,
  });
  console.log("Authorize this app by visiting this url:", authUrl);
  open(authUrl);

  const code = await new Promise<string>((resolve) => {
    const server = http
      .createServer((request, response) => {
        const url = new URL(`http://localhost${request.url}`);
        const code = new URLSearchParams(url.search).get("code");
        if (code) {
          response.end("Handling the code to your NodeJS app, check it...");
          server.close();
          resolve(code);
          return;
        }
        response.end("waiting for code...");
      })
      .listen(19843);
  });

  let token: Credentials;
  try {
    token = (await oAuth2Client.getToken(code)).tokens;
  } catch (error) {
    throw `Error while trying to retrieve access token: ${error}`;
  }
  oAuth2Client.setCredentials(token);

  // Store the token to disk for later program executions
  fs.writeFileSync(TOKEN_PATH, JSON.stringify(token));
  console.log("Token stored to", TOKEN_PATH);
  return token;
};

export class GoogleSheets {
  private oAuth2Client: OAuth2Client | undefined;

  public async getOAuth2Client() {
    if (this.oAuth2Client === undefined) {
      this.oAuth2Client = await authorize(JSON.parse(credentials));
    }
    return this.oAuth2Client;
  }
}

in credentials.json:

-"redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"]
+"redirect_uris": ["http://localhost:19843"]

from node-samples.

bakkot avatar bakkot commented on August 16, 2024

This is a problem for all of the samples, not just adminSDK.

@sqrrrl (sorry if you are not the appropriate person to ping; I'm not sure who maintains this): All of the quickstart samples for node are currently broken because of this. This is particularly bad these are often the first place developers start. Any chance you can prioritize this, or ping someone who can?

from node-samples.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.