AddAccount.js 14 KB

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