1

I am following this link step by step for accessing gmail API through cloud functions.

When an email will be received by gmail it will publish a message on pub/sub.

I have completed the procedure up to step#5 and when I trigger the function, the login screen appears as shown in step#5 but when I trigger the cloud function it automatically redirects to the google account login page and after giving credentials, it asks for following permissions 1. send email on your behalf 2. view and modify but not delete your email After allowing it gives error "error occurred in authorization process".

An error has occurred in the authorization process.

index.js for cloud functions

    // express-oauth is a Google-provided, open-source package that helps automate
    // the authorization process.
    const Auth = require('@google-cloud/express-oauth2-handlers');
    // googleapis is the official Google Node.js client library for a number of
    // Google APIs, including Gmail.
    const {google} = require('googleapis');
    const gmail = google.gmail('v1');

    // Specify the access scopes required. If authorized, Google will grant your
    // registered OAuth client access to your profile, email address, and data in
    // your Gmail and Google Sheets.
    const requiredScopes = [
      'profile',
      'email',
      'https://www.googleapis.com/auth/gmail.modify',
      'https://www.googleapis.com/auth/spreadsheets'
    ];

    const auth = Auth('datastore', requiredScopes, 'email', true);

    const GCP_PROJECT = process.env.GCP_PROJECT;
    const PUBSUB_TOPIC = process.env.PUBSUB_TOPIC;

    // Call the Gmail API (Users.watch) to set up Gmail push notifications.
    // Gmail will send a notification to the specified Cloud Pub/Sun topic
    // every time a new mail arrives in inbox.
    const setUpGmailPushNotifications = (email, pubsubTopic) => {
      return gmail.users.watch({
        userId: email,
        requestBody: {
          labelIds: ['INBOX'],
          topicName: `projects/${GCP_PROJECT}/topics/${pubsubTopic}`
        }
      });
    };

    // If the authorization process completes successfully, set up Gmail push
    // notification using the tokens returned
    const onSuccess = async (req, res) => {
      let email;

      try {
        // Set up the googleapis library to use the returned tokens.
        email = await auth.auth.authedUser.getUserId(req, res);
        const OAuth2Client = await auth.auth.authedUser.getClient(req, res, email);
        google.options({auth: OAuth2Client});
      } catch (err) {
        console.log(err);
        throw err;
      }

      try {
        await setUpGmailPushNotifications(email, PUBSUB_TOPIC);
      } catch (err) {
        console.log(err);
        if (!err.toString().includes('one user push notification client allowed per developer')) {
          throw err;
        }
      }

      res.send(`Successfully set up Gmail push notifications.`);
    };

    // If the authorization process fails, return an error message.
    const onFailure = (err, req, res) => {
      console.log(err);
      res.send(`An error has occurred in the authorization process.`);
    };

    // Export the Cloud Functions for authorization.
    exports.auth_init = auth.routes.init;
    exports.auth_callback = auth.routes.cb(onSuccess, onFailure);

package.json

{
  "name": "gcf-gmail-codelab-auth",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "repository": {
    "type": "git",
    "url": ""
  },
  "author": "",
  "license": "Apache-2.0",
  "dependencies": {
    "@google-cloud/express-oauth2-handlers": "^0.1.2",
    "express": "^4.16.4",
    "googleapis": "^37.2.0"
  }
}

env_vars.yml

GOOGLE_CLIENT_ID: (gave my client id)
GOOGLE_CLIENT_SECRET: (gave my client secret)
GOOGLE_CALLBACK_URL: (gave my callback function trigger URL )
PUBSUB_TOPIC: (gave my pub/sub topic name)

Saad Tahir
  • 67
  • 2
  • 5
  • Hello! Is there any other message in your error before the text you provided? Could you double check you did all the actions in the 4th step of the guide? – ZektorH Oct 10 '19 at 15:43
  • No, there is no error other than error in authorization process after I trigger the auth_init function. Yes, I have followed the procedure very carefully and one of my colleague is also facing the same error.... – Saad Tahir Oct 10 '19 at 16:01
  • What settings did you change on your Gmail account to allow this? Edit your question with details. Start here https://support.google.com/accounts/answer/6010255?hl=en and here https://developers.google.com/gmail – John Hanley Oct 10 '19 at 17:03
  • When I trigger the cloud function it automatically redirects to the google account login page and after giving credentials, it asks for following permissions 1. send email on your behalf 2. view and modify but not delete your email After allowing it gives error "error occurred in authorization process". – Saad Tahir Oct 10 '19 at 17:42

1 Answers1

0

Problem is that it's written in node 8. Node 10 had a subtle breaking change carrying a huge impact by taking environment variables out of the hard code and using a reference format to identify and access resource outside of your working directory.

As great as this change was, it does create almost invisible errors in your code. Primarily due to the fact that linters mostly won't catch it due to the syntax is correct but the format and structure causes it to read out of context. A lot of which is related to oauth2 and the connection to env.vars such as GOOGLE_APPLICATION_CREDENTIALS which is not set and used outside the function will cause problems. Also the env_vars file is not needed and should be replaced by implementation of your environment during the initial launch command of your function rather than hard coding authorization references in you directory.

Majority of the packages you might install will not function properly with node 8. Only way I was able to get this to work properly was to actually do all the coding directly in cloud shell. I am actually working through the client libraries for all resources involved to put together an updated version. Google desperately needs to update the documentation but that can be quite difficult while at the same time trying to keep up to date on all the tech.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Dave
  • 11
  • 1