Skip to content
This repository was archived by the owner on Jan 10, 2025. It is now read-only.

Commit

Permalink
feat: 🎸 增加checklogin api接口和token生成机制
Browse files Browse the repository at this point in the history
  • Loading branch information
chentianyu committed Oct 7, 2023
1 parent d8d8237 commit 1b64d1e
Show file tree
Hide file tree
Showing 9 changed files with 102 additions and 16 deletions.
5 changes: 4 additions & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
PORT=3001
# 如果想自己处理收到消息的逻辑,在下面填上你的API地址, 默认为空
LOCAL_RECVD_MSG_API=
LOCAL_RECVD_MSG_API=
# 登录地址Token访问地址: http://localhost:3001/loginCheck?token=[LOCAL_LOGIN_API_TOKEN]
# 生成规则:src/utils/index.js
LOCAL_LOGIN_API_TOKEN=
2 changes: 1 addition & 1 deletion main.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ app.use(express.json());
registerRoute({app, bot})

app.listen(PORT, () => {
console.log(`service is running on ${chalk.cyan('http://localhost:'+ PORT)}\n`);
console.log(`service is running, Port is ${PORT}`);
});
4 changes: 4 additions & 0 deletions scripts/shellToken.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// 给 shell 调用使用
const { generateToken } = require('../src/utils/index')

console.log(generateToken());
2 changes: 2 additions & 0 deletions src/route/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// 此处批量管理注册的webhook
const registerMsgPusherRouter = require('./msg')
const registerLoginCheck = require('./loginCheck')

module.exports = function registerRoute({app, bot}) {
registerMsgPusherRouter({app, bot})
registerLoginCheck({app, bot})
}
44 changes: 44 additions & 0 deletions src/route/loginCheck.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// 登录
module.exports = function registerLoginCheck({ app, bot }) {
let message,
success = false

bot
.on('scan', qrcode => {
message = 'https://wechaty.js.org/qrcode/' + encodeURIComponent(qrcode)
success = false
})
.on('login', user => {
message = user + 'is already login'
success = true
})
.on('logout', user => {
message = ''
success = false
})

// 处理 POST 请求
app.get('/loginCheck', async (req, res) => {

// getLoginApiToken
const { token } = req.query

if (token !== process.env.globalLoginToken) {
return res.status(401).json({
success: false,
message: 'Unauthorized: Access is denied due to invalid credentials.'
});
}

try {
res.status(200).json({
success,
message
})

} catch (error) {
console.error('Error handling POST request:', error);
res.status(500).json({ success: false, message: 'Internal server error.' });
}
});
}
6 changes: 3 additions & 3 deletions src/route/msg.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ module.exports = function registerPushHook({ app, bot }) {
return res.status(200).json({ success: false, message: `[${unValidParamsStr}] params is not valid, please checkout the api reference (https://github.com/danni-cool/docker-wechat-roomBot#body-%E5%8F%82%E6%95%B0%E8%AF%B4%E6%98%8E)` });
}

const targetMsgReceiver = isRoom ?
const msgReceiver = isRoom ?
await bot.Room.find({ topic: to }) :
await bot.Contact.find({ name: to })

if (targetMsgReceiver) {
const sendStatus = await formatAndSendMsg({ type, content, msgInstance: targetMsgReceiver, res })
if (msgReceiver) {
const sendStatus = await formatAndSendMsg({ type, content, msgInstance: msgReceiver, res })
res.status(200).json({ success: sendStatus, message: `Message sent ${sendStatus ? 'successfully' : 'failed'}.` });
} else {
res.status(200).json({ success: false, message: `${isRoom ? 'Room' : 'User'} is not found` });
Expand Down
25 changes: 21 additions & 4 deletions src/service/webhook.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
const fetch = require('node-fetch-commonjs')
const FormData = require('form-data')
const chalk = require('chalk')
const { LOCAL_RECVD_MSG_API, RECVD_MSG_API } = process.env
const { generateToken } = require('../utils/index')
const {
LOCAL_RECVD_MSG_API,
RECVD_MSG_API,
LOGIN_API_TOKEN,
LOCAL_LOGIN_API_TOKEN
} = process.env

const sendMsg2RecvdAPI = async function (msg, webhookUrl) {
const sendMsg2RecvdApi = async function (msg, webhookUrl) {
const source = {
room: msg.room() || '',
to: msg.to() || '',
Expand Down Expand Up @@ -69,8 +75,19 @@ const getValidRecvdApi = () => {
return webhookUrl
}

//得到 loginAPIToken
const getLoginApiToken = () => {
if(!process.env.globalLoginToken) {
process.env.globalLoginToken = LOGIN_API_TOKEN || LOCAL_LOGIN_API_TOKEN || generateToken()
}

return process.env.globalLoginToken
}



module.exports = {
sendMsg2RecvdAPI,
getValidRecvdApi
sendMsg2RecvdApi,
getValidRecvdApi,
getLoginApiToken
}
14 changes: 13 additions & 1 deletion src/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,21 @@ const getUnvalidParamsList = arr => {
.filter(({ unValidReason }) => unValidReason)
}

const generateToken =(num=12) => {
const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~';
let token = '';
for (let i = 0; i < 16; i++) {
const randomIndex = Math.floor(Math.random() * charset.length);
token += charset[randomIndex];
}

return token
}

module.exports = {
getFileNameFromUrl,
getMediaFromUrl,
getUnvalidParamsList
getUnvalidParamsList,
generateToken
}

16 changes: 10 additions & 6 deletions src/wechaty/init.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,28 @@
const { WechatyBuilder } = require('wechaty')
const { sendMsg2RecvdAPI, getValidRecvdApi } = require('../service/webhook')
const { sendMsg2RecvdApi, getValidRecvdApi, getLoginApiToken } = require('../service/webhook')
const bot = WechatyBuilder.build() // get a Wechaty instance
const chalk = require('chalk')
const { PORT } = process.env

module.exports = function init() {
const webhookUrl = getValidRecvdApi()

// 启动 Wechaty 机器人
bot
.on('scan', (qrcode) => console.log(`\n以下链接浏览器打开wx扫码登录: ${chalk.cyan('https://wechaty.js.org/qrcode/' + encodeURIComponent(qrcode))}`))
.on('login', async user => {
console.log(`User ${user} logged in`)
})
.on('scan', (qrcode) =>
console.log([
`\nAccess the URL to login: ${chalk.cyan('https://wechaty.js.org/qrcode/' + encodeURIComponent(qrcode))}`,
'You can also check login by API: '+ chalk.cyan(`http://localhost:${PORT}/loginCheck?token=${getLoginApiToken()}`)
].join('\n')))
.on('login', async user => console.log(chalk.green(`User ${user} logged in`)))
.on('logout', async user => console.log(chalk.red(`User ${user} logout`)))
// .on('room-topic', async (room, topic, oldTopic, changer) => {
// console.log(`Room ${await room.topic()} topic changed from ${oldTopic} to ${topic} by ${changer.name()}`)
// })
.on('message', async message => {
console.log(`Message: ${message}`)
//收到消息二次转发特殊处理
webhookUrl && await sendMsg2RecvdAPI(message, webhookUrl)
webhookUrl && await sendMsg2RecvdApi(message, webhookUrl)

})
.on('error', (error) => {
Expand Down

0 comments on commit 1b64d1e

Please sign in to comment.