AddAccount.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. const API = require("../../../lib/API.js");
  2. const db = require("../../../plugin/DataBase/db.js");
  3. const Redis = require("../../../plugin/DataBase/Redis.js");
  4. const { BaseStdResponse } = require("../../../BaseStdResponse.js");
  5. const AccessControl = require("../../../lib/AccessControl.js");
  6. const { insertBindAudit, BindAuditAction, BindAuditSource } = require("../../../lib/Lepao/BindAudit.js");
  7. const { fetchWebVpnCookieFromPy, invalidateWebVpnCookie } = require("../../../lib/Lepao/webvpnCookie");
  8. class AddAccount extends API {
  9. constructor() {
  10. super();
  11. this.setPath('/Lepao/Account')
  12. this.setMethod('POST')
  13. this.emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  14. this.banEmailList = ['icloud.com']
  15. this.autoUnbindDailyLimit = 10
  16. }
  17. // 生成 6 位数字 + 字母混合码
  18. async generateCode() {
  19. try {
  20. const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  21. let code = ""
  22. for (let i = 0; i < 6; i++) {
  23. code += chars.charAt(Math.floor(Math.random() * chars.length))
  24. }
  25. let sql = 'SELECT id FROM lepao_extra WHERE bind_code = ?'
  26. let rows = await db.query(sql, [code])
  27. if (!rows)
  28. throw new Error('数据库错误,请稍后再试')
  29. if (rows.length > 0)
  30. return await this.generateCode()
  31. return code
  32. } catch (error) {
  33. throw error
  34. }
  35. }
  36. getSemesterStartTimestamp() {
  37. const now = new Date()
  38. const year = now.getFullYear()
  39. const feb1ThisYear = new Date(year, 1, 1, 0, 0, 0, 0)
  40. const aug31ThisYear = new Date(year, 7, 31, 0, 0, 0, 0)
  41. if (now >= feb1ThisYear && now < aug31ThisYear) {
  42. return feb1ThisYear.getTime()
  43. }
  44. return new Date(now < feb1ThisYear ? year - 1 : year, 7, 31, 0, 0, 0, 0).getTime()
  45. }
  46. getAutoUnbindDailyRedisKey() {
  47. const now = new Date()
  48. const year = now.getFullYear()
  49. const month = `${now.getMonth() + 1}`.padStart(2, '0')
  50. const day = `${now.getDate()}`.padStart(2, '0')
  51. return `lepao:auto_unbind:daily:${year}${month}${day}`
  52. }
  53. getSecondsToDayEnd() {
  54. const now = new Date()
  55. const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 0, 0, 0, 0)
  56. return Math.max(1, Math.floor((tomorrow.getTime() - now.getTime()) / 1000))
  57. }
  58. async onRequest(req, res) {
  59. let { uuid, session, student_num, email, id, area, auto_time, auto_run, target_count, auto_day, notice_type, notes, jw_password } = req.body
  60. if ([uuid, session, student_num, auto_time, target_count, auto_day].some(value => value === '' || value === null || value === undefined))
  61. return res.json({
  62. ...BaseStdResponse.MISSING_PARAMETER
  63. })
  64. if (!id && [jw_password].some(value => value === '' || value === null || value === undefined))
  65. return res.json({
  66. ...BaseStdResponse.MISSING_PARAMETER,
  67. msg: '新绑定乐跑账号时必须提供教务系统密码(jw_password)'
  68. })
  69. if (isNaN(target_count) || target_count < 0 || target_count > 99) {
  70. return res.json({
  71. ...BaseStdResponse.ERR,
  72. msg: '乐跑目标次数不在合法范围内'
  73. })
  74. }
  75. if (notice_type === 'email') {
  76. if (!this.emailRegex.test(email)) {
  77. return res.json({
  78. ...BaseStdResponse.ERR,
  79. msg: '请检查邮箱格式是否正确'
  80. })
  81. }
  82. const emailDomain = email.split('@')[1].toLowerCase()
  83. if (this.banEmailList.includes(emailDomain))
  84. return res.json({
  85. ...BaseStdResponse.ERR,
  86. msg: `暂不支持使用 ${emailDomain} 域名的邮箱,请更换其他邮箱后重试`
  87. })
  88. }
  89. if (auto_run === 1 && (!Array.isArray(auto_day) || !auto_day.every(v => Number.isInteger(v) && v >= 0 && v <= 6)))
  90. return res.json({
  91. ...BaseStdResponse.ERR,
  92. msg: '自动乐跑日期格式不合法'
  93. })
  94. if (!await AccessControl.checkSession(uuid, session))
  95. return res.status(401).json({
  96. ...BaseStdResponse.ACCESS_DENIED
  97. })
  98. const jwLoginName = String(student_num).trim()
  99. let plainJwPassword = null
  100. if (jw_password != null && jw_password !== '') {
  101. try {
  102. plainJwPassword = atob(jw_password)
  103. } catch {
  104. return res.json({
  105. ...BaseStdResponse.ERR,
  106. msg: '教务密码格式错误'
  107. })
  108. }
  109. }
  110. if (plainJwPassword) {
  111. try {
  112. await fetchWebVpnCookieFromPy(jwLoginName, plainJwPassword)
  113. } catch (e) {
  114. return res.json({
  115. ...BaseStdResponse.ERR,
  116. msg: `教务账号或密码无法通过 WebVPN 校验:${e.message || '请核对后重试'}`
  117. })
  118. }
  119. try {
  120. await invalidateWebVpnCookie(uuid, jwLoginName)
  121. } catch (_) { /* ignore */ }
  122. }
  123. let countSql = 'SELECT id, create_user, total_num, auto_run, update_time FROM lepao_account WHERE student_num = ?'
  124. let countRows = await db.query(countSql, [student_num])
  125. if (!countRows)
  126. return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
  127. // 判断是否重复注册
  128. if (!id) {
  129. if (countRows.length !== 0 && countRows[0].create_user != null) {
  130. if (countRows[0].create_user !== uuid) {
  131. const semesterStartTimestamp = this.getSemesterStartTimestamp()
  132. const dailyAutoUnbindKey = this.getAutoUnbindDailyRedisKey()
  133. const dailyAutoUnbindCount = Number(await Redis.get(dailyAutoUnbindKey) || 0)
  134. const canAutoUnbindAndRebind = (countRows[0].auto_run === 0) &&
  135. (!countRows[0].update_time || countRows[0].update_time < semesterStartTimestamp) &&
  136. (dailyAutoUnbindCount < this.autoUnbindDailyLimit)
  137. if (!canAutoUnbindAndRebind)
  138. return res.json({ ...BaseStdResponse.ERR, msg: '该乐跑账号已被其他用户绑定,请联系客服处理' })
  139. } else {
  140. return res.json({ ...BaseStdResponse.ERR, msg: '该乐跑账号您已绑定' })
  141. }
  142. }
  143. }
  144. if (countRows.length !== 0) {
  145. if (auto_run === 1 && countRows[0].total_num >= target_count && target_count !== 0)
  146. return res.json({ ...BaseStdResponse.ERR, msg: '该账号累计跑步次数已达到预设目标次数,请尝试增大目标次数后再试' })
  147. }
  148. const time = new Date().getTime()
  149. if (plainJwPassword) {
  150. const jwExisting = await db.query(
  151. 'SELECT id FROM jw_account WHERE create_user = ? AND username = ?',
  152. [uuid, jwLoginName]
  153. )
  154. if (jwExisting && jwExisting.length > 0) {
  155. await db.query(
  156. 'UPDATE jw_account SET password = ?, update_time = ?, state = 0 WHERE id = ?',
  157. [plainJwPassword, time, jwExisting[0].id]
  158. )
  159. } else {
  160. await db.query(
  161. 'INSERT INTO jw_account (username, password, create_user, create_time) VALUES (?, ?, ?, ?)',
  162. [jwLoginName, plainJwPassword, uuid, time]
  163. )
  164. }
  165. }
  166. const previousOwner = countRows.length !== 0 ? countRows[0].create_user : null
  167. const shouldAutoUnbindAndRebind = !id &&
  168. countRows.length !== 0 &&
  169. previousOwner != null &&
  170. previousOwner !== uuid
  171. const shouldRecordBind = !id && previousOwner !== uuid
  172. let sql, r
  173. if (!id) {
  174. if (countRows.length !== 0) {
  175. sql = 'UPDATE lepao_account SET create_user = ?, email = ?, area = ?, auto_time = ?, auto_run = ?, target_count = ?, create_time = ?, update_time = ?, notes = ?, auto_day = ?, notice_type = ? WHERE id = ?'
  176. r = await db.query(sql, [uuid, email ?? '', area, auto_time, auto_run, target_count, time, time, notes ?? '', JSON.stringify(auto_day), notice_type, countRows[0].id])
  177. }
  178. else {
  179. const bind_code = await this.generateCode()
  180. sql = 'INSERT INTO lepao_account (student_num, email, area, auto_time, auto_run, target_count, create_user, create_time, notes, auto_day, notice_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
  181. r = await db.query(sql, [student_num, email ?? '', area, auto_time, auto_run, target_count, uuid, time, notes ?? '', JSON.stringify(auto_day), notice_type])
  182. let faceSql = 'INSERT INTO lepao_extra (student_num, bind_code) VALUES (?, ?)'
  183. let faceRows = await db.query(faceSql, [student_num, bind_code])
  184. if (!faceRows || faceRows.affectedRows !== 1)
  185. return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
  186. }
  187. } else {
  188. sql = 'UPDATE lepao_account SET student_num = ?, email = ?, area = ?, auto_time = ?, target_count = ?, auto_run = ?, notes = ?, auto_day = ?, update_time = ?, notice_type = ? WHERE id = ?'
  189. r = await db.query(sql, [student_num, email ?? '', area, auto_time, target_count, auto_run, notes ?? '', JSON.stringify(auto_day), time, notice_type, id])
  190. }
  191. try {
  192. if (r && r.affectedRows > 0) {
  193. const selectSql = `
  194. SELECT
  195. a.id, a.create_user, a.total_num, e.bind_code, e.bot_account
  196. FROM
  197. lepao_account a
  198. LEFT JOIN
  199. lepao_extra e
  200. ON
  201. a.student_num = e.student_num
  202. WHERE
  203. a.student_num = ?
  204. `
  205. const selectRows = await db.query(selectSql, [student_num])
  206. if (!selectRows)
  207. return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
  208. res.json({
  209. ...BaseStdResponse.OK,
  210. id: r.insertId,
  211. data: {
  212. student_num, email, id, area, auto_time, auto_run, target_count, auto_day, notice_type, notes,
  213. bind_code: selectRows.length !== 0 ? selectRows[0].bind_code : undefined,
  214. bot_account: selectRows.length !== 0 ? selectRows[0].bot_account : undefined
  215. }
  216. })
  217. if (shouldRecordBind) {
  218. if (shouldAutoUnbindAndRebind) {
  219. const unbindAuditOk = await insertBindAudit({
  220. studentNum: student_num,
  221. ownerUuid: previousOwner,
  222. action: BindAuditAction.PLATFORM_UNBIND,
  223. source: BindAuditSource.USER_API,
  224. operatorUuid: uuid,
  225. detail: { via: 'AddAccount:auto_unbind_rebind' },
  226. createdAt: time
  227. })
  228. if (!unbindAuditOk) {
  229. this.logger.warn(`自动解绑审计写入失败 student_num=${student_num}`)
  230. } else {
  231. const dailyAutoUnbindKey = this.getAutoUnbindDailyRedisKey()
  232. const latestAutoUnbindCount = await Redis.incr(dailyAutoUnbindKey)
  233. if (latestAutoUnbindCount === 1) {
  234. await Redis.expire(dailyAutoUnbindKey, this.getSecondsToDayEnd())
  235. }
  236. }
  237. }
  238. const auditOk = await insertBindAudit({
  239. studentNum: student_num,
  240. ownerUuid: uuid,
  241. action: BindAuditAction.PLATFORM_BIND,
  242. source: BindAuditSource.USER_API,
  243. operatorUuid: uuid,
  244. detail: { via: 'AddAccount' },
  245. createdAt: time
  246. })
  247. if (!auditOk) {
  248. this.logger.warn(`绑定审计写入失败 student_num=${student_num}`)
  249. }
  250. }
  251. } else {
  252. return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
  253. }
  254. } catch (err) {
  255. this.logger.error(`添加乐跑账号失败!${err.stack}`)
  256. res.json({
  257. ...BaseStdResponse.ERR,
  258. msg: "添加乐跑账号失败!",
  259. });
  260. }
  261. }
  262. }
  263. module.exports.AddAccount = AddAccount;