fix: comprehensive security, quality and consistency fixes
Server: - Block startup with default JWT secrets in production - Make subscription verify admin-only (no payment integration yet) - Add device ownership validation on command/result, event, treatment/sync - Remove admin token from request body fallback - Add pageParams boundary protection (pageSize capped at 100) - Fix COS getObjectUrl to use callback-based Promise - Add settings key whitelist matching frontend fields - Add user existence check before subscription creation - Fix firmware always returning has_update:true - Replace hardcoded trial subscription with actual DB query - Extract shared utilities (limitClause, toMysqlDate, formatDate) Miniprogram: - Replace fake PD random data with placeholder - Mark client-timer treatment completions with source field - Disable mock.js - Fix BLE listener leaks (save refs, cleanup in onUnload) - Fix ble.off clearing all listeners (pass specific callback) - Add BLE disconnect detection via onBLEConnectionStateChange - Fix subscription status type consistency (number not string) - Fix scan callback accumulation in ble.js - Fix history stats accumulation across pages - Fix subscribe-success/treatment-done hardcoded values - Fix profile subscription view logic - Replace purchase flow with admin-contact modal - Add error logging in command-sync report Admin console: - Fix AdminLayout logout (require->import, logout->clearToken) - Remove all mock data from production request.js - Replace dashboard fake data with real API calls - Replace monthly_revenue with subscription_count - Fix subscription stats fallback (|| -> ??) - Add token expiry tracking (7 days) - Unify device status map and subscription status text - Fix user page record link navigation - Fix subscription createForm.user_id type handling - Add error feedback in all empty catch blocks - Remove unused remember checkbox and uview-plus dependency - Extract common CSS to shared stylesheet (-900 lines) - Extract formatDate to shared utils/format.js - Show real admin name in layout header
这个提交包含在:
@@ -32,4 +32,9 @@ const config = {
|
||||
}
|
||||
}
|
||||
|
||||
if (config.nodeEnv === 'production') {
|
||||
if (config.jwt.secret === 'dev-user-secret') throw new Error('JWT_SECRET must be set in production')
|
||||
if (config.jwt.adminSecret === 'dev-admin-secret') throw new Error('ADMIN_JWT_SECRET must be set in production')
|
||||
}
|
||||
|
||||
module.exports = config
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ async function requireUser(ctx) {
|
||||
}
|
||||
|
||||
async function requireAdmin(ctx) {
|
||||
const token = readBearer(ctx.headers) || (ctx.body && ctx.body.token)
|
||||
const token = readBearer(ctx.headers)
|
||||
if (!token) return null
|
||||
try {
|
||||
const payload = jwt.verify(token, config.jwt.adminSecret)
|
||||
|
||||
+11
-6
@@ -14,12 +14,17 @@ function getClient() {
|
||||
}
|
||||
|
||||
function getObjectUrl(key, expiresSeconds) {
|
||||
return getClient().getObjectUrl({
|
||||
Bucket: config.cos.bucket,
|
||||
Region: config.cos.region,
|
||||
Key: key,
|
||||
Sign: true,
|
||||
Expires: expiresSeconds || 600
|
||||
return new Promise((resolve, reject) => {
|
||||
getClient().getObjectUrl({
|
||||
Bucket: config.cos.bucket,
|
||||
Region: config.cos.region,
|
||||
Key: key,
|
||||
Sign: true,
|
||||
Expires: expiresSeconds || 3600
|
||||
}, (err, data) => {
|
||||
if (err) reject(err)
|
||||
else resolve(data.Url)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+5
-1
@@ -45,4 +45,8 @@ async function transaction(work) {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { getPool, query, one, transaction }
|
||||
function limitClause(pageSize, offset) {
|
||||
return ' LIMIT ' + Number(pageSize) + ' OFFSET ' + Number(offset)
|
||||
}
|
||||
|
||||
module.exports = { getPool, query, one, transaction, limitClause }
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
function toMysqlDate(value) {
|
||||
if (!value) return null
|
||||
const d = new Date(value)
|
||||
if (Number.isNaN(d.getTime())) return null
|
||||
return d.toISOString().slice(0, 19).replace('T', ' ')
|
||||
}
|
||||
|
||||
function formatDate(date) {
|
||||
return toMysqlDate(date)
|
||||
}
|
||||
|
||||
module.exports = { toMysqlDate, formatDate }
|
||||
+33
-34
@@ -1,23 +1,14 @@
|
||||
const { one, query } = require('../lib/db')
|
||||
const { one, query, limitClause } = require('../lib/db')
|
||||
const { ok, fail } = require('../lib/response')
|
||||
const { hashPassword, signAdmin, requireAdmin } = require('../lib/auth')
|
||||
const { writeLog } = require('../lib/log')
|
||||
|
||||
function pageParams(ctx) {
|
||||
const page = Math.max(1, parseInt(ctx.query.page || ctx.body.page, 10) || 1)
|
||||
const pageSize = Math.min(Math.max(1, parseInt(ctx.query.page_size || ctx.body.page_size, 10) || 20), 100)
|
||||
const page = Math.max(1, parseInt(ctx.query.page, 10) || 1)
|
||||
const pageSize = Math.min(Math.max(1, parseInt(ctx.query.page_size, 10) || 20), 100)
|
||||
return { page, pageSize, offset: (page - 1) * pageSize }
|
||||
}
|
||||
|
||||
function limitClause(p) {
|
||||
return ' LIMIT ' + Number(p.pageSize) + ' OFFSET ' + Number(p.offset)
|
||||
}
|
||||
|
||||
async function adminOnly(ctx) {
|
||||
const admin = await requireAdmin(ctx)
|
||||
return admin
|
||||
}
|
||||
|
||||
function register(router) {
|
||||
router.post('/api/v1/admin/login', async ctx => {
|
||||
const username = ctx.body.username || ''
|
||||
@@ -30,7 +21,7 @@ function register(router) {
|
||||
})
|
||||
|
||||
router.get('/api/v1/admin/dashboard', async ctx => {
|
||||
const admin = await adminOnly(ctx)
|
||||
const admin = await requireAdmin(ctx)
|
||||
if (!admin) return fail(1002, '未授权,请重新登录')
|
||||
const rows = await Promise.all([
|
||||
query('SELECT COUNT(*) AS total FROM devices', {}),
|
||||
@@ -42,16 +33,16 @@ function register(router) {
|
||||
})
|
||||
|
||||
router.get('/api/v1/admin/devices', async ctx => {
|
||||
const admin = await adminOnly(ctx)
|
||||
const admin = await requireAdmin(ctx)
|
||||
if (!admin) return fail(1002, '未授权,请重新登录')
|
||||
const p = pageParams(ctx)
|
||||
const total = await query('SELECT COUNT(*) AS total FROM devices', {})
|
||||
const records = await query('SELECT d.*, b.user_id AS bound_user, b.bind_time AS activated_at FROM devices d LEFT JOIN bindings b ON b.device_id = d.device_id AND b.bind_status = 1 ORDER BY d.created_at DESC' + limitClause(p), {})
|
||||
const records = await query('SELECT d.*, b.user_id AS bound_user, b.bind_time AS activated_at FROM devices d LEFT JOIN bindings b ON b.device_id = d.device_id AND b.bind_status = 1 ORDER BY d.created_at DESC' + limitClause(p.pageSize, p.offset), {})
|
||||
return ok({ records, total: total[0].total })
|
||||
})
|
||||
|
||||
router.post('/api/v1/admin/devices', async ctx => {
|
||||
const admin = await adminOnly(ctx)
|
||||
const admin = await requireAdmin(ctx)
|
||||
if (!admin) return fail(1002, '未授权,请重新登录')
|
||||
const deviceId = String(ctx.body.device_id || '').trim()
|
||||
if (!deviceId) return fail(2001, 'device_id required')
|
||||
@@ -70,7 +61,7 @@ function register(router) {
|
||||
})
|
||||
|
||||
router.get('/api/v1/admin/devices/:device_id', async ctx => {
|
||||
const admin = await adminOnly(ctx)
|
||||
const admin = await requireAdmin(ctx)
|
||||
if (!admin) return fail(1002, '未授权,请重新登录')
|
||||
const device = await one('SELECT d.*, b.user_id AS bound_user, b.bind_time AS activated_at FROM devices d LEFT JOIN bindings b ON b.device_id = d.device_id AND b.bind_status = 1 WHERE d.device_id = :device_id', { device_id: ctx.params.device_id })
|
||||
if (!device) return fail(1005, 'DEVICE_NOT_FOUND')
|
||||
@@ -78,7 +69,7 @@ function register(router) {
|
||||
})
|
||||
|
||||
router.post('/api/v1/admin/devices/:device_id/unbind', async ctx => {
|
||||
const admin = await adminOnly(ctx)
|
||||
const admin = await requireAdmin(ctx)
|
||||
if (!admin) return fail(1002, '未授权,请重新登录')
|
||||
await query('UPDATE bindings SET bind_status = 2, unbind_time = NOW() WHERE device_id = :device_id AND bind_status = 1', { device_id: ctx.params.device_id })
|
||||
await writeLog({ admin_id: admin.admin_id, action: 'admin_device_unbind', detail: '后台解绑设备: ' + ctx.params.device_id, ip: ctx.ip })
|
||||
@@ -86,7 +77,7 @@ function register(router) {
|
||||
})
|
||||
|
||||
router.post('/api/v1/admin/devices/:device_id/command', async ctx => {
|
||||
const admin = await adminOnly(ctx)
|
||||
const admin = await requireAdmin(ctx)
|
||||
if (!admin) return fail(1002, '未授权,请重新登录')
|
||||
const opcode = parseInt(ctx.body.opcode, 10)
|
||||
if (!opcode) return fail(2001, 'opcode required')
|
||||
@@ -99,28 +90,28 @@ function register(router) {
|
||||
})
|
||||
|
||||
router.get('/api/v1/admin/devices/:device_id/commands', async ctx => {
|
||||
const admin = await adminOnly(ctx)
|
||||
const admin = await requireAdmin(ctx)
|
||||
if (!admin) return fail(1002, '未授权,请重新登录')
|
||||
const p = pageParams(ctx)
|
||||
const total = await query('SELECT COUNT(*) AS total FROM device_commands WHERE device_id = :device_id', { device_id: ctx.params.device_id })
|
||||
const records = await query(
|
||||
'SELECT command_id, device_id, admin_id, opcode, payload_json, status, created_at, pulled_at, finished_at, result_json FROM device_commands WHERE device_id = :device_id ORDER BY created_at DESC' + limitClause(p),
|
||||
'SELECT command_id, device_id, admin_id, opcode, payload_json, status, created_at, pulled_at, finished_at, result_json FROM device_commands WHERE device_id = :device_id ORDER BY created_at DESC' + limitClause(p.pageSize, p.offset),
|
||||
{ device_id: ctx.params.device_id }
|
||||
)
|
||||
return ok({ records, total: total[0].total })
|
||||
})
|
||||
|
||||
router.get('/api/v1/admin/users', async ctx => {
|
||||
const admin = await adminOnly(ctx)
|
||||
const admin = await requireAdmin(ctx)
|
||||
if (!admin) return fail(1002, '未授权,请重新登录')
|
||||
const p = pageParams(ctx)
|
||||
const total = await query('SELECT COUNT(*) AS total FROM users', {})
|
||||
const records = await query('SELECT * FROM users ORDER BY created_at DESC' + limitClause(p), {})
|
||||
const records = await query('SELECT * FROM users ORDER BY created_at DESC' + limitClause(p.pageSize, p.offset), {})
|
||||
return ok({ records, total: total[0].total })
|
||||
})
|
||||
|
||||
router.get('/api/v1/admin/users/:user_id', async ctx => {
|
||||
const admin = await adminOnly(ctx)
|
||||
const admin = await requireAdmin(ctx)
|
||||
if (!admin) return fail(1002, '未授权,请重新登录')
|
||||
const user = await one('SELECT * FROM users WHERE user_id = :user_id', { user_id: ctx.params.user_id })
|
||||
if (!user) return fail(1004, 'USER_NOT_FOUND')
|
||||
@@ -130,17 +121,19 @@ function register(router) {
|
||||
})
|
||||
|
||||
router.get('/api/v1/admin/subscriptions', async ctx => {
|
||||
const admin = await adminOnly(ctx)
|
||||
const admin = await requireAdmin(ctx)
|
||||
if (!admin) return fail(1002, '未授权,请重新登录')
|
||||
const p = pageParams(ctx)
|
||||
const total = await query('SELECT COUNT(*) AS total FROM subscriptions', {})
|
||||
const records = await query('SELECT * FROM subscriptions ORDER BY created_at DESC' + limitClause(p), {})
|
||||
const records = await query('SELECT * FROM subscriptions ORDER BY created_at DESC' + limitClause(p.pageSize, p.offset), {})
|
||||
return ok({ records, total: total[0].total })
|
||||
})
|
||||
|
||||
router.post('/api/v1/admin/subscriptions', async ctx => {
|
||||
const admin = await adminOnly(ctx)
|
||||
const admin = await requireAdmin(ctx)
|
||||
if (!admin) return fail(1002, '未授权,请重新登录')
|
||||
const targetUser = await one('SELECT user_id FROM users WHERE user_id = :user_id', { user_id: ctx.body.user_id })
|
||||
if (!targetUser) return fail(1004, 'user_not_found')
|
||||
await query('INSERT INTO subscriptions (user_id, plan, status, amount, order_id, start_time, expire_time) VALUES (:user_id, :plan, 1, :amount, :order_id, NOW(), DATE_ADD(NOW(), INTERVAL :days DAY))', {
|
||||
user_id: ctx.body.user_id,
|
||||
plan: ctx.body.plan || 'monthly',
|
||||
@@ -152,38 +145,44 @@ function register(router) {
|
||||
})
|
||||
|
||||
router.get('/api/v1/admin/records', async ctx => {
|
||||
const admin = await adminOnly(ctx)
|
||||
const admin = await requireAdmin(ctx)
|
||||
if (!admin) return fail(1002, '未授权,请重新登录')
|
||||
const p = pageParams(ctx)
|
||||
const total = await query('SELECT COUNT(*) AS total FROM treatment_records', {})
|
||||
const records = await query('SELECT * FROM treatment_records ORDER BY created_at DESC' + limitClause(p), {})
|
||||
const records = await query('SELECT * FROM treatment_records ORDER BY created_at DESC' + limitClause(p.pageSize, p.offset), {})
|
||||
return ok({ records, total: total[0].total })
|
||||
})
|
||||
|
||||
router.get('/api/v1/admin/logs', async ctx => {
|
||||
const admin = await adminOnly(ctx)
|
||||
const admin = await requireAdmin(ctx)
|
||||
if (!admin) return fail(1002, '未授权,请重新登录')
|
||||
const p = pageParams(ctx)
|
||||
const total = await query('SELECT COUNT(*) AS total FROM operation_logs', {})
|
||||
const records = await query('SELECT * FROM operation_logs ORDER BY created_at DESC' + limitClause(p), {})
|
||||
const records = await query('SELECT * FROM operation_logs ORDER BY created_at DESC' + limitClause(p.pageSize, p.offset), {})
|
||||
return ok({ records, total: total[0].total })
|
||||
})
|
||||
|
||||
router.get('/api/v1/admin/settings', async ctx => {
|
||||
const admin = await adminOnly(ctx)
|
||||
const admin = await requireAdmin(ctx)
|
||||
if (!admin) return fail(1002, '未授权,请重新登录')
|
||||
const rows = await query('SELECT setting_key, setting_value FROM system_settings', {})
|
||||
const settings = {}
|
||||
rows.forEach(row => {
|
||||
settings[row.setting_key] = typeof row.setting_value === 'string' ? JSON.parse(row.setting_value) : row.setting_value
|
||||
if (typeof row.setting_value === 'string') {
|
||||
try { settings[row.setting_key] = JSON.parse(row.setting_value) } catch (_) { settings[row.setting_key] = row.setting_value }
|
||||
} else {
|
||||
settings[row.setting_key] = row.setting_value
|
||||
}
|
||||
})
|
||||
return ok(settings)
|
||||
})
|
||||
|
||||
router.post('/api/v1/admin/settings', async ctx => {
|
||||
const admin = await adminOnly(ctx)
|
||||
const admin = await requireAdmin(ctx)
|
||||
if (!admin) return fail(1002, '未授权,请重新登录')
|
||||
const ALLOWED_KEYS = ['system_name', 'admin_email', 'timezone', 'monthly_price', 'yearly_price', 'trial_days', 'enable_register', 'enable_binding', 'enable_free_mode', 'enable_smart_mode', 'maintenance_mode']
|
||||
for (const key of Object.keys(ctx.body || {})) {
|
||||
if (!ALLOWED_KEYS.includes(key)) continue
|
||||
await query('REPLACE INTO system_settings (setting_key, setting_value) VALUES (:setting_key, :setting_value)', { setting_key: key, setting_value: JSON.stringify(ctx.body[key]) })
|
||||
}
|
||||
return ok({ message: 'success' })
|
||||
|
||||
@@ -2,10 +2,7 @@ const { one, query, transaction } = require('../lib/db')
|
||||
const { ok, fail } = require('../lib/response')
|
||||
const { requireUser, randomHex } = require('../lib/auth')
|
||||
const { writeLog } = require('../lib/log')
|
||||
|
||||
function formatDate(date) {
|
||||
return date.toISOString().slice(0, 19).replace('T', ' ')
|
||||
}
|
||||
const { formatDate } = require('../lib/utils')
|
||||
|
||||
async function ensureTrial(conn, userId) {
|
||||
const [subs] = await conn.execute('SELECT subscription_id FROM subscriptions WHERE user_id = ? AND status = 1 AND expire_time > NOW() LIMIT 1', [userId])
|
||||
@@ -40,7 +37,8 @@ function register(router) {
|
||||
if (result.invalid) return fail(1005, 'DEVICE_NOT_FOUND')
|
||||
if (result.duplicated) return fail(2001, '已绑定设备', { device_id: result.device_id })
|
||||
await writeLog({ user_id: user.user_id, action: 'device_bind_request', detail: '申请绑定设备: ' + deviceId, ip: ctx.ip })
|
||||
return ok(Object.assign(result, { subscription: { plan: 'trial', remaining_days: 7 } }))
|
||||
const sub = await one('SELECT plan, GREATEST(DATEDIFF(expire_time, NOW()), 0) AS remaining_days FROM subscriptions WHERE user_id = :user_id AND status = 1 AND expire_time > NOW() ORDER BY expire_time DESC LIMIT 1', { user_id: user.user_id })
|
||||
return ok(Object.assign(result, { subscription: sub ? { plan: sub.plan, remaining_days: sub.remaining_days } : { plan: 'none', remaining_days: 0 } }))
|
||||
})
|
||||
|
||||
router.post('/api/v1/device/bind/confirm', async ctx => {
|
||||
@@ -62,7 +60,8 @@ function register(router) {
|
||||
})
|
||||
if (!updated) return fail(2001, 'bind_token invalid or expired')
|
||||
await writeLog({ user_id: user.user_id, action: 'device_bind_confirm', detail: '确认绑定设备: ' + deviceId, ip: ctx.ip })
|
||||
return ok({ message: 'success', subscription: { plan: 'trial', remaining_days: 7 } })
|
||||
const sub = await one('SELECT plan, GREATEST(DATEDIFF(expire_time, NOW()), 0) AS remaining_days FROM subscriptions WHERE user_id = :user_id AND status = 1 AND expire_time > NOW() ORDER BY expire_time DESC LIMIT 1', { user_id: user.user_id })
|
||||
return ok({ message: 'success', subscription: sub ? { plan: sub.plan, remaining_days: sub.remaining_days } : { plan: 'none', remaining_days: 0 } })
|
||||
})
|
||||
|
||||
router.post('/api/v1/device/unbind', async ctx => {
|
||||
@@ -107,6 +106,8 @@ function register(router) {
|
||||
const commandId = parseInt(ctx.body.command_id || ctx.body.seq, 10)
|
||||
const success = ctx.body.success !== false
|
||||
if (!commandId) return fail(2001, 'command_id required')
|
||||
const cmd = await one('SELECT dc.command_id FROM device_commands dc JOIN bindings b ON b.device_id = dc.device_id AND b.user_id = :user_id AND b.bind_status = 1 WHERE dc.command_id = :command_id', { user_id: user.user_id, command_id: commandId })
|
||||
if (!cmd) return fail(1006, 'device_not_bound')
|
||||
await query('UPDATE device_commands SET status = :status, finished_at = NOW(), result_json = :result_json WHERE command_id = :command_id', {
|
||||
command_id: commandId,
|
||||
status: success ? 3 : 4,
|
||||
@@ -131,6 +132,8 @@ function register(router) {
|
||||
if (!user) return fail(1001, 'invalid_token')
|
||||
const deviceId = String(ctx.body.device_id || '').trim()
|
||||
if (!deviceId) return fail(2001, 'device_id required')
|
||||
const binding = await one('SELECT binding_id FROM bindings WHERE user_id = :user_id AND device_id = :device_id AND bind_status = 1', { user_id: user.user_id, device_id: deviceId })
|
||||
if (!binding) return fail(1006, 'device_not_bound')
|
||||
await query(
|
||||
'INSERT INTO device_events (device_id, user_id, event_type, error_code, temperature, payload_json) VALUES (:device_id, :user_id, :event_type, :error_code, :temperature, :payload_json)',
|
||||
{
|
||||
|
||||
@@ -4,20 +4,16 @@ const { requireUser, requireAdmin } = require('../lib/auth')
|
||||
const { getObjectUrl } = require('../lib/cos')
|
||||
const { writeLog } = require('../lib/log')
|
||||
|
||||
function adminOnly(ctx) {
|
||||
return requireAdmin(ctx)
|
||||
}
|
||||
|
||||
function register(router) {
|
||||
router.get('/api/v1/admin/firmware', async ctx => {
|
||||
const admin = await adminOnly(ctx)
|
||||
const admin = await requireAdmin(ctx)
|
||||
if (!admin) return fail(1002, '未授权,请重新登录')
|
||||
const rows = await query('SELECT firmware_id, version, device_type, cos_key, size_bytes, sha256, status, created_at FROM firmware_files ORDER BY created_at DESC', {})
|
||||
return ok({ records: rows, total: rows.length })
|
||||
})
|
||||
|
||||
router.post('/api/v1/admin/firmware', async ctx => {
|
||||
const admin = await adminOnly(ctx)
|
||||
const admin = await requireAdmin(ctx)
|
||||
if (!admin) return fail(1002, '未授权,请重新登录')
|
||||
const version = String(ctx.body.version || '').trim()
|
||||
const cosKey = String(ctx.body.cos_key || '').trim()
|
||||
@@ -38,7 +34,7 @@ function register(router) {
|
||||
})
|
||||
|
||||
router.post('/api/v1/admin/firmware/:firmware_id/status', async ctx => {
|
||||
const admin = await adminOnly(ctx)
|
||||
const admin = await requireAdmin(ctx)
|
||||
if (!admin) return fail(1002, '未授权,请重新登录')
|
||||
const firmwareId = parseInt(ctx.params.firmware_id, 10)
|
||||
const status = Number(ctx.body.status) === 1 ? 1 : 0
|
||||
@@ -53,12 +49,14 @@ function register(router) {
|
||||
if (!user) return fail(1001, 'invalid_token')
|
||||
const firmware = await one('SELECT * FROM firmware_files WHERE status = 1 ORDER BY created_at DESC LIMIT 1', {})
|
||||
if (!firmware) return ok({ has_update: false })
|
||||
const currentVersion = ctx.query.current_version || ''
|
||||
if (currentVersion && currentVersion === firmware.version) return ok({ has_update: false })
|
||||
return ok({
|
||||
has_update: true,
|
||||
version: firmware.version,
|
||||
size_bytes: firmware.size_bytes,
|
||||
sha256: firmware.sha256,
|
||||
download_url: getObjectUrl(firmware.cos_key, 600)
|
||||
download_url: await getObjectUrl(firmware.cos_key, 600)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
const { one, query } = require('../lib/db')
|
||||
const { one, query, transaction } = require('../lib/db')
|
||||
const { ok, fail } = require('../lib/response')
|
||||
const { requireUser } = require('../lib/auth')
|
||||
const { requireUser, requireAdmin } = require('../lib/auth')
|
||||
const { writeLog } = require('../lib/log')
|
||||
|
||||
const PLANS = {
|
||||
@@ -26,21 +26,22 @@ function register(router) {
|
||||
return ok({ order_id: orderId, payment_params: {}, plan, amount: PLANS[plan].amount })
|
||||
})
|
||||
|
||||
// Temporary: admin-only until payment integration
|
||||
router.post('/api/v1/subscription/verify', async ctx => {
|
||||
const user = await requireUser(ctx)
|
||||
if (!user) return fail(1001, 'invalid_token')
|
||||
const admin = await requireAdmin(ctx)
|
||||
if (!admin) return fail(1002, '未授权,请重新登录')
|
||||
const userId = ctx.body.user_id
|
||||
if (!userId) return fail(2001, 'user_id required')
|
||||
const plan = ctx.body.plan || ctx.body.plan_type || 'monthly'
|
||||
if (!PLANS[plan]) return fail(2001, 'invalid plan')
|
||||
const p = PLANS[plan]
|
||||
await query('UPDATE subscriptions SET status = 2 WHERE user_id = :user_id AND status = 1', { user_id: user.user_id })
|
||||
await query('INSERT INTO subscriptions (user_id, plan, status, amount, order_id, start_time, expire_time) VALUES (:user_id, :plan, 1, :amount, :order_id, NOW(), DATE_ADD(NOW(), INTERVAL :days DAY))', {
|
||||
user_id: user.user_id,
|
||||
plan,
|
||||
amount: p.amount,
|
||||
order_id: ctx.body.order_id || 'ORD' + Date.now(),
|
||||
days: p.days
|
||||
await transaction(async conn => {
|
||||
await conn.execute('UPDATE subscriptions SET status = 2 WHERE user_id = ? AND status = 1', [userId])
|
||||
await conn.execute('INSERT INTO subscriptions (user_id, plan, status, amount, order_id, start_time, expire_time) VALUES (?, ?, 1, ?, ?, NOW(), DATE_ADD(NOW(), INTERVAL ? DAY))', [
|
||||
userId, plan, p.amount, ctx.body.order_id || 'ORD' + Date.now(), p.days
|
||||
])
|
||||
})
|
||||
await writeLog({ user_id: user.user_id, action: 'subscription_verify', detail: '订阅生效: ' + plan, ip: ctx.ip })
|
||||
await writeLog({ admin_id: admin.admin_id, action: 'subscription_verify', detail: '订阅生效: ' + plan + ' user:' + userId, ip: ctx.ip })
|
||||
return ok({ status: 'active', plan, remaining_days: p.days })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,19 +1,10 @@
|
||||
const { query } = require('../lib/db')
|
||||
const { one, query, limitClause } = require('../lib/db')
|
||||
const { ok, fail } = require('../lib/response')
|
||||
const { requireUser } = require('../lib/auth')
|
||||
const { writeLog } = require('../lib/log')
|
||||
|
||||
function toMysqlDate(value) {
|
||||
if (!value) return null
|
||||
const d = new Date(value)
|
||||
if (Number.isNaN(d.getTime())) return null
|
||||
return d.toISOString().slice(0, 19).replace('T', ' ')
|
||||
}
|
||||
const { toMysqlDate } = require('../lib/utils')
|
||||
|
||||
function register(router) {
|
||||
function limitClause(pageSize, offset) {
|
||||
return ' LIMIT ' + Number(pageSize) + ' OFFSET ' + Number(offset)
|
||||
}
|
||||
|
||||
router.get('/api/v1/treatment/history', async ctx => {
|
||||
const user = await requireUser(ctx)
|
||||
@@ -31,6 +22,8 @@ function register(router) {
|
||||
if (!user) return fail(1001, 'invalid_token')
|
||||
const d = ctx.body || {}
|
||||
if (!d.device_id) return fail(2001, 'device_id required')
|
||||
const binding = await one('SELECT binding_id FROM bindings WHERE user_id = :user_id AND device_id = :device_id AND bind_status = 1', { user_id: user.user_id, device_id: d.device_id })
|
||||
if (!binding) return fail(1006, 'device_not_bound')
|
||||
const sessionId = d.session_id || 'SESS' + Date.now()
|
||||
await query(
|
||||
`INSERT INTO treatment_records
|
||||
|
||||
在新工单中引用
屏蔽一个用户