AddAccount.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. class AddAccount extends API {
  8. constructor() {
  9. super();
  10. this.setPath('/Lepao/Account')
  11. this.setMethod('POST')
  12. this.emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  13. this.banEmailList = ['icloud.com']
  14. this.autoUnbindDailyLimit = 100
  15. }
  16. // 生成 6 位数字 + 字母混合码
  17. async generateCode() {
  18. try {
  19. const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  20. let code = ""
  21. for (let i = 0; i < 6; i++) {
  22. code += chars.charAt(Math.floor(Math.random() * chars.length))
  23. }
  24. let sql = 'SELECT id FROM lepao_extra WHERE bind_code = ?'
  25. let rows = await db.query(sql, [code])
  26. if (!rows)
  27. throw new Error('数据库错误,请稍后再试')
  28. if (rows.length > 0)
  29. return await this.generateCode()
  30. return code
  31. } catch (error) {
  32. throw error
  33. }
  34. }
  35. getSemesterStartTimestamp() {
  36. const now = new Date()
  37. const year = now.getFullYear()
  38. const feb1ThisYear = new Date(year, 1, 1, 0, 0, 0, 0)
  39. const aug31ThisYear = new Date(year, 7, 31, 0, 0, 0, 0)
  40. if (now >= feb1ThisYear && now < aug31ThisYear) {
  41. return feb1ThisYear.getTime()
  42. }
  43. return new Date(now < feb1ThisYear ? year - 1 : year, 7, 31, 0, 0, 0, 0).getTime()
  44. }
  45. getAutoUnbindDailyRedisKey() {
  46. const now = new Date()
  47. const year = now.getFullYear()
  48. const month = `${now.getMonth() + 1}`.padStart(2, '0')
  49. const day = `${now.getDate()}`.padStart(2, '0')
  50. return `lepao:auto_unbind:daily:${year}${month}${day}`
  51. }
  52. getSecondsToDayEnd() {
  53. const now = new Date()
  54. const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 0, 0, 0, 0)
  55. return Math.max(1, Math.floor((tomorrow.getTime() - now.getTime()) / 1000))
  56. }
  57. async onRequest(req, res) {
  58. let { uuid, session, student_num, email, id, area, auto_time, auto_run, target_count, auto_day, notice_type, notes } = req.body
  59. if ([uuid, session, student_num, auto_time, target_count, auto_day].some(value => value === '' || value === null || value === undefined))
  60. return res.json({
  61. ...BaseStdResponse.MISSING_PARAMETER
  62. })
  63. if (notice_type && !['email', 'none', 'bot', 'wechat'].includes(notice_type)) {
  64. return res.json({
  65. ...BaseStdResponse.ERR,
  66. msg: '通知方式不合法'
  67. })
  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. let countSql = 'SELECT id, create_user, total_num, auto_run, update_time FROM lepao_account WHERE student_num = ?'
  99. let countRows = await db.query(countSql, [student_num])
  100. if (!countRows)
  101. return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
  102. // 判断是否重复注册
  103. if (!id) {
  104. if (countRows.length !== 0 && countRows[0].create_user != null) {
  105. if (countRows[0].create_user !== uuid) {
  106. const semesterStartTimestamp = this.getSemesterStartTimestamp()
  107. const dailyAutoUnbindKey = this.getAutoUnbindDailyRedisKey()
  108. const dailyAutoUnbindCount = Number(await Redis.get(dailyAutoUnbindKey) || 0)
  109. const canAutoUnbindAndRebind = (countRows[0].auto_run === 0) &&
  110. (!countRows[0].update_time || countRows[0].update_time < semesterStartTimestamp) &&
  111. (dailyAutoUnbindCount < this.autoUnbindDailyLimit)
  112. if (!canAutoUnbindAndRebind)
  113. return res.json({ ...BaseStdResponse.ERR, msg: '该乐跑账号已被其他用户绑定,请联系客服处理' })
  114. } else {
  115. return res.json({ ...BaseStdResponse.ERR, msg: '该乐跑账号您已绑定' })
  116. }
  117. }
  118. }
  119. if (countRows.length !== 0) {
  120. if (auto_run === 1 && countRows[0].total_num >= target_count && target_count !== 0)
  121. return res.json({ ...BaseStdResponse.ERR, msg: '该账号累计跑步次数已达到预设目标次数,请尝试增大目标次数后再试' })
  122. }
  123. const time = new Date().getTime()
  124. const previousOwner = countRows.length !== 0 ? countRows[0].create_user : null
  125. const shouldAutoUnbindAndRebind = !id &&
  126. countRows.length !== 0 &&
  127. previousOwner != null &&
  128. previousOwner !== uuid
  129. const shouldRecordBind = !id && previousOwner !== uuid
  130. let sql, r
  131. if (!id) {
  132. if (countRows.length !== 0) {
  133. 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 = ?'
  134. 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])
  135. }
  136. else {
  137. const bind_code = await this.generateCode()
  138. 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
  139. r = await db.query(sql, [student_num, email ?? '', area, auto_time, auto_run, target_count, uuid, time, notes ?? '', JSON.stringify(auto_day), notice_type])
  140. let faceSql = 'INSERT INTO lepao_extra (student_num, bind_code) VALUES (?, ?)'
  141. let faceRows = await db.query(faceSql, [student_num, bind_code])
  142. if (!faceRows || faceRows.affectedRows !== 1)
  143. return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
  144. }
  145. } else {
  146. sql = 'UPDATE lepao_account SET student_num = ?, email = ?, area = ?, auto_time = ?, target_count = ?, auto_run = ?, notes = ?, auto_day = ?, update_time = ?, notice_type = ? WHERE id = ?'
  147. r = await db.query(sql, [student_num, email ?? '', area, auto_time, target_count, auto_run, notes ?? '', JSON.stringify(auto_day), time, notice_type, id])
  148. }
  149. try {
  150. if (r && r.affectedRows > 0) {
  151. const selectSql = `
  152. SELECT
  153. a.id, a.create_user, a.total_num, e.bind_code, e.bot_account
  154. FROM
  155. lepao_account a
  156. LEFT JOIN
  157. lepao_extra e
  158. ON
  159. a.student_num = e.student_num
  160. WHERE
  161. a.student_num = ?
  162. `
  163. const selectRows = await db.query(selectSql, [student_num])
  164. if (!selectRows)
  165. return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
  166. res.json({
  167. ...BaseStdResponse.OK,
  168. id: r.insertId,
  169. data: {
  170. student_num, email, id, area, auto_time, auto_run, target_count, auto_day, notice_type, notes,
  171. bind_code: selectRows.length !== 0 ? selectRows[0].bind_code : undefined,
  172. bot_account: selectRows.length !== 0 ? selectRows[0].bot_account : undefined
  173. }
  174. })
  175. if (shouldRecordBind) {
  176. if (shouldAutoUnbindAndRebind) {
  177. const unbindAuditOk = await insertBindAudit({
  178. studentNum: student_num,
  179. ownerUuid: previousOwner,
  180. action: BindAuditAction.PLATFORM_UNBIND,
  181. source: BindAuditSource.USER_API,
  182. operatorUuid: uuid,
  183. detail: { via: 'AddAccount:auto_unbind_rebind' },
  184. createdAt: time
  185. })
  186. if (!unbindAuditOk) {
  187. this.logger.warn(`自动解绑审计写入失败 student_num=${student_num}`)
  188. } else {
  189. const dailyAutoUnbindKey = this.getAutoUnbindDailyRedisKey()
  190. const latestAutoUnbindCount = await Redis.incr(dailyAutoUnbindKey)
  191. if (latestAutoUnbindCount === 1) {
  192. await Redis.expire(dailyAutoUnbindKey, this.getSecondsToDayEnd())
  193. }
  194. }
  195. }
  196. const auditOk = await insertBindAudit({
  197. studentNum: student_num,
  198. ownerUuid: uuid,
  199. action: BindAuditAction.PLATFORM_BIND,
  200. source: BindAuditSource.USER_API,
  201. operatorUuid: uuid,
  202. detail: { via: 'AddAccount' },
  203. createdAt: time
  204. })
  205. if (!auditOk) {
  206. this.logger.warn(`绑定审计写入失败 student_num=${student_num}`)
  207. }
  208. }
  209. } else {
  210. return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
  211. }
  212. } catch (err) {
  213. this.logger.error(`添加乐跑账号失败!${err.stack}`)
  214. res.json({
  215. ...BaseStdResponse.ERR,
  216. msg: "添加乐跑账号失败!",
  217. });
  218. }
  219. }
  220. }
  221. module.exports.AddAccount = AddAccount;