| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297 |
- const API = require("../../../lib/API.js");
- const db = require("../../../plugin/DataBase/db.js");
- const Redis = require("../../../plugin/DataBase/Redis.js");
- const { BaseStdResponse } = require("../../../BaseStdResponse.js");
- const AccessControl = require("../../../lib/AccessControl.js");
- const { insertBindAudit, BindAuditAction, BindAuditSource } = require("../../../lib/Lepao/BindAudit.js");
- const { fetchWebVpnCookieFromPy, invalidateWebVpnCookie } = require("../../../lib/Lepao/webvpnCookie");
- class AddAccount extends API {
- constructor() {
- super();
- this.setPath('/Lepao/Account')
- this.setMethod('POST')
- this.emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
- this.banEmailList = ['icloud.com']
- this.autoUnbindDailyLimit = 10
- }
- // 生成 6 位数字 + 字母混合码
- async generateCode() {
- try {
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
- let code = ""
- for (let i = 0; i < 6; i++) {
- code += chars.charAt(Math.floor(Math.random() * chars.length))
- }
- let sql = 'SELECT id FROM lepao_extra WHERE bind_code = ?'
- let rows = await db.query(sql, [code])
- if (!rows)
- throw new Error('数据库错误,请稍后再试')
- if (rows.length > 0)
- return await this.generateCode()
- return code
- } catch (error) {
- throw error
- }
- }
- getSemesterStartTimestamp() {
- const now = new Date()
- const year = now.getFullYear()
- const feb1ThisYear = new Date(year, 1, 1, 0, 0, 0, 0)
- const aug31ThisYear = new Date(year, 7, 31, 0, 0, 0, 0)
- if (now >= feb1ThisYear && now < aug31ThisYear) {
- return feb1ThisYear.getTime()
- }
- return new Date(now < feb1ThisYear ? year - 1 : year, 7, 31, 0, 0, 0, 0).getTime()
- }
- getAutoUnbindDailyRedisKey() {
- const now = new Date()
- const year = now.getFullYear()
- const month = `${now.getMonth() + 1}`.padStart(2, '0')
- const day = `${now.getDate()}`.padStart(2, '0')
- return `lepao:auto_unbind:daily:${year}${month}${day}`
- }
- getSecondsToDayEnd() {
- const now = new Date()
- const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 0, 0, 0, 0)
- return Math.max(1, Math.floor((tomorrow.getTime() - now.getTime()) / 1000))
- }
- async onRequest(req, res) {
- let { uuid, session, student_num, email, id, area, auto_time, auto_run, target_count, auto_day, notice_type, notes, jw_password } = req.body
- if ([uuid, session, student_num, auto_time, target_count, auto_day].some(value => value === '' || value === null || value === undefined))
- return res.json({
- ...BaseStdResponse.MISSING_PARAMETER
- })
- if (!id && [jw_password].some(value => value === '' || value === null || value === undefined))
- return res.json({
- ...BaseStdResponse.MISSING_PARAMETER,
- msg: '新绑定乐跑账号时必须提供教务系统密码(jw_password)'
- })
- if (isNaN(target_count) || target_count < 0 || target_count > 99) {
- return res.json({
- ...BaseStdResponse.ERR,
- msg: '乐跑目标次数不在合法范围内'
- })
- }
- if (notice_type === 'email') {
- if (!this.emailRegex.test(email)) {
- return res.json({
- ...BaseStdResponse.ERR,
- msg: '请检查邮箱格式是否正确'
- })
- }
- const emailDomain = email.split('@')[1].toLowerCase()
- if (this.banEmailList.includes(emailDomain))
- return res.json({
- ...BaseStdResponse.ERR,
- msg: `暂不支持使用 ${emailDomain} 域名的邮箱,请更换其他邮箱后重试`
- })
- }
- if (auto_run === 1 && (!Array.isArray(auto_day) || !auto_day.every(v => Number.isInteger(v) && v >= 0 && v <= 6)))
- return res.json({
- ...BaseStdResponse.ERR,
- msg: '自动乐跑日期格式不合法'
- })
- if (!await AccessControl.checkSession(uuid, session))
- return res.status(401).json({
- ...BaseStdResponse.ACCESS_DENIED
- })
- const jwLoginName = String(student_num).trim()
- let plainJwPassword = null
- if (jw_password != null && jw_password !== '') {
- try {
- plainJwPassword = atob(jw_password)
- } catch {
- return res.json({
- ...BaseStdResponse.ERR,
- msg: '教务密码格式错误'
- })
- }
- }
- if (plainJwPassword) {
- try {
- await fetchWebVpnCookieFromPy(jwLoginName, plainJwPassword)
- } catch (e) {
- return res.json({
- ...BaseStdResponse.ERR,
- msg: `教务账号或密码无法通过 WebVPN 校验:${e.message || '请核对后重试'}`
- })
- }
- try {
- await invalidateWebVpnCookie(uuid, jwLoginName)
- } catch (_) { /* ignore */ }
- }
- let countSql = 'SELECT id, create_user, total_num, auto_run, update_time FROM lepao_account WHERE student_num = ?'
- let countRows = await db.query(countSql, [student_num])
- if (!countRows)
- return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
- // 判断是否重复注册
- if (!id) {
- if (countRows.length !== 0 && countRows[0].create_user != null) {
- if (countRows[0].create_user !== uuid) {
- const semesterStartTimestamp = this.getSemesterStartTimestamp()
- const dailyAutoUnbindKey = this.getAutoUnbindDailyRedisKey()
- const dailyAutoUnbindCount = Number(await Redis.get(dailyAutoUnbindKey) || 0)
- const canAutoUnbindAndRebind = (countRows[0].auto_run === 0) &&
- (!countRows[0].update_time || countRows[0].update_time < semesterStartTimestamp) &&
- (dailyAutoUnbindCount < this.autoUnbindDailyLimit)
- if (!canAutoUnbindAndRebind)
- return res.json({ ...BaseStdResponse.ERR, msg: '该乐跑账号已被其他用户绑定,请联系客服处理' })
- } else {
- return res.json({ ...BaseStdResponse.ERR, msg: '该乐跑账号您已绑定' })
- }
- }
- }
- if (countRows.length !== 0) {
- if (auto_run === 1 && countRows[0].total_num >= target_count && target_count !== 0)
- return res.json({ ...BaseStdResponse.ERR, msg: '该账号累计跑步次数已达到预设目标次数,请尝试增大目标次数后再试' })
- }
- const time = new Date().getTime()
- if (plainJwPassword) {
- const jwExisting = await db.query(
- 'SELECT id FROM jw_account WHERE create_user = ? AND username = ?',
- [uuid, jwLoginName]
- )
- if (jwExisting && jwExisting.length > 0) {
- await db.query(
- 'UPDATE jw_account SET password = ?, update_time = ?, state = 0 WHERE id = ?',
- [plainJwPassword, time, jwExisting[0].id]
- )
- } else {
- await db.query(
- 'INSERT INTO jw_account (username, password, create_user, create_time) VALUES (?, ?, ?, ?)',
- [jwLoginName, plainJwPassword, uuid, time]
- )
- }
- }
- const previousOwner = countRows.length !== 0 ? countRows[0].create_user : null
- const shouldAutoUnbindAndRebind = !id &&
- countRows.length !== 0 &&
- previousOwner != null &&
- previousOwner !== uuid
- const shouldRecordBind = !id && previousOwner !== uuid
- let sql, r
- if (!id) {
- if (countRows.length !== 0) {
- 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 = ?'
- 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])
- }
- else {
- const bind_code = await this.generateCode()
- 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
- r = await db.query(sql, [student_num, email ?? '', area, auto_time, auto_run, target_count, uuid, time, notes ?? '', JSON.stringify(auto_day), notice_type])
- let faceSql = 'INSERT INTO lepao_extra (student_num, bind_code) VALUES (?, ?)'
- let faceRows = await db.query(faceSql, [student_num, bind_code])
- if (!faceRows || faceRows.affectedRows !== 1)
- return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
- }
- } else {
- sql = 'UPDATE lepao_account SET student_num = ?, email = ?, area = ?, auto_time = ?, target_count = ?, auto_run = ?, notes = ?, auto_day = ?, update_time = ?, notice_type = ? WHERE id = ?'
- r = await db.query(sql, [student_num, email ?? '', area, auto_time, target_count, auto_run, notes ?? '', JSON.stringify(auto_day), time, notice_type, id])
- }
- try {
- if (r && r.affectedRows > 0) {
- const selectSql = `
- SELECT
- a.id, a.create_user, a.total_num, e.bind_code, e.bot_account
- FROM
- lepao_account a
- LEFT JOIN
- lepao_extra e
- ON
- a.student_num = e.student_num
- WHERE
- a.student_num = ?
- `
- const selectRows = await db.query(selectSql, [student_num])
- if (!selectRows)
- return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
- res.json({
- ...BaseStdResponse.OK,
- id: r.insertId,
- data: {
- student_num, email, id, area, auto_time, auto_run, target_count, auto_day, notice_type, notes,
- bind_code: selectRows.length !== 0 ? selectRows[0].bind_code : undefined,
- bot_account: selectRows.length !== 0 ? selectRows[0].bot_account : undefined
- }
- })
- if (shouldRecordBind) {
- if (shouldAutoUnbindAndRebind) {
- const unbindAuditOk = await insertBindAudit({
- studentNum: student_num,
- ownerUuid: previousOwner,
- action: BindAuditAction.PLATFORM_UNBIND,
- source: BindAuditSource.USER_API,
- operatorUuid: uuid,
- detail: { via: 'AddAccount:auto_unbind_rebind' },
- createdAt: time
- })
- if (!unbindAuditOk) {
- this.logger.warn(`自动解绑审计写入失败 student_num=${student_num}`)
- } else {
- const dailyAutoUnbindKey = this.getAutoUnbindDailyRedisKey()
- const latestAutoUnbindCount = await Redis.incr(dailyAutoUnbindKey)
- if (latestAutoUnbindCount === 1) {
- await Redis.expire(dailyAutoUnbindKey, this.getSecondsToDayEnd())
- }
- }
- }
- const auditOk = await insertBindAudit({
- studentNum: student_num,
- ownerUuid: uuid,
- action: BindAuditAction.PLATFORM_BIND,
- source: BindAuditSource.USER_API,
- operatorUuid: uuid,
- detail: { via: 'AddAccount' },
- createdAt: time
- })
- if (!auditOk) {
- this.logger.warn(`绑定审计写入失败 student_num=${student_num}`)
- }
- }
- } else {
- return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败!数据库错误' })
- }
- } catch (err) {
- this.logger.error(`添加乐跑账号失败!${err.stack}`)
- res.json({
- ...BaseStdResponse.ERR,
- msg: "添加乐跑账号失败!",
- });
- }
- }
- }
- module.exports.AddAccount = AddAccount;
|