Как мне выполнить oauth (2) для аутентификации в GMail-api из приложения Meteor. js без ручной аутентификации в браузере? - PullRequest
7 голосов
/ 15 января 2020

Я хочу войти в свою программу сервера метеоров без ручной аутентификации браузера. Таким образом, аутентификация должна быть автоматизирована; Я не хочу вмешательства пользователя / взаимодействия вообще. Я встречал ответ здесь , но он есть в java, и я не знаю, работает ли он или нет. Может кто-нибудь дать ответ в метеоре. js. Если ответ в node.js и может работать в метеоре, это тоже нормально.

Предпочтительно я хочу запустить этот код метеора в бэкэнде как часть работы, используя pacjage msavin / SteveJobs.

1 Ответ

0 голосов
/ 23 января 2020

Ниже приведен рабочий фрагмент в простом виде node.js

Функциональность:

Вы можете настроить его для своих нужд, используя Gmail API

Если вы бороться с этим примером попробуйте Node.js Краткое руководство

Вот фрагмент:

const fs = require('fs');
const readline = require('readline');
const { google } = require('googleapis');

// If modifying these scopes, delete token.json.
const SCOPES = [
  'https://mail.google.com/',
  'https://www.googleapis.com/auth/gmail.modify',
  'https://www.googleapis.com/auth/gmail.compose',
  'https://www.googleapis.com/auth/gmail.send'
];
// 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 = 'token.json';

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const { client_secret, client_id, redirect_uris } = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
    client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getNewToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getNewToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

/********************************************************************************************
*********************************************************************************************
*********************************************************************************************
 * Custom edits here
 */

let labelList = [];

function listLabels(auth) {

  const gmail = google.gmail({ version: 'v1', auth });

  gmail.users.labels.list({
    userId: 'me',
  }, (err, res) => {

    if (err) return console.log('The API returned an error: ' + err);

    const labels = res.data.labels;

    if (labels.length) {
      labels.forEach((label) => {
        labelList.push(`${label.name}`);
      });
    } else {
      console.log('No labels found.');
    }

  });

  console.log('===listLabels finished===');

}

function makeEmailBody(to, from, subject, message) {

  let str = [
    "Content-Type: text/plain; charset=\"UTF-8\"\n",
    "MIME-Version: 1.0\n",
    "Content-Transfer-Encoding: 7bit\n",
    "to: ", to, "\n",
    "from: ", from, "\n",
    "subject: ", subject, "\n\n",
    message
  ].join('');

  let encodedMail = new Buffer(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');

  return encodedMail;

}

function sendMessage(auth) {

  let raw = makeEmailBody(
    /* to */'email@gmail.com',
    /* from */'email@gmail.com',
    /* subject */'Subject',
    /* message */`Labels:
      ${labelList}
    `);

  const gmail = google.gmail({ version: 'v1', auth });

  gmail.users.messages.send({
    auth: auth,
    userId: 'me',
    resource: {
      raw: raw
    }
  }, (err, res) => {
    return (err || res)
  });

  console.log('===SendMessage finished===');

}

let userId = 'email@gmail.com';
let messageId = '__id__'; 

function getEmail(auth){

  const gmail = google.gmail({ version: 'v1', auth });

  gmail.users.messages.get({
    id: messageId,
    userId: userId,
    format: 'full'
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    console.log(res.data);
  });

  console.log('===listLabels finished===');

}

// RUN script
fs.readFile('credentials.json', (err, content) => {

  if (err) {
    console.log('Error loading client secret file: ' + err);
    return;
  }

  authorize(JSON.parse(content), getEmail);

  // authorize(JSON.parse(content), listLabels);
  // authorize(JSON.parse(content), listFiles);
  // authorize(JSON.parse(content), sendMessage);

});

Как создать учетную запись службы:

  1. Создание проекта в Консоль администратора
  2. Создание учетной записи службы
  3. Go для консоли администратора> Безопасность> Дополнительные параметры> Управление API клиентский доступ
  4. В поле «Имя клиента» укажите полный адрес электронной почты созданной учетной записи службы
  5. . В одну или несколько областей API введите https://mail.google.com/ и нажмите «Авторизовать» * 1051. *
  6. Вернитесь к Сервисные учетные записи , выберите свою учетную запись, Включите делегирование G Suite для всего домена
  7. Создайте KEY учетной записи службы (загрузите ее как. json) * 105 7 *
  8. Активируйте Gmail API для вашего проекта. Go к API и услугам> Панель управления , нажмите ВКЛЮЧИТЬ АПИС И УСЛУГИ, найдите Gmail и включите его.

Теперь вы получили служебную учетную запись и можете использовать ее в ваш проект.

...