From 7cabb1ee45f954604652ffb6fc741eabe79bf0ae Mon Sep 17 00:00:00 2001 From: fengkx Date: Fri, 20 Mar 2020 12:16:00 +0800 Subject: [PATCH] fix: url contain - treat as channel id --- .prettierignore | 1 + middlewares/is-admin.js | 15 ++++++++++++++- test/is-admin.test.js | 12 ++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/.prettierignore b/.prettierignore index 7dc06dc4931..91d82bfb071 100644 --- a/.prettierignore +++ b/.prettierignore @@ -2,3 +2,4 @@ package.json package-lock.json node_modules logs +coverage diff --git a/middlewares/is-admin.js b/middlewares/is-admin.js index 3e02aceea65..d6eef50f9fd 100644 --- a/middlewares/is-admin.js +++ b/middlewares/is-admin.js @@ -2,6 +2,19 @@ const errors = require('../utils/errors'); const USERS = require('../proxies/users'); const config = require('../config'); +/** + * Check if using for channel + * @param {string} text message recived + * @return {boolean} whether contain channel id (can be start with @ or a number start with -) + */ +function checkChannelId(text) { + const textPart = text.split(/\s+/); + if (textPart.length > 1 && textPart[1].match(/^(@\w+)|(-\d+)$/)) { + return true; + } + return false; +} + module.exports = async (ctx, next) => { ctx.state.chat = await ctx.getChat(); const chat = ctx.state.chat; @@ -32,7 +45,7 @@ module.exports = async (ctx, next) => { } else if ( ctx.message && // button respone without message ctx.message.text && - ctx.message.text.search(/(@\w+)|(-\d+)/) !== -1 + checkChannelId(ctx.message.text) ) { // for channel subscription in private chat const channelId = ctx.message.text.match(/(@\w+)|(-\d+)/)[0]; diff --git a/test/is-admin.test.js b/test/is-admin.test.js index 303e9a6163c..7d992e0fad4 100644 --- a/test/is-admin.test.js +++ b/test/is-admin.test.js @@ -19,6 +19,7 @@ test('sub channel with @', async () => { const ctx = pass('/sub @testChannel http://test.test', 666); await isAdmin(ctx, () => {}); expect(ctx).toHaveProperty('state.chat.id', channelId); + expect(ctx.message.text).not.toMatch(/@\w+/); }); test('sub channel without @', async () => { @@ -26,6 +27,7 @@ test('sub channel without @', async () => { const ctx = pass('/sub -123456 http://test.test', channelId); await isAdmin(ctx, () => {}); expect(ctx).toHaveProperty('state.chat.id', channelId); + expect(ctx.message.text).not.toMatch(/-\d+/); }); test('bot no admin in channel', async () => { @@ -33,3 +35,13 @@ test('bot no admin in channel', async () => { const ctx = noAdmin('/sub -123456 http://test.test', channelId); await expect(isAdmin(ctx, () => {})).rejects.toThrow(ErrClass); }); + +test('url contain -', async () => { + const channelId = 666; + const ctx = pass( + '/sub http://ip-243-184bpo123.com/kuaidi100/141abc', + channelId + ); + await isAdmin(ctx, () => {}); + expect(ctx).toHaveProperty('state.chat.id', 233233233); +});