itizawa 4 лет назад
Родитель
Сommit
c2a5ff836b
2 измененных файлов с 51 добавлено и 55 удалено
  1. 44 13
      src/server/routes/apiv3/slack-integration.js
  2. 7 42
      src/server/service/slackbot.js

+ 44 - 13
src/server/routes/apiv3/slack-integration.js

@@ -1,9 +1,10 @@
 const express = require('express');
 const mongoose = require('mongoose');
+const urljoin = require('url-join');
 
 const loggerFactory = require('@alias/logger');
 
-const { verifySlackRequest } = require('@growi/slack');
+const { verifySlackRequest, generateWebClient } = require('@growi/slack');
 
 const logger = loggerFactory('growi:routes:apiv3:slack-integration');
 const router = express.Router();
@@ -24,18 +25,20 @@ module.exports = (crowi) => {
       return res.status(400).send({ message });
     }
 
-    const slackAppIntegrationCount = await SlackAppIntegration.estimatedDocumentCount({ tokenPtoG });
+    const slackAppIntegration = await SlackAppIntegration.findOne({ tokenPtoG });
 
     logger.debug('verifyAccessTokenFromProxy', {
       tokenPtoG,
     });
 
-    if (slackAppIntegrationCount === 0) {
+    if (slackAppIntegration == null) {
       return res.status(403).send({
         message: 'The access token that identifies the request source is slackbot-proxy is invalid. Did you setup with `/growi register`?',
       });
     }
 
+    req.shareSearchResults = slackAppIntegration.tokenGtoP;
+
     next();
   }
 
@@ -44,8 +47,35 @@ module.exports = (crowi) => {
     return next();
   };
 
+  const generateClientForResponse = (req, res, next) => {
+    const currentBotType = crowi.configManager.getConfig('crowi', 'slackbot:currentBotType');
+
+    if (currentBotType == null) {
+      throw new Error('The config \'SLACK_BOT_TYPE\'(ns: \'crowi\', key: \'slackbot:currentBotType\') must be set.');
+    }
+
+    let token;
+
+    // connect directly
+    if (req.shareSearchResults == null) {
+      token = crowi.configManager.getConfig('crowi', 'slackbot:token');
+      req.client = generateWebClient(token);
+      return next();
+    }
+
+    // connect to proxy
+    const proxyServerUri = crowi.configManager.getConfig('crowi', 'slackbot:proxyServerUri');
+    const serverUri = urljoin(proxyServerUri, '/g2s');
+    const headers = {
+      'x-growi-gtop-tokens': req.shareSearchResults,
+    };
+
+    req.client = generateWebClient(token, serverUri, headers);
+    return next();
+  };
+
   async function handleCommands(req, res) {
-    const { body } = req;
+    const { client, body } = req;
 
     if (body.text == null) {
       return 'No text.';
@@ -65,13 +95,13 @@ module.exports = (crowi) => {
     try {
       switch (command) {
         case 'search':
-          await crowi.slackBotService.showEphemeralSearchResults(body, args);
+          await crowi.slackBotService.showEphemeralSearchResults(client, body, args);
           break;
         case 'create':
-          await crowi.slackBotService.createModal(body);
+          await crowi.slackBotService.createModal(client, body);
           break;
         default:
-          await crowi.slackBotService.notCommand(body);
+          await crowi.slackBotService.notCommand(client, body);
           break;
       }
     }
@@ -81,11 +111,11 @@ module.exports = (crowi) => {
     }
   }
 
-  router.post('/commands', addSigningSecretToReq, verifySlackRequest, async(req, res) => {
+  router.post('/commands', addSigningSecretToReq, verifySlackRequest, generateClientForResponse, async(req, res) => {
     return handleCommands(req, res);
   });
 
-  router.post('/proxied/commands', verifyAccessTokenFromProxy, async(req, res) => {
+  router.post('/proxied/commands', verifyAccessTokenFromProxy, generateClientForResponse, async(req, res) => {
     const { body } = req;
 
     // eslint-disable-next-line max-len
@@ -137,16 +167,17 @@ module.exports = (crowi) => {
     // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
     res.send();
 
+    const { client } = req;
     const payload = JSON.parse(req.body.payload);
     const { type } = payload;
 
     try {
       switch (type) {
         case 'block_actions':
-          await handleBlockActions(payload);
+          await handleBlockActions(client, payload);
           break;
         case 'view_submission':
-          await handleViewSubmission(payload);
+          await handleViewSubmission(client, payload);
           break;
         default:
           break;
@@ -159,11 +190,11 @@ module.exports = (crowi) => {
 
   }
 
-  router.post('/interactions', addSigningSecretToReq, verifySlackRequest, async(req, res) => {
+  router.post('/interactions', addSigningSecretToReq, verifySlackRequest, generateClientForResponse, async(req, res) => {
     return handleInteractions(req, res);
   });
 
-  router.post('/proxied/interactions', verifyAccessTokenFromProxy, async(req, res) => {
+  router.post('/proxied/interactions', verifyAccessTokenFromProxy, generateClientForResponse, async(req, res) => {
     return handleInteractions(req, res);
   });
 

+ 7 - 42
src/server/service/slackbot.js

@@ -1,9 +1,6 @@
-const urljoin = require('url-join');
 const logger = require('@alias/logger')('growi:service:SlackBotService');
 const mongoose = require('mongoose');
 
-const { generateWebClient } = require('@growi/slack');
-
 const PAGINGLIMIT = 10;
 
 const S2sMessage = require('../models/vo/s2s-message');
@@ -26,31 +23,6 @@ class SlackBotService extends S2sMessageHandlable {
     this.lastLoadedAt = new Date();
   }
 
-  async generateClient(body) {
-    const currentBotType = this.crowi.configManager.getConfig('crowi', 'slackbot:currentBotType');
-
-    if (currentBotType == null) {
-      throw new Error('The config \'SLACK_BOT_TYPE\'(ns: \'crowi\', key: \'slackbot:currentBotType\') must be set.');
-    }
-
-    let serverUri;
-    let token;
-
-    // connect directly
-    if (currentBotType === 'customBotWithoutProxy') {
-      token = this.crowi.configManager.getConfig('crowi', 'slackbot:token');
-      return generateWebClient(token, serverUri);
-    }
-
-    // connect to proxy
-    const proxyServerUri = this.crowi.configManager.getConfig('crowi', 'slackbot:proxyServerUri');
-    serverUri = urljoin(proxyServerUri, '/g2s');
-    const headers = {
-      'x-growi-gtop-tokens': body.tokenGtoP,
-    };
-    return generateWebClient(token, serverUri, headers);
-  }
-
   /**
    * @inheritdoc
    */
@@ -90,9 +62,8 @@ class SlackBotService extends S2sMessageHandlable {
     }
   }
 
-  async notCommand(body) {
+  async notCommand(client, body) {
     logger.error('Invalid first argument');
-    const client = await this.generateClient(body);
     client.chat.postEphemeral({
       channel: body.channel_id,
       user: body.user_id,
@@ -109,8 +80,7 @@ class SlackBotService extends S2sMessageHandlable {
     return keywords;
   }
 
-  async getSearchResultPaths(body, args, offset = 0) {
-    const client = this.generateClient(body);
+  async getSearchResultPaths(client, body, args, offset = 0) {
     const firstKeyword = args[1];
     if (firstKeyword == null) {
       client.chat.postEphemeral({
@@ -167,19 +137,17 @@ class SlackBotService extends S2sMessageHandlable {
     };
   }
 
-  async shareSearchResults(payload) {
-    const client = await this.generateClient();
+  async shareSearchResults(client, payload) {
     client.chat.postMessage({
       channel: payload.channel.id,
       text: payload.actions[0].value,
     });
   }
 
-  async showEphemeralSearchResults(body, args, offsetNum) {
+  async showEphemeralSearchResults(client, body, args, offsetNum) {
     const {
       resultPaths, offset, resultsTotal,
-    } = await this.getSearchResultPaths(body, args, offsetNum);
-    const client = await this.generateClient(body);
+    } = await this.getSearchResultPaths(client, body, args, offsetNum);
 
     const keywords = this.getKeywords(args);
 
@@ -267,9 +235,7 @@ class SlackBotService extends S2sMessageHandlable {
     }
   }
 
-  async createModal(body) {
-    const client = await this.generateClient(body);
-
+  async createModal(client, body) {
     try {
       await client.views.open({
         trigger_id: body.trigger_id,
@@ -311,12 +277,11 @@ class SlackBotService extends S2sMessageHandlable {
   }
 
   // Submit action in create Modal
-  async createPageInGrowi(payload) {
+  async createPageInGrowi(client, payload) {
     const Page = this.crowi.model('Page');
     const pathUtils = require('growi-commons').pathUtils;
 
     const contentsBody = payload.view.state.values.contents.contents_input.value;
-    const client = await this.generateClient();
 
     try {
       let path = payload.view.state.values.path.path_input.value;