Browse Source

Merge pull request #3745 from weseek/feat/5840-5847-implement-test

implement route at proxy
itizawa 4 years ago
parent
commit
a0ffaf6495

+ 10 - 0
packages/slack/src/utils/check-communicable.ts

@@ -89,3 +89,13 @@ export const getConnectionStatuses = async(tokens: string[]): Promise<{[key: str
   // convert to object
   // convert to object
   return Object.fromEntries(await map);
   return Object.fromEntries(await map);
 };
 };
+
+/**
+ * @param token bot OAuth token
+ * @returns
+ */
+export const relationTestToSlack = async(token:string): Promise<void> => {
+  const client = generateWebClient(token);
+  // TODO GW-6002 fire chat.postMessage
+  await testSlackApiServer(client);
+};

+ 68 - 1
packages/slackbot-proxy/src/controllers/growi-to-slack.ts

@@ -4,14 +4,19 @@ import {
 
 
 import { WebAPICallResult } from '@slack/web-api';
 import { WebAPICallResult } from '@slack/web-api';
 
 
-import { verifyGrowiToSlackRequest, getConnectionStatuses } from '@growi/slack';
+import { verifyGrowiToSlackRequest, getConnectionStatuses, relationTestToSlack } from '@growi/slack';
 
 
 import { GrowiReq } from '~/interfaces/growi-to-slack/growi-req';
 import { GrowiReq } from '~/interfaces/growi-to-slack/growi-req';
 import { InstallationRepository } from '~/repositories/installation';
 import { InstallationRepository } from '~/repositories/installation';
 import { RelationRepository } from '~/repositories/relation';
 import { RelationRepository } from '~/repositories/relation';
+import { OrderRepository } from '~/repositories/order';
+
 import { InstallerService } from '~/services/InstallerService';
 import { InstallerService } from '~/services/InstallerService';
 import loggerFactory from '~/utils/logger';
 import loggerFactory from '~/utils/logger';
 
 
+import { Relation } from '~/entities/relation';
+import { Order } from '~/entities/order';
+
 
 
 const logger = loggerFactory('slackbot-proxy:controllers:growi-to-slack');
 const logger = loggerFactory('slackbot-proxy:controllers:growi-to-slack');
 
 
@@ -28,6 +33,9 @@ export class GrowiToSlackCtrl {
   @Inject()
   @Inject()
   relationRepository: RelationRepository;
   relationRepository: RelationRepository;
 
 
+  @Inject()
+  orderRepository: OrderRepository;
+
   @Get('/connection-status')
   @Get('/connection-status')
   @UseBefore(verifyGrowiToSlackRequest)
   @UseBefore(verifyGrowiToSlackRequest)
   async getConnectionStatuses(@Req() req: GrowiReq, @Res() res: Res): Promise<void|string|Res|WebAPICallResult> {
   async getConnectionStatuses(@Req() req: GrowiReq, @Res() res: Res): Promise<void|string|Res|WebAPICallResult> {
@@ -52,4 +60,63 @@ export class GrowiToSlackCtrl {
     return res.send({ connectionStatuses });
     return res.send({ connectionStatuses });
   }
   }
 
 
+  @Get('/relation-test')
+  @UseBefore(verifyGrowiToSlackRequest)
+  async postRelation(@Req() req: GrowiReq, @Res() res: Res): Promise<void|string|Res|WebAPICallResult> {
+    const { tokenGtoPs } = req;
+
+    if (tokenGtoPs.length !== 1) {
+      return res.status(400).send({ message: 'installation is invalid' });
+    }
+
+    const tokenGtoP = tokenGtoPs[0];
+
+    // retrieve relation with Installation
+    const relation = await this.relationRepository.createQueryBuilder('relation')
+      .where('tokenGtoP = :token', { token: tokenGtoP })
+      .leftJoinAndSelect('relation.installation', 'installation')
+      .getOne();
+
+    // Returns the result of the test if it already exists
+    if (relation != null) {
+      logger.debug('relation found', relation);
+
+      const token = relation.installation.data.bot?.token;
+      if (token == null) {
+        return res.status(400).send({ message: 'installation is invalid' });
+      }
+
+      await relationTestToSlack(token);
+      return res.send({ relation });
+    }
+
+    // retrieve latest Order with Installation
+    const order = await this.orderRepository.createQueryBuilder('order')
+      .orderBy('order.createdAt', 'DESC')
+      .where('growiAccessToken = :token', { token: tokenGtoP })
+      .leftJoinAndSelect('order.installation', 'installation')
+      .getOne();
+
+    if (order == null || order.isExpired()) {
+      return res.status(400).send({ message: 'order has expired or does not exist.' });
+    }
+
+    logger.debug('order found', order);
+
+    const token = order.installation.data.bot?.token;
+    if (token == null) {
+      return res.status(400).send({ message: 'installation is invalid' });
+    }
+
+    await relationTestToSlack(token);
+
+    logger.debug('relation test is success', order);
+
+    // TODO GW-5864 issue relation
+
+    // return order temporary
+    // TODO return new relation
+    return res.send({ order });
+  }
+
 }
 }

+ 1 - 1
packages/slackbot-proxy/src/entities/order.ts

@@ -16,7 +16,7 @@ export class Order {
   readonly updatedAt: Date;
   readonly updatedAt: Date;
 
 
   @ManyToOne(() => Installation)
   @ManyToOne(() => Installation)
-  readonly installation: number;
+  readonly installation: Installation;
 
 
   @Column({ nullable: true, default: false })
   @Column({ nullable: true, default: false })
   isCompleted?: boolean;
   isCompleted?: boolean;

+ 3 - 3
packages/slackbot-proxy/src/services/RegisterService.ts

@@ -66,16 +66,16 @@ export class RegisterService implements GrowiCommandProcessor {
     const inputGrowiAccessToken = inputValues.growiAccessToken.contents_input.value;
     const inputGrowiAccessToken = inputValues.growiAccessToken.contents_input.value;
     const inputProxyAccessToken = inputValues.proxyToken.contents_input.value;
     const inputProxyAccessToken = inputValues.proxyToken.contents_input.value;
 
 
-    const order = await orderRepository.findOne({ installation: installation?.id, growiUrl: inputGrowiUrl });
+    const order = await orderRepository.findOne({ installation, growiUrl: inputGrowiUrl });
     if (order != null) {
     if (order != null) {
       orderRepository.update(
       orderRepository.update(
-        { installation: installation?.id, growiUrl: inputGrowiUrl },
+        { installation, growiUrl: inputGrowiUrl },
         { growiAccessToken: inputGrowiAccessToken, proxyAccessToken: inputProxyAccessToken },
         { growiAccessToken: inputGrowiAccessToken, proxyAccessToken: inputProxyAccessToken },
       );
       );
     }
     }
     else {
     else {
       orderRepository.save({
       orderRepository.save({
-        installation: installation?.id, growiUrl: inputGrowiUrl, growiAccessToken: inputGrowiAccessToken, proxyAccessToken: inputProxyAccessToken,
+        installation, growiUrl: inputGrowiUrl, growiAccessToken: inputGrowiAccessToken, proxyAccessToken: inputProxyAccessToken,
       });
       });
     }
     }
   }
   }

+ 61 - 0
src/server/routes/apiv3/slack-integration-settings.js

@@ -67,6 +67,9 @@ module.exports = (crowi) => {
         .isString()
         .isString()
         .isLength({ min: 1 }),
         .isLength({ min: 1 }),
     ],
     ],
+    RelationTest: [
+      body('slackappintegrationsId').isMongoId(),
+    ],
   };
   };
 
 
   async function resetAllBotSettings() {
   async function resetAllBotSettings() {
@@ -99,6 +102,18 @@ module.exports = (crowi) => {
     return result.data;
     return result.data;
   }
   }
 
 
+  async function postRelationTest(token) {
+    const proxyUri = crowi.configManager.getConfig('crowi', 'slackbot:serverUri');
+
+    const result = await axios.get(urljoin(proxyUri, '/g2s/relation-test'), {
+      headers: {
+        'x-growi-gtop-tokens': token,
+      },
+    });
+
+    return result.data;
+  }
+
   /**
   /**
    * @swagger
    * @swagger
    *
    *
@@ -417,5 +432,51 @@ module.exports = (crowi) => {
 
 
   });
   });
 
 
+  /**
+   * @swagger
+   *
+   *    /slack-integration-settings/with-proxy/relation-test:
+   *      post:
+   *        tags: [botType]
+   *        operationId: postRelationTest
+   *        summary: /slack-integration/bot-type
+   *        description: Delete botType setting.
+   *        requestBody:
+   *          content:
+   *            application/json:
+   *              schema:
+   *                properties:
+   *                  slackappintegrationsId:
+   *                    type: string
+   *        responses:
+   *           200:
+   *             description: Succeeded to delete botType setting.
+   */
+  router.post('/with-proxy/relation-test', loginRequiredStrictly, adminRequired, csrf, validator.RelationTest, apiV3FormValidator, async(req, res) => {
+    const currentBotType = crowi.configManager.getConfig('crowi', 'slackbot:currentBotType');
+    if (currentBotType === 'customBotWithoutProxy') {
+      const msg = 'Not Proxy Type';
+      return res.apiv3Err(new ErrorV3(msg, 'not-proxy-type'), 400);
+    }
+
+    const { slackappintegrationsId } = req.body;
+
+    try {
+      const slackAppIntegration = await SlackAppIntegration.findOne({ _id: slackappintegrationsId });
+      if (slackAppIntegration == null) {
+        const msg = 'Could not find SlackAppIntegration by id';
+        return res.apiv3Err(new ErrorV3(msg, 'find-slackAppIntegration-failed'), 400);
+      }
+      const response = await postRelationTest(slackAppIntegration.tokenGtoP);
+
+      return res.apiv3({ response });
+    }
+    catch (error) {
+      const msg = 'Error occured in updating Custom bot setting';
+      logger.error('Error', error);
+      return res.apiv3Err(new ErrorV3(msg, 'update-CustomBotSetting-failed'), 500);
+    }
+  });
+
   return router;
   return router;
 };
 };