AddAccount.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 = 10
  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 (isNaN(target_count) || target_count < 0 || target_count > 99) {
  64. return res.json({
  65. ...BaseStdResponse.ERR,
  66. msg: '乐跑目标次数不在合法范围内'
  67. })
  68. }
  69. if (notice_type === 'email') {
  70. if (!this.emailRegex.test(email)) {
  71. return res.json({
  72. ...BaseStdResponse.ERR,
  73. msg: '请检查邮箱格式是否正确'
  74. })
  75. }
  76. const emailDomain = email.split('@')[1].toLowerCase()
  77. if (this.banEmailList.includes(emailDomain))
  78. return res.json({
  79. ...BaseStdResponse.ERR,
  80. msg: `暂不支持使用 ${emailDomain} 域名的邮箱,请更换其他邮箱后重试`
  81. })
  82. }
  83. if (auto_run === 1 && (!Array.isArray(auto_day) || !auto_day.every(v => Number.isInteger(v) && v >= 0 && v <= 6)))
  84. return res.json({
  85. ...BaseStdResponse.ERR,
  86. msg: '自动乐跑日期格式不合法'
  87. })
  88. if (!await AccessControl.checkSession(uuid, session))
  89. return res.status(401).json({
  90. ...BaseStdResponse.ACCESS_DENIED
  91. })
  92. let countSql = 'SELECT id, create_user, total_num, auto_run, update_time FROM lepao_account WHERE student_num = ?'
  93. let countRows = await db.query(countSql, [student_num])
  94. if (!countRows)
  95. return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
  96. // 判断是否重复注册
  97. if (!id) {
  98. if (countRows.length !== 0 && countRows[0].create_user != null) {
  99. if (countRows[0].create_user !== uuid) {
  100. const semesterStartTimestamp = this.getSemesterStartTimestamp()
  101. const dailyAutoUnbindKey = this.getAutoUnbindDailyRedisKey()
  102. const dailyAutoUnbindCount = Number(await Redis.get(dailyAutoUnbindKey) || 0)
  103. const canAutoUnbindAndRebind = (countRows[0].auto_run === 0) &&
  104. (!countRows[0].update_time || countRows[0].update_time < semesterStartTimestamp) &&
  105. (dailyAutoUnbindCount < this.autoUnbindDailyLimit)
  106. if (!canAutoUnbindAndRebind)
  107. return res.json({ ...BaseStdResponse.ERR, msg: '该乐跑账号已被其他用户绑定,请联系客服处理' })
  108. } else {
  109. return res.json({ ...BaseStdResponse.ERR, msg: '该乐跑账号您已绑定' })
  110. }
  111. }
  112. }
  113. if (countRows.length !== 0) {
  114. if (auto_run === 1 && countRows[0].total_num >= target_count && target_count !== 0)
  115. return res.json({ ...BaseStdResponse.ERR, msg: '该账号累计跑步次数已达到预设目标次数,请尝试增大目标次数后再试' })
  116. }
  117. const time = new Date().getTime()
  118. const previousOwner = countRows.length !== 0 ? countRows[0].create_user : null
  119. const shouldAutoUnbindAndRebind = !id &&
  120. countRows.length !== 0 &&
  121. previousOwner != null &&
  122. previousOwner !== uuid
  123. const shouldRecordBind = !id && previousOwner !== uuid
  124. let sql, r
  125. if (!id) {
  126. if (countRows.length !== 0) {
  127. 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 = ?'
  128. 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])
  129. }
  130. else {
  131. const bind_code = await this.generateCode()
  132. 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
  133. r = await db.query(sql, [student_num, email ?? '', area, auto_time, auto_run, target_count, uuid, time, notes ?? '', JSON.stringify(auto_day), notice_type])
  134. let faceSql = 'INSERT INTO lepao_extra (student_num, bind_code) VALUES (?, ?)'
  135. let faceRows = await db.query(faceSql, [student_num, bind_code])
  136. if (!faceRows || faceRows.affectedRows !== 1)
  137. return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
  138. }
  139. } else {
  140. sql = 'UPDATE lepao_account SET student_num = ?, email = ?, area = ?, auto_time = ?, target_count = ?, auto_run = ?, notes = ?, auto_day = ?, update_time = ?, notice_type = ? WHERE id = ?'
  141. r = await db.query(sql, [student_num, email ?? '', area, auto_time, target_count, auto_run, notes ?? '', JSON.stringify(auto_day), time, notice_type, id])
  142. }
  143. try {
  144. if (r && r.affectedRows > 0) {
  145. const selectSql = `
  146. SELECT
  147. a.id, a.create_user, a.total_num, e.bind_code, e.bot_account
  148. FROM
  149. lepao_account a
  150. LEFT JOIN
  151. lepao_extra e
  152. ON
  153. a.student_num = e.student_num
  154. WHERE
  155. a.student_num = ?
  156. `
  157. const selectRows = await db.query(selectSql, [student_num])
  158. if (!selectRows)
  159. return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
  160. res.json({
  161. ...BaseStdResponse.OK,
  162. id: r.insertId,
  163. data: {
  164. student_num, email, id, area, auto_time, auto_run, target_count, auto_day, notice_type, notes,
  165. bind_code: selectRows.length !== 0 ? selectRows[0].bind_code : undefined,
  166. bot_account: selectRows.length !== 0 ? selectRows[0].bot_account : undefined
  167. }
  168. })
  169. if (shouldRecordBind) {
  170. if (shouldAutoUnbindAndRebind) {
  171. const unbindAuditOk = await insertBindAudit({
  172. studentNum: student_num,
  173. ownerUuid: previousOwner,
  174. action: BindAuditAction.PLATFORM_UNBIND,
  175. source: BindAuditSource.USER_API,
  176. operatorUuid: uuid,
  177. detail: { via: 'AddAccount:auto_unbind_rebind' },
  178. createdAt: time
  179. })
  180. if (!unbindAuditOk) {
  181. this.logger.warn(`自动解绑审计写入失败 student_num=${student_num}`)
  182. } else {
  183. const dailyAutoUnbindKey = this.getAutoUnbindDailyRedisKey()
  184. const latestAutoUnbindCount = await Redis.incr(dailyAutoUnbindKey)
  185. if (latestAutoUnbindCount === 1) {
  186. await Redis.expire(dailyAutoUnbindKey, this.getSecondsToDayEnd())
  187. }
  188. }
  189. }
  190. const auditOk = await insertBindAudit({
  191. studentNum: student_num,
  192. ownerUuid: uuid,
  193. action: BindAuditAction.PLATFORM_BIND,
  194. source: BindAuditSource.USER_API,
  195. operatorUuid: uuid,
  196. detail: { via: 'AddAccount' },
  197. createdAt: time
  198. })
  199. if (!auditOk) {
  200. this.logger.warn(`绑定审计写入失败 student_num=${student_num}`)
  201. }
  202. }
  203. } else {
  204. return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
  205. }
  206. } catch (err) {
  207. this.logger.error(`添加乐跑账号失败!${err.stack}`)
  208. res.json({
  209. ...BaseStdResponse.ERR,
  210. msg: "添加乐跑账号失败!",
  211. });
  212. }
  213. }
  214. }
  215. module.exports.AddAccount = AddAccount;