router.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. const express = require('express')
  2. const { updateGPTConfig } = require('./API/ChatGPT')
  3. const { updateXunfeiConfig } = require('./API/xunfei')
  4. const { updateTYConfig } = require('./API/tongyi')
  5. const { sendMessageToAPI } = require('./wechat/main')
  6. const sqlite3 = require('sqlite3')
  7. const jsonwebtoken = require('jsonwebtoken')
  8. const bcryptjs = require('bcryptjs')
  9. const path = require('path')
  10. const secretKey = 'co666'
  11. const {
  12. wxlogin,
  13. Status,
  14. User,
  15. setWx,
  16. stopWx,
  17. loadConfigValues
  18. } = require('./wechat/main')
  19. //打开数据库
  20. var db = new sqlite3.Database("./db/data.db")
  21. const router = express.Router()
  22. router.use(express.static('./public'))
  23. // 定义中间件.unless指定哪些接口不需要进行token身份认证
  24. const { expressjwt: jwt } = require("express-jwt")
  25. const checkTokenMiddleware = jwt({ secret: secretKey, algorithms: ["HS256"] }).unless({
  26. path: [/^\/userlogin/, /^\/register/, /^\/getavatar/],
  27. })
  28. // 验证token
  29. const errorcheckToken = (err, req, res, next) => {
  30. if (err.name === 'UnauthorizedError') {
  31. return res.send({ status: 401, msg: '请先登录' })
  32. }
  33. res.send({ status: 500, msg: '未知错误' })
  34. }
  35. // 封装验证Token和错误处理的函数
  36. const checkToken = (req, res, next) => {
  37. checkTokenMiddleware(req, res, (err) => {
  38. if (err) {
  39. errorcheckToken(err, req, res, next)
  40. } else {
  41. next()
  42. }
  43. })
  44. }
  45. router.use(checkToken)
  46. //用户登录
  47. router.post('/userlogin', (req, res) => {
  48. const username = req.body.username
  49. const password = req.body.password
  50. const remember = req.body.remember
  51. // 匹配密码
  52. db.all('select * from user where username=?', username, function (err, row) {
  53. if (err) res.send({ status: 500, msg: "数据库查询失败" })
  54. else {
  55. if (row == "") {
  56. res.send({ status: 500, msg: "此用户不存在" })
  57. } else {
  58. const compareResult = bcryptjs.compareSync(password, row[0].password)
  59. if (!compareResult) {
  60. res.send({ status: 500, msg: "密码错误" })
  61. } else {
  62. // 如果用户名存在且密码匹配,则登录成功。
  63. if(remember) {
  64. const tokenStr = jsonwebtoken.sign({ username: username }, secretKey)
  65. res.send({ status: 200, msg: "登录成功", token: "Bearer " + tokenStr })
  66. } else{
  67. const tokenStr = jsonwebtoken.sign({ username: username }, secretKey, { expiresIn: '24h' })
  68. res.send({ status: 200, msg: "登录成功", token: "Bearer " + tokenStr })
  69. }
  70. }
  71. }
  72. }
  73. })
  74. })
  75. function findusername(req, res, next) {
  76. // 从请求头中获取 Token
  77. const token = req.headers['authorization']
  78. jsonwebtoken.verify(token.split(' ')[1], secretKey, (err, decoded) => {
  79. if (err) {
  80. return res.send({ status: 401, msg: 'Token无效' })
  81. } else {
  82. req.username = decoded.username
  83. next()
  84. }
  85. })
  86. }
  87. router.post('/getusername', findusername,(req,res) => {
  88. const username = req.username
  89. res.send({status: 200,msg:username})
  90. })
  91. router.post('/changeaccount', findusername, (req, res) => {
  92. const username = req.username;
  93. const oldpassword = req.body.oldpassword;
  94. const newusername = req.body.newusername;
  95. const newpassword = req.body.newpassword;
  96. // 查询用户是否存在以及旧密码是否正确
  97. db.get('SELECT * FROM user WHERE username=?', [username], (err, row) => {
  98. if (err) {
  99. res.send({ status: 500, msg: "数据库查询失败" })
  100. } else {
  101. if (!row) {
  102. res.send({ status: 500, msg: "用户名或密码错误" })
  103. } else {
  104. // 比对旧密码
  105. const compareResult = bcryptjs.compareSync(oldpassword, row.password)
  106. if (!compareResult) {
  107. res.send({ status: 500, msg: "用户名或密码错误" })
  108. } else {
  109. if (newusername.length < 5) {
  110. res.send({ status: 500, msg: "用户名不能小于5位" })
  111. } else if (newpassword.length < 6) {
  112. res.send({ status: 500, msg: "密码不能小于6位" })
  113. } else {
  114. // 更新用户名和密码
  115. db.run('UPDATE user SET username=?, password=? WHERE username=?', [newusername, bcryptjs.hashSync(newpassword, 10), username], (err) => {
  116. if (err) {
  117. res.send({ status: 500, msg: "更新账户信息失败" })
  118. } else {
  119. res.send({ status: 200, msg: "账户信息更新成功" })
  120. }
  121. })
  122. }
  123. }
  124. }
  125. }
  126. })
  127. })
  128. //获取二维码 启动bot
  129. router.get('/getqrcode',async(req,res) => {
  130. wxlogin()
  131. .then(qrcodeUrl =>{
  132. res.send({ qrcode: qrcodeUrl })
  133. })
  134. })
  135. // 发送头像图片文件
  136. router.get('/getavatar',async(req,res) => {
  137. try {
  138. const avatarFilePath = path.join(__dirname,'./wechat/avatar/avatar.jpg')
  139. res.sendFile(avatarFilePath)
  140. } catch(error) {
  141. res.send({status:500,msg:'获取头像失败!' + error.message})
  142. }
  143. })
  144. router.get('/getwxname', async (req, res) => {
  145. res.send({ wxname: User.name })
  146. })
  147. //获取二维码状态
  148. router.get('/getstatus',async(req,res) => {
  149. res.send({status:Status.status})
  150. })
  151. router.post('/chat',async(req,res) => {
  152. try{
  153. const response = await sendMessageToAPI(req.body.msg)
  154. res.send({status:200,msg:response})
  155. } catch(err) {
  156. res.send({status:500,msg:'获取消息失败!'+ err.message})
  157. }
  158. })
  159. // 停止机器人
  160. router.get('/stop', async (req, res) => {
  161. try {
  162. stopWx()
  163. res.send({ Status: 200, msg: '停止机器人成功' })
  164. } catch (error) {
  165. res.send({ Status: 500, msg: '停止机器人失败' + error })
  166. }
  167. })
  168. router.post('/getgptconfig', async (req, res) => {
  169. db.all('SELECT * FROM gptconfig', [], (err, rows) => {
  170. if (err) {
  171. res.send({ status: 500, msg: '查询失败!' })
  172. return
  173. }
  174. res.send({ status: 200, msg: rows })
  175. })
  176. })
  177. router.post('/getxfconfig', async (req, res) => {
  178. db.all('SELECT * FROM xfconfig', [], (err, rows) => {
  179. if (err) {
  180. res.send({ status: 500, msg: '查询失败!' })
  181. return
  182. }
  183. res.send({ status: 200, msg: rows })
  184. })
  185. })
  186. router.post('/gettyconfig', async (req, res) => {
  187. db.all('SELECT * FROM tongyiconfig', [], (err, rows) => {
  188. if (err) {
  189. res.send({ status: 500, msg: '查询失败!' })
  190. return
  191. }
  192. res.send({ status: 200, msg: rows })
  193. })
  194. })
  195. router.post('/gptconfig',async(req,res) => {
  196. const { apiKey, apiUrl, app_code, model, temperature,max_tokens,presets } = req.body
  197. try {
  198. updateGPTConfig("apiKey", apiKey)
  199. updateGPTConfig("apiUrl", apiUrl)
  200. updateGPTConfig("app_code", app_code)
  201. updateGPTConfig("model",model)
  202. updateXunfeiConfig("temperature", temperature)
  203. updateXunfeiConfig("max_tokens", max_tokens)
  204. updateGPTConfig("presets",presets)
  205. res.send({status: 200,msg: '设置成功!'})
  206. } catch (error) {
  207. res.send({status: 500, msg: '设置失败!'})
  208. }
  209. })
  210. router.post('/xfconfig', async (req, res) => {
  211. const { temperature, max_tokens, app_id, APIKey, APISecret, APIUrl, domain } = req.body
  212. try {
  213. updateXunfeiConfig("temperature", temperature)
  214. updateXunfeiConfig("max_tokens", max_tokens)
  215. updateXunfeiConfig("app_id", app_id)
  216. updateXunfeiConfig("APIKey", APIKey)
  217. updateXunfeiConfig("APISecret", APISecret)
  218. updateXunfeiConfig("APIUrl", APIUrl)
  219. updateXunfeiConfig("domain", domain)
  220. res.send({ status: 200, msg: '设置成功!' })
  221. } catch (error) {
  222. res.send({ status: 500, msg: '设置失败!' })
  223. }
  224. })
  225. router.post('/tyconfig', async (req, res) => {
  226. const { temperature, max_tokens, model, apiKey, presets, apiUrl } = req.body
  227. try {
  228. updateTYConfig("temperature", temperature)
  229. updateTYConfig("max_tokens", max_tokens)
  230. updateTYConfig("presets", presets)
  231. updateTYConfig("apiKey", apiKey)
  232. updateTYConfig("model", model)
  233. updateTYConfig("apiUrl", apiUrl)
  234. res.send({ status: 200, msg: '设置成功!' })
  235. } catch (error) {
  236. res.send({ status: 500, msg: '设置失败!' })
  237. }
  238. })
  239. //获取机器人设置
  240. router.post('/getwxconfig', async (req, res) => {
  241. db.all('SELECT * FROM wxconfig', [], (err, rows) => {
  242. if (err) {
  243. res.send({ status: 500, msg: '查询失败!' })
  244. return
  245. }
  246. res.send({ status: 200, msg: rows })
  247. })
  248. })
  249. //设置微信机器人
  250. router.post('/wxconfig', async (req, res) => {
  251. const { autoReplySingle, suffix, prefix, atReply, keyWords, blackName, whiteRoom ,usemodel} = req.body
  252. try {
  253. setWx('autoReplySingle', autoReplySingle)
  254. setWx('suffix', suffix)
  255. setWx('prefix', prefix)
  256. setWx('whiteRoom', whiteRoom)
  257. setWx('atReply', atReply)
  258. setWx('keyWords', keyWords)
  259. setWx('blackName', blackName)
  260. setWx('usemodel', usemodel)
  261. loadConfigValues()
  262. res.send({ status: 200, msg: '设置成功!' })
  263. } catch (error) {
  264. res.send({ status: 500, msg: '设置失败!' })
  265. }
  266. })
  267. //获取消息发送记录
  268. router.post('/messagehistory',async (req,res)=>{
  269. db.all('SELECT * FROM message', [], (err, rows) => {
  270. if (err) {
  271. res.send({ status: 500, msg: '查询失败!' })
  272. return
  273. }
  274. res.send({ status: 200, msg: rows })
  275. })
  276. })
  277. //清空消息发送记录
  278. router.post('/clearmessage',async(req,res) => {
  279. db.run('DELETE FROM message', (err) => {
  280. if (err) {
  281. res.send({ status: 500, msg: '删除失败!' })
  282. } else {
  283. res.send({ status: 200, msg: '删除成功!' })
  284. }
  285. })
  286. })
  287. module.exports = router