AddAccount.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. const API = require("../../../lib/API.js");
  2. const db = require("../../../plugin/DataBase/db.js");
  3. const { BaseStdResponse } = require("../../../BaseStdResponse.js");
  4. const AccessControl = require("../../../lib/AccessControl.js");
  5. const { insertBindAudit, BindAuditAction, BindAuditSource } = require("../../../lib/Lepao/BindAudit.js");
  6. class AddAccount extends API {
  7. constructor() {
  8. super();
  9. this.setPath('/Lepao/Account')
  10. this.setMethod('POST')
  11. this.emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  12. this.banEmailList = ['icloud.com']
  13. }
  14. // 生成 6 位数字 + 字母混合码
  15. async generateCode() {
  16. try {
  17. const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  18. let code = ""
  19. for (let i = 0; i < 6; i++) {
  20. code += chars.charAt(Math.floor(Math.random() * chars.length))
  21. }
  22. let sql = 'SELECT id FROM lepao_extra WHERE bind_code = ?'
  23. let rows = await db.query(sql, [code])
  24. if (!rows)
  25. throw new Error('数据库错误,请稍后再试')
  26. if (rows.length > 0)
  27. return await this.generateCode()
  28. return code
  29. } catch (error) {
  30. throw error
  31. }
  32. }
  33. async onRequest(req, res) {
  34. let { uuid, session, student_num, email, id, area, auto_time, auto_run, target_count, auto_day, notice_type, notes } = req.body
  35. if ([uuid, session, student_num, auto_time, target_count, auto_day].some(value => value === '' || value === null || value === undefined))
  36. return res.json({
  37. ...BaseStdResponse.MISSING_PARAMETER
  38. })
  39. if (isNaN(target_count) || target_count < 0 || target_count > 99) {
  40. return res.json({
  41. ...BaseStdResponse.ERR,
  42. msg: '乐跑目标次数不在合法范围内'
  43. })
  44. }
  45. if (notice_type === 'email') {
  46. if (!this.emailRegex.test(email)) {
  47. return res.json({
  48. ...BaseStdResponse.ERR,
  49. msg: '请检查邮箱格式是否正确'
  50. })
  51. }
  52. const emailDomain = email.split('@')[1].toLowerCase()
  53. if (this.banEmailList.includes(emailDomain))
  54. return res.json({
  55. ...BaseStdResponse.ERR,
  56. msg: `暂不支持使用 ${emailDomain} 域名的邮箱,请更换其他邮箱后重试`
  57. })
  58. }
  59. if (auto_run === 1 && (!Array.isArray(auto_day) || !auto_day.every(v => Number.isInteger(v) && v >= 0 && v <= 6)))
  60. return res.json({
  61. ...BaseStdResponse.ERR,
  62. msg: '自动乐跑日期格式不合法'
  63. })
  64. if (!await AccessControl.checkSession(uuid, session))
  65. return res.status(401).json({
  66. ...BaseStdResponse.ACCESS_DENIED
  67. })
  68. let countSql = 'SELECT id, create_user, total_num FROM lepao_account WHERE student_num = ?'
  69. let countRows = await db.query(countSql, [student_num])
  70. if (!countRows)
  71. return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
  72. // 判断是否重复注册
  73. if (!id) {
  74. if (countRows.length !== 0 && countRows[0].create_user != null) {
  75. if (countRows[0].create_user !== uuid)
  76. return res.json({ ...BaseStdResponse.ERR, msg: '该乐跑账号已被其他用户绑定,请联系客服解绑' })
  77. return res.json({ ...BaseStdResponse.ERR, msg: '该乐跑账号您已绑定' })
  78. }
  79. }
  80. if (countRows.length !== 0) {
  81. if (auto_run === 1 && countRows[0].total_num >= target_count && target_count !== 0)
  82. return res.json({ ...BaseStdResponse.ERR, msg: '该账号累计跑步次数已达到预设目标次数,请尝试增大目标次数后再试' })
  83. }
  84. const time = new Date().getTime()
  85. const previousOwner = countRows.length !== 0 ? countRows[0].create_user : null
  86. const shouldRecordBind = !id && previousOwner !== uuid
  87. let sql, r
  88. if (!id) {
  89. if (countRows.length !== 0) {
  90. 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 = ?'
  91. 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])
  92. }
  93. else {
  94. const bind_code = await this.generateCode()
  95. 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
  96. r = await db.query(sql, [student_num, email ?? '', area, auto_time, auto_run, target_count, uuid, time, notes ?? '', JSON.stringify(auto_day), notice_type])
  97. let faceSql = 'INSERT INTO lepao_extra (student_num, bind_code) VALUES (?, ?)'
  98. let faceRows = await db.query(faceSql, [student_num, bind_code])
  99. if (!faceRows || faceRows.affectedRows !== 1)
  100. return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
  101. }
  102. } else {
  103. sql = 'UPDATE lepao_account SET student_num = ?, email = ?, area = ?, auto_time = ?, target_count = ?, auto_run = ?, notes = ?, auto_day = ?, update_time = ?, notice_type = ? WHERE id = ?'
  104. r = await db.query(sql, [student_num, email ?? '', area, auto_time, target_count, auto_run, notes ?? '', JSON.stringify(auto_day), time, notice_type, id])
  105. }
  106. try {
  107. if (r && r.affectedRows > 0) {
  108. const selectSql = `
  109. SELECT
  110. a.id, a.create_user, a.total_num, e.bind_code, e.bot_account
  111. FROM
  112. lepao_account a
  113. LEFT JOIN
  114. lepao_extra e
  115. ON
  116. a.student_num = e.student_num
  117. WHERE
  118. a.student_num = ?
  119. `
  120. const selectRows = await db.query(selectSql, [student_num])
  121. if (!selectRows)
  122. return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
  123. res.json({
  124. ...BaseStdResponse.OK,
  125. id: r.insertId,
  126. data: {
  127. student_num, email, id, area, auto_time, auto_run, target_count, auto_day, notice_type, notes,
  128. bind_code: selectRows.length !== 0 ? selectRows[0].bind_code : undefined,
  129. bot_account: selectRows.length !== 0 ? selectRows[0].bot_account : undefined
  130. }
  131. })
  132. if (shouldRecordBind) {
  133. const auditOk = await insertBindAudit({
  134. studentNum: student_num,
  135. ownerUuid: uuid,
  136. action: BindAuditAction.PLATFORM_BIND,
  137. source: BindAuditSource.USER_API,
  138. operatorUuid: uuid,
  139. detail: { via: 'AddAccount' },
  140. createdAt: time
  141. })
  142. if (!auditOk) {
  143. this.logger.warn(`绑定审计写入失败 student_num=${student_num}`)
  144. }
  145. }
  146. } else {
  147. return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
  148. }
  149. } catch (err) {
  150. this.logger.error(`添加乐跑账号失败!${err.stack}`)
  151. res.json({
  152. ...BaseStdResponse.ERR,
  153. msg: "添加乐跑账号失败!",
  154. });
  155. }
  156. }
  157. }
  158. module.exports.AddAccount = AddAccount;