fix(security): 消除服务端 19 处 '|| user-1' 身份回退,堵住游客态数据泄露

- 读路由 7 处回退改 null:游客 joined/created/templates 自然空集、stats 零计数
- 写路由 8 处加 authenticateUser 401 守卫(profile/account/avatar/share/join/checkin/collab)
- admin 守卫路由 3 处改用 req.authUser.id,消除 header 伪造面
- multer 文件名回退改 guest;isJoined 改显式布尔(undefined 会被 JSON 序列化丢弃)
- 并入前期已上线未提交改动:拆书 level/level1 迁移与 memberLevelLabel、登录/资料编辑页、后台管理页
This commit is contained in:
2026-11-15 02:14:18 +08:00
parent 1917675455
commit 33a303b6f1
10 changed files with 716 additions and 154 deletions
+10
View File
@@ -106,6 +106,15 @@ const deleteChaishuTag = (tag) => {
return post('/chaishu/tags/delete', { tag });
};
/**
* 绑定/修改邮箱(邮箱为拆书帮会员身份认定凭证)
* @param {string} email
* @returns {Promise}
*/
const bindEmail = (email) => {
return post('/user/email/bind', { email });
};
module.exports = {
wechatLogin,
login,
@@ -118,4 +127,5 @@ module.exports = {
getUserStats,
getChaishuBranches,
bindChaishu,
bindEmail,
};
+28 -2
View File
@@ -1,5 +1,5 @@
// pages/edit-profile/index.js
const { getProfile, updateProfile, uploadAvatar, getChaishuBranches, bindChaishu, deleteChaishuTag } = require('../../api/user');
const { getProfile, updateProfile, uploadAvatar, getChaishuBranches, bindChaishu, deleteChaishuTag, bindEmail } = require('../../api/user');
const { chooseImages, getFullImageUrl } = require('../../utils/helpers');
Page({
@@ -24,6 +24,7 @@ Page({
chaishuBranchIndex: -1,
chaishuName: '',
binding: false,
bindingEmail: false,
},
onLoad() {
@@ -225,6 +226,30 @@ Page({
}
},
async handleBindEmail() {
const email = (this.data.form.email || '').trim();
if (!email) {
wx.showToast({ title: '请输入邮箱', icon: 'none' });
return;
}
if (this.data.bindingEmail) return;
this.setData({ bindingEmail: true });
try {
const res = await bindEmail(email);
if (res.success) {
const hadEmail = !!this.data.form.email;
wx.showToast({ title: res.data && res.data.chaishuAutoBound ? '绑定成功,已认证拆书帮身份' : (hadEmail ? '换绑成功' : '绑定成功'), icon: 'none' });
this.loadProfile();
} else {
wx.showToast({ title: res.message || '绑定失败', icon: 'none' });
}
} catch (err) {
wx.showToast({ title: err.message || '绑定失败', icon: 'none' });
} finally {
this.setData({ bindingEmail: false });
}
},
async handleSubmit() {
const { form } = this.data;
@@ -238,13 +263,14 @@ Page({
this.setData({ submitting: true });
try {
// 构建提交数据:companies 字段需要转为数组
// 构建提交数据:companies 字段需要转为数组;email 走独立绑定接口,不随资料提交
const submitData = {
...form,
companies: form.companies
? (Array.isArray(form.companies) ? form.companies : [form.companies])
: [],
};
delete submitData.email;
const res = await updateProfile(submitData);
if (res.success) {
wx.showToast({
@@ -21,6 +21,25 @@
/>
</view>
<view class="form-item form-item-column">
<view class="email-label-row">
<text class="form-label">邮箱</text>
<text wx:if="{{form.email}}" class="email-bound-badge">✓ 已绑定</text>
</view>
<view class="email-row">
<input
class="form-input email-input"
value="{{form.email}}"
placeholder="{{form.email ? '如需更换请输入新邮箱' : '绑定后可用邮箱登录'}}"
data-field="email"
bindinput="onInput"
/>
<button class="email-bind-btn" bindtap="handleBindEmail" disabled="{{bindingEmail}}">{{form.email ? '换绑' : '绑定'}}</button>
</view>
<text class="email-tip" wx:if="{{form.email}}">当前已绑定:{{form.email}},可用它直接登录</text>
<text class="email-tip" wx:else>邮箱是拆书帮会员身份认定凭证,绑定后即可用邮箱登录</text>
</view>
<view class="form-item">
<text class="form-label">手机号</text>
<input
@@ -44,31 +63,6 @@
/>
</view>
<view class="form-item">
<text class="form-label">职位</text>
<input
class="form-input"
value="{{form.position}}"
placeholder="请输入职位"
data-field="position"
bindinput="onInput"
/>
</view>
<view class="form-item">
<text class="form-label">拆书家级别</text>
<picker
mode="selector"
range="{{chaishuLevelOptions}}"
bindchange="onChaishuLevelChange"
>
<view class="form-input picker-value">
<text>{{form.chaishuLevel || '请选择拆书家级别'}}</text>
<text class="picker-arrow">›</text>
</view>
</picker>
</view>
<view class="form-item">
<text class="form-label">行业</text>
<input
@@ -91,17 +85,6 @@
/>
</view>
<view class="form-item">
<text class="form-label">邮箱</text>
<input
class="form-input"
value="{{form.email}}"
placeholder="请输入邮箱"
data-field="email"
bindinput="onInput"
/>
</view>
<view class="form-item">
<text class="form-label">专长</text>
<input
@@ -199,3 +199,56 @@
color: #cccccc;
font-size: 32rpx;
}
.email-row {
display: flex;
align-items: center;
width: 100%;
}
.email-label-row {
display: flex;
align-items: center;
width: 100%;
margin-bottom: 12rpx;
}
.email-bound-badge {
margin-left: auto;
font-size: 24rpx;
color: #07c160;
font-weight: 500;
}
.form-item-column {
flex-direction: column;
align-items: stretch;
}
.email-row .email-input {
flex: 1;
}
.email-bind-btn {
flex-shrink: 0;
margin-left: 16rpx;
padding: 0 28rpx;
height: 64rpx;
line-height: 64rpx;
font-size: 26rpx;
color: #ffffff;
background-color: #4A90E2;
border-radius: 32rpx;
}
.email-bind-btn[disabled] {
background-color: #8bb8e0;
}
.email-tip {
display: block;
margin-top: 12rpx;
font-size: 22rpx;
color: #999999;
line-height: 1.5;
}
+44 -12
View File
@@ -26,6 +26,8 @@ const isLoggedIn = () => {
Page({
data: {
loading: false,
showIdentifierLogin: false,
identifier: '',
},
goBack() {
@@ -51,10 +53,11 @@ Page({
// 从 e.detail 提取手机号(如果有)
const phoneNumber = e.detail?.phoneNumber || null;
// 发送 code 和手机号到后端
// 发送 code 和手机号到后端;带 e.detail.phoneNumber 即视为运营商验证过的注册凭证
const res = await post('/auth/login', {
code,
phone: phoneNumber,
phoneVerified: !!e.detail?.phoneNumber,
});
console.log('登录返回:', res);
@@ -80,18 +83,47 @@ Page({
}
},
onReject() {
wx.showModal({
title: '提示',
content: '需要授权才能使用完整功能',
showCancel: false,
});
toggleIdentifierLogin() {
this.setData({ showIdentifierLogin: !this.data.showIdentifierLogin });
},
onShareAppMessage() {
return {
title: '拆约 - 拆书活动邀约平台',
path: '/pages/home/index',
};
onIdentifierInput(e) {
this.setData({ identifier: e.detail.value });
},
async handleIdentifierLogin() {
const raw = (this.data.identifier || '').trim();
if (!raw) {
wx.showToast({ title: '请输入手机号、微信号或邮箱', icon: 'none' });
return;
}
if (this.data.loading) return;
this.setData({ loading: true });
try {
const isEmail = /^[\w.+-]+@[\w-]+(\.[\w-]+)+$/.test(raw);
const isCnPhone = /^1\d{10}$/.test(raw);
if (!isEmail && !isCnPhone) {
wx.showToast({ title: '请输入正确的手机号或邮箱', icon: 'none' });
return;
}
const payload = isEmail ? { email: raw } : { phone: raw };
const res = await post('/auth/login', payload, { showLoading: false });
if (res.success && res.data) {
const { token, user } = res.data;
saveLoginState(token, user?.id, user);
wx.showToast({ title: '登录成功', icon: 'success' });
setTimeout(() => {
wx.switchTab({ url: '/pages/home/index' });
}, 1500);
} else {
wx.showToast({ title: res.message || '登录失败', icon: 'none' });
}
} catch (err) {
console.error('登录异常:', err);
wx.showToast({ title: err.message || '登录失败,请重试', icon: 'none' });
} finally {
this.setData({ loading: false });
}
},
});
+32
View File
@@ -25,6 +25,38 @@
<text class="wechat-btn-text">{{loading ? '登录中...' : '手机号快速验证'}}</text>
</button>
<view class="divider">
<view class="divider-line"></view>
<text class="divider-text">其他登录方式</text>
<view class="divider-line"></view>
</view>
<view class="identifier-login" wx:if="{{showIdentifierLogin}}">
<input
class="identifier-input"
type="text"
value="{{identifier}}"
placeholder="手机号 / 微信号 / 邮箱"
placeholder-class="identifier-placeholder"
bindinput="onIdentifierInput"
confirm-type="done"
bindconfirm="handleIdentifierLogin"
/>
<button
class="identifier-login-btn"
bindtap="handleIdentifierLogin"
disabled="{{loading}}"
>
<text class="identifier-btn-text">{{loading ? '登录中...' : '登录'}}</text>
</button>
<view class="identifier-tip">
<text>邮箱为拆书帮会员身份认定凭证;非会员用手机号或微信号登录</text>
</view>
</view>
<view class="toggle-login-wrap" wx:else>
<text class="toggle-login-text" bindtap="toggleIdentifierLogin">使用手机号 / 微信号 / 邮箱登录</text>
</view>
</view>
<view class="login-footer">
+86
View File
@@ -101,6 +101,92 @@
color: #ffffff;
}
.divider {
display: flex;
align-items: center;
width: 100%;
margin: 48rpx 0 8rpx;
}
.divider-line {
flex: 1;
height: 1rpx;
background-color: #eeeeee;
}
.divider-text {
font-size: 24rpx;
color: #999999;
margin: 0 24rpx;
}
.identifier-login {
display: flex;
flex-direction: column;
width: 100%;
}
.identifier-input {
width: 100%;
height: 96rpx;
box-sizing: border-box;
padding: 0 32rpx;
border: 2rpx solid #eeeeee;
border-radius: 48rpx;
background-color: #f7f8fa;
font-size: 30rpx;
color: #333333;
}
.identifier-placeholder {
color: #bbbbbb;
font-size: 28rpx;
}
.identifier-login-btn {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 96rpx;
margin-top: 24rpx;
background-color: #333333;
border-radius: 48rpx;
border: none;
}
.identifier-login-btn[disabled] {
background-color: #777777;
}
.identifier-btn-text {
font-size: 32rpx;
font-weight: 500;
color: #ffffff;
}
.identifier-tip {
margin-top: 24rpx;
display: flex;
justify-content: center;
}
.identifier-tip text {
font-size: 22rpx;
color: #999999;
}
.toggle-login-wrap {
display: flex;
justify-content: center;
margin-top: 40rpx;
}
.toggle-login-text {
font-size: 26rpx;
color: #4A90E2;
}
.login-tips {
display: flex;
align-items: center;
+153 -50
View File
@@ -35,7 +35,10 @@
.topbar .who a { color: var(--red); cursor: pointer; text-decoration: none; }
.container { max-width: 1100px; margin: 24px auto; padding: 0 24px; }
.stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin-bottom: 22px; }
.stats { display: grid; grid-template-columns: repeat(5, 1fr); gap: 16px; margin-bottom: 22px; }
.tabs { display: flex; gap: 8px; margin-bottom: 16px; }
.tab { border: 1px solid var(--line); background: var(--card); border-radius: 8px; padding: 9px 20px; font-size: 14px; cursor: pointer; color: var(--muted); }
.tab.active { background: var(--brand); border-color: var(--brand); color: #fff; font-weight: 500; }
.stat-card { background: var(--card); border-radius: 12px; padding: 18px 20px; border: 1px solid var(--line); }
.stat-card .num { font-size: 26px; font-weight: 700; }
.stat-card .label { color: var(--muted); font-size: 13px; margin-top: 4px; }
@@ -110,11 +113,15 @@
</div>
<div class="container">
<div class="stats" id="stats"></div>
<div class="panel">
<div class="tabs">
<button class="tab active" id="tabUsers" onclick="switchTab('users')">注册用户</button>
<button class="tab" id="tabChaishu" onclick="switchTab('chaishu')">拆书帮会员</button>
</div>
<div class="panel" id="panelUsers">
<div class="panel-head">
<h2>用户列表</h2>
<div class="search-box">
<input id="searchInput" placeholder="搜索昵称 / 手机号 / 用户ID" onkeydown="if(event.key==='Enter')loadUsers(1)">
<input id="searchInput" placeholder="搜索昵称 / 手机号 / 微信号 / 邮箱 / 用户ID" onkeydown="if(event.key==='Enter')loadUsers(1)">
<button class="btn btn-primary btn-sm" style="width:auto" onclick="loadUsers(1)">搜索</button>
</div>
</div>
@@ -122,7 +129,7 @@
<table>
<thead>
<tr>
<th>用户</th><th>手机号</th><th>活动数</th><th>注册时间</th><th>角色</th><th>操作</th>
<th>用户</th><th>邮箱</th><th>微信号</th><th>手机号</th><th>职业/公司</th><th>籍贯</th><th>专长</th><th>拆书帮</th><th>活动数</th><th>注册时间</th><th>角色</th><th>操作</th>
</tr>
</thead>
<tbody id="userRows"></tbody>
@@ -135,6 +142,31 @@
<button id="nextBtn" onclick="loadUsers(page+1)">下一页</button>
</div>
</div>
<div class="panel hidden" id="panelChaishu">
<div class="panel-head">
<h2>拆书帮会员(微信号 / 邮箱联系方式)</h2>
<div class="search-box">
<input id="chaishuSearchInput" placeholder="搜索姓名 / 微信号 / 邮箱 / 城市 / 分舵" onkeydown="if(event.key==='Enter')loadChaishu(1)">
<button class="btn btn-primary btn-sm" style="width:auto" onclick="loadChaishu(1)">搜索</button>
</div>
</div>
<div style="overflow-x:auto">
<table>
<thead>
<tr>
<th>姓名</th><th>城市/分舵</th><th>等级</th><th>微信号</th><th>邮箱</th><th>师父</th><th>标签</th>
</tr>
</thead>
<tbody id="chaishuRows"></tbody>
</table>
</div>
<div id="chaishuEmptyTip" class="empty hidden">暂无会员</div>
<div class="pager">
<span id="chaishuPageInfo"></span>
<button id="chaishuPrevBtn" onclick="loadChaishu(chaishuPage-1)">上一页</button>
<button id="chaishuNextBtn" onclick="loadChaishu(chaishuPage+1)">下一页</button>
</div>
</div>
</div>
</div>
@@ -151,14 +183,23 @@
</div>
</div>
<!-- 角色变更确认弹窗 -->
<div class="modal-mask" id="roleModal">
<div class="modal">
<h3 id="roleTitle">确认操作</h3>
<div id="roleMsg" style="font-size:14px;line-height:1.7;white-space:pre-line;"></div>
<div style="display:flex;gap:10px;justify-content:flex-end;margin-top:20px;">
<button class="btn" onclick="closeRoleModal()">取消</button>
<button class="btn btn-primary" id="roleConfirmBtn" onclick="confirmRole()">确认</button>
<div class="modal-mask" id="userEditModal">
<div class="modal" style="max-width:520px">
<h3 id="eu-title">编辑用户</h3>
<div class="field"><label>昵称</label><input id="eu-nickname"></div>
<div class="field"><label>邮箱(身份标识,慎重修改)</label><input id="eu-email" placeholder="如:koningyang@outlook.com"></div>
<div class="field"><label>微信号</label><input id="eu-weixin" placeholder="如:kenyanghui"></div>
<div class="field"><label>手机号</label><input id="eu-phone"></div>
<div class="field"><label>职位</label><input id="eu-position" placeholder="如:AI学习力教练"></div>
<div class="field"><label>行业</label><input id="eu-industry" placeholder="如:教育"></div>
<div class="field"><label>籍贯</label><input id="eu-hometown" placeholder="如:广东广州"></div>
<div class="field"><label>公司/机构(多个用、分隔)</label><input id="eu-companies" placeholder="如:拆书帮、AI贝"></div>
<div class="field"><label>专长标签(用、分隔)</label><input id="eu-expertise" placeholder="如:AI教育、拆书"></div>
<div class="field"><label>拆书帮 UID(留空即解绑)</label><input id="eu-uid" placeholder="如:28646"></div>
<div class="login-error" id="euError"></div>
<div style="display:flex;gap:8px">
<button class="btn btn-primary" onclick="saveUser()">保存</button>
<button class="btn" onclick="document.getElementById('userEditModal').classList.remove('show')">取消</button>
</div>
</div>
</div>
@@ -170,7 +211,17 @@ const API = location.origin;
let token = sessionStorage.getItem('admin_token') || '';
let mustChange = false;
let page = 1, pageSize = 20, total = 0;
const userCache = {};
let chaishuPage = 1, chaishuTotal = 0;
let currentTab = 'users';
function switchTab(tab) {
currentTab = tab;
document.getElementById('tabUsers').classList.toggle('active', tab === 'users');
document.getElementById('tabChaishu').classList.toggle('active', tab === 'chaishu');
document.getElementById('panelUsers').classList.toggle('hidden', tab !== 'users');
document.getElementById('panelChaishu').classList.toggle('hidden', tab !== 'chaishu');
if (tab === 'chaishu' && !chaishuTotal) loadChaishu(1);
}
// ---------- 工具 ----------
function showToast(msg) {
@@ -228,7 +279,7 @@ async function loadStats() {
const d = r.data;
const cards = [
[d.users, '注册用户'], [d.admins, '活动管理员'],
[d.activities, '活动总数'], [d.activeActivities, '进行中活动'],
[d.chaishuMembers, '拆书帮会员'], [d.activities, '活动总数'], [d.activeActivities, '进行中活动'],
];
document.getElementById('stats').innerHTML = cards.map(([n, l]) =>
`<div class="stat-card"><div class="num">${n}</div><div class="label">${l}</div></div>`).join('');
@@ -242,7 +293,6 @@ async function loadUsers(p) {
if (!r.success) { showToast(r.message || '加载失败'); return; }
total = r.data.total;
const rows = r.data.list;
rows.forEach(u => { userCache[u.id] = u.nickname || '未设置昵称'; });
const tbody = document.getElementById('userRows');
document.getElementById('emptyTip').classList.toggle('hidden', rows.length > 0);
tbody.innerHTML = rows.map(u => `
@@ -255,14 +305,21 @@ async function loadUsers(p) {
<span>${escapeHtml(u.nickname || '未设置昵称')}</span>
</div>
</td>
<td class="muted">${escapeHtml(u.email || '-')}</td>
<td class="muted">${escapeHtml(u.weixin || '-')}</td>
<td class="muted">${escapeHtml(u.phone || '-')}</td>
<td class="muted">${escapeHtml([u.position, u.industry].filter(Boolean).join(' · ') || '-')}<br><span class="tag" style="background:#f0f4f8;color:#5a6b7d">${escapeHtml((u.companies || []).join('、') || '无公司')}</span></td>
<td class="muted">${escapeHtml(u.hometown || '-')}</td>
<td class="muted">${escapeHtml((u.expertise || '').split(/[,,、;;\s]+/).filter(Boolean).slice(0,3).join(' · ') || '-')}</td>
<td>${u.chaishuUid ? `<span class="tag ${u.chaishuVerified ? 'tag-admin' : 'tag-user'}">${u.chaishuLevel ? escapeHtml(u.chaishuLevel) : '已绑定'}</span>` : '<span class="muted">-</span>'}</td>
<td class="muted">创建 ${u.createdCount} / 参加 ${u.joinedCount}</td>
<td class="muted">${fmtDate(u.createdAt)}</td>
<td>${u.isAdmin ? '<span class="tag tag-admin">管理员</span>' : '<span class="tag tag-user">普通用户</span>'}</td>
<td>
<button class="btn btn-sm" style="background:#1a56b0;color:#fff" onclick="openEditUser('${escapeHtml(u.id)}')">编辑</button>
${u.isAdmin
? `<button class="btn btn-sm btn-revoke" onclick="toggleRole('${u.id}','user')">取消管理员</button>`
: `<button class="btn btn-sm btn-grant" onclick="toggleRole('${u.id}','admin')">设为管理员</button>`}
? `<button class="btn btn-sm btn-revoke" onclick="toggleRole('${u.id}','user','${escapeHtml(u.nickname)}')">取消管理员</button>`
: `<button class="btn btn-sm btn-grant" onclick="toggleRole('${u.id}','admin','${escapeHtml(u.nickname)}')">设为管理员</button>`}
</td>
</tr>`).join('');
const pages = Math.max(1, Math.ceil(total / pageSize));
@@ -271,41 +328,41 @@ async function loadUsers(p) {
document.getElementById('nextBtn').disabled = page >= pages;
}
function escapeHtml(s) {
return String(s || '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
return String(s || '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}));
}
let pendingRole = null; // { id, role }
function toggleRole(id, role) {
const nickname = userCache[id] || id;
pendingRole = { id, role };
document.getElementById('roleTitle').textContent = role === 'admin' ? '设为管理员' : '取消管理员';
document.getElementById('roleMsg').textContent = role === 'admin'
? `确定将「${nickname}」设为管理员吗?\n设为管理员后,该用户可以在小程序中创建、编辑、删除活动。`
: `确定取消「${nickname}」的管理员权限吗?\n取消后,该用户将无法再创建活动(已有活动不受影响)。`;
document.getElementById('roleModal').classList.add('show');
async function loadChaishu(p) {
if (p < 1) return;
chaishuPage = p;
const search = document.getElementById('chaishuSearchInput').value.trim();
const r = await api(`/api/admin/chaishu-members?page=${chaishuPage}&pageSize=${pageSize}&search=${encodeURIComponent(search)}`);
if (!r.success) { showToast(r.message || '加载失败'); return; }
chaishuTotal = r.data.total;
const rows = r.data.list;
const tbody = document.getElementById('chaishuRows');
document.getElementById('chaishuEmptyTip').classList.toggle('hidden', rows.length > 0);
tbody.innerHTML = rows.map(m => `
<tr>
<td><div class="nick"><span class="avatar-fallback">${escapeHtml((m.name || '?')[0])}</span><span>${escapeHtml(m.name || '未署名')}</span></div></td>
<td class="muted">${escapeHtml(m.city || '-')}${m.branch ? ' · ' + escapeHtml(m.branch) : ''}</td>
<td>${(() => { const lv = Number(m.level)||1; const no = lv===4?m.level3:lv===3?m.level2:lv===2?m.level1:''; const nm = lv===4?'三级':lv===3?'二级':lv===2?'一级':'学员'; const cls = lv===4?'tag tag-admin':lv===3?'tag tag-user':lv===2?'tag':'tag'; const sty = lv>=2?'':lv===1?'background:#f0f0f0;color:#888':''; return no ? `<span class="${cls}" style="${sty}">${nm}·${escapeHtml(no)}</span>` : `<span class="tag" style="${sty}">${nm}</span>`; })()}</td>
<td class="muted">${escapeHtml(m.weixin || '-')}</td>
<td class="muted">${escapeHtml(m.email || '-')}</td>
<td class="muted">${escapeHtml(m.shifuName || '-')}</td>
<td>${(m.tags || []).slice(0, 2).map(t => `<span class="tag tag-user">${escapeHtml(t)}</span>`).join(' ')}${(m.tags || []).length > 2 ? ' …' : ''}</td>
</tr>`).join('');
const pages = Math.max(1, Math.ceil(chaishuTotal / pageSize));
document.getElementById('chaishuPageInfo').textContent = `第 ${chaishuPage} / ${pages} 页 · 共 ${chaishuTotal} 人`;
document.getElementById('chaishuPrevBtn').disabled = chaishuPage <= 1;
document.getElementById('chaishuNextBtn').disabled = chaishuPage >= pages;
}
function closeRoleModal() {
document.getElementById('roleModal').classList.remove('show');
pendingRole = null;
}
async function confirmRole() {
if (!pendingRole) return;
const { id, role } = pendingRole;
const btn = document.getElementById('roleConfirmBtn');
btn.disabled = true;
try {
const r = await api(`/api/admin/users/${id}/role`, { method: 'PUT', body: { role } });
if (r.success) {
closeRoleModal();
showToast(role === 'admin' ? '已设为管理员' : '已取消管理员');
loadUsers(page); loadStats();
} else {
showToast(r.message || '操作失败');
}
} catch (e) {
showToast('网络错误,请稍后重试');
} finally {
btn.disabled = false;
}
async function toggleRole(id, role, nickname) {
const action = role === 'admin' ? `确定将「${nickname}」设为管理员吗?\n设为管理员后,该用户可以在小程序中创建、编辑、删除活动。`
: `确定取消「${nickname}」的管理员权限吗?\n取消后,该用户将无法再创建活动(已有活动不受影响)。`;
if (!confirm(action)) return;
const r = await api(`/api/admin/users/${id}/role`, { method: 'PUT', body: { role } });
if (r.success) { showToast(role === 'admin' ? '已设为管理员' : '已取消管理员'); loadUsers(page); loadStats(); }
else showToast(r.message || '操作失败');
}
// ---------- 改密 ----------
@@ -328,6 +385,52 @@ async function doChangePwd() {
} else errEl.textContent = r.message || '修改失败';
}
// ---------- 用户编辑弹窗 ----------
let editingUserId = null;
async function openEditUser(id) {
const r = await api(`/api/admin/users?page=1&pageSize=100&search=${encodeURIComponent(id)}`);
if (!r.success || !r.data.list.length) { showToast('未找到用户'); return; }
const u = r.data.list.find(x => x.id === id);
if (!u) { showToast('未找到用户'); return; }
editingUserId = id;
document.getElementById('eu-title').textContent = `编辑用户:${u.nickname}`;
document.getElementById('eu-nickname').value = u.nickname || '';
document.getElementById('eu-weixin').value = u.weixin || '';
document.getElementById('eu-phone').value = u.phone || '';
document.getElementById('eu-position').value = u.position || '';
document.getElementById('eu-industry').value = u.industry || '';
document.getElementById('eu-hometown').value = u.hometown || '';
document.getElementById('eu-email').value = u.email || '';
document.getElementById('eu-email').readOnly = false;
document.getElementById('eu-expertise').value = u.expertise || '';
document.getElementById('eu-companies').value = (u.companies || []).join('、');
document.getElementById('eu-uid').value = u.chaishuUid || '';
document.getElementById('userEditModal').classList.add('show');
}
async function saveUser() {
if (!editingUserId) return;
const body = {
nickname: document.getElementById('eu-nickname').value.trim(),
email: document.getElementById('eu-email').value.trim(),
weixin: document.getElementById('eu-weixin').value.trim(),
phone: document.getElementById('eu-phone').value.trim(),
position: document.getElementById('eu-position').value.trim(),
industry: document.getElementById('eu-industry').value.trim(),
hometown: document.getElementById('eu-hometown').value.trim(),
expertise: document.getElementById('eu-expertise').value.trim(),
companies: document.getElementById('eu-companies').value.split(/[,,、]/).map(s => s.trim()).filter(Boolean),
chaishu_uid: document.getElementById('eu-uid').value.trim(),
};
const r = await api(`/api/admin/users/${editingUserId}`, { method: 'PUT', body });
if (r.success) {
showToast('已保存');
document.getElementById('userEditModal').classList.remove('show');
loadUsers(page);
} else {
showToast(r.message || '保存失败');
}
}
// ---------- 启动 ----------
(async function init() {
if (!token) return;
@@ -0,0 +1,169 @@
#!/usr/bin/env node
/**
* 游客态 fallback 污染修复补丁(19 处)
* 分类:A 读路由 7 处 → || null(游客自然空集/零计数/false)
* B 写路由 8 处 → authenticateUser 401(表均 user_id NOT NULL)
* C admin 守卫路由 3 处 → req.authUser.id(守卫已注入,消除 header 依赖)
* D multer 文件名 1 处 → || 'guest'(防御性命名)
* 安全机制:所有锚点必须唯一命中,任一失败整体中止、不写文件。
*/
const fs = require('fs');
const path = require('path');
const file = process.argv[2] || path.join(__dirname, '..', 'server.js');
let src = fs.readFileSync(file, 'utf8');
const original = src;
const UID = `req.headers['x-user-id'] || 'user-1'`;
const AUTH401 = [
`const authUser = authenticateUser(req);`,
` if (!authUser) {`,
` return res.status(401).json({ success: false, message: '请先登录' });`,
` }`,
` const userId = authUser.id;`,
].join('\n');
const patches = [
// D. multer 文件名 @195
{
id: 'D-multer-filename',
anchor: ` filename: (req, file, cb) => {\n const userId = ${UID};`,
replace: ` filename: (req, file, cb) => {\n const userId = req.headers['x-user-id'] || 'guest';`,
},
// A. GET /user/profile @656
{
id: 'A-get-profile',
anchor: `app.get('/user/profile', (req, res) => {\n try {\n const userId = ${UID};`,
replace: `app.get('/user/profile', (req, res) => {\n try {\n const userId = req.headers['x-user-id'] || null;`,
},
// B. PUT /user/profile @671
{
id: 'B-put-profile',
anchor: `app.put('/user/profile', (req, res) => {\n try {\n const userId = ${UID};`,
replace: `app.put('/user/profile', (req, res) => {\n try {\n ${AUTH401}`,
},
// A. GET /user/stats @697
{
id: 'A-get-stats',
anchor: `app.get('/user/stats', (req, res) => {\n try {\n const userId = ${UID};`,
replace: `app.get('/user/stats', (req, res) => {\n try {\n const userId = req.headers['x-user-id'] || null;`,
},
// B. DELETE /user/account @710
{
id: 'B-delete-account',
anchor: `app.delete('/user/account', (req, res) => {\n try {\n const userId = ${UID};`,
replace: `app.delete('/user/account', (req, res) => {\n try {\n ${AUTH401}`,
},
// B. POST /user/avatar @723(multer 前拦截防孤儿文件)
{
id: 'B-post-avatar',
anchor: `app.post('/user/avatar', (req, res, next) => {\n req.uploadSubDir = 'avatars';\n next();\n}, upload.single('file'), (req, res) => {\n try {\n if (!req.file) {\n return res.json({ success: false, message: '请选择要上传的图片' });\n }\n const userId = ${UID};`,
replace: `app.post('/user/avatar', (req, res, next) => {\n const authUser = authenticateUser(req);\n if (!authUser) {\n return res.status(401).json({ success: false, message: '请先登录' });\n }\n req.authUser = authUser;\n req.uploadSubDir = 'avatars';\n next();\n}, upload.single('file'), (req, res) => {\n try {\n if (!req.file) {\n return res.json({ success: false, message: '请选择要上传的图片' });\n }\n const userId = req.authUser.id;`,
},
// A. GET /user/profile/completion @747
{
id: 'A-get-completion',
anchor: `app.get('/user/profile/completion', (req, res) => {\n try {\n const userId = ${UID};`,
replace: `app.get('/user/profile/completion', (req, res) => {\n try {\n const userId = req.headers['x-user-id'] || null;`,
},
// A. GET /activities @777(tab 解构在 userId 前一天然隔离锚点)
{
id: 'A-get-activities',
anchor: ` const { tab = 'latest', page, pageSize } = req.query;\n const userId = ${UID};`,
replace: ` const { tab = 'latest', page, pageSize } = req.query;\n const userId = req.headers['x-user-id'] || null;`,
},
// A. GET /activities/templates @846
{
id: 'A-get-templates',
anchor: `app.get('/activities/templates', (req, res) => {\n try {\n const userId = ${UID};`,
replace: `app.get('/activities/templates', (req, res) => {\n try {\n const userId = req.headers['x-user-id'] || null;`,
},
// A. GET /activities/:id @892
{
id: 'A-get-activity-detail',
anchor: `app.get('/activities/:id', (req, res) => {\n try {\n const { id } = req.params;\n const userId = ${UID};`,
replace: `app.get('/activities/:id', (req, res) => {\n try {\n const { id } = req.params;\n const userId = req.headers['x-user-id'] || null;`,
},
// C. POST /activities @968
{
id: 'C-post-activities',
anchor: `app.post('/activities', requireActivityAdmin, (req, res) => {\n try {\n const userId = ${UID};`,
replace: `app.post('/activities', requireActivityAdmin, (req, res) => {\n try {\n const userId = req.authUser.id;`,
},
// C. PUT /activities/:id @1002
{
id: 'C-put-activity',
anchor: `app.put('/activities/:id', requireActivityAdmin, (req, res) => {\n try {\n const { id } = req.params;\n const userId = ${UID};`,
replace: `app.put('/activities/:id', requireActivityAdmin, (req, res) => {\n try {\n const { id } = req.params;\n const userId = req.authUser.id;`,
},
// B. POST /activities/:id/share @1041
{
id: 'B-post-share',
anchor: `app.post('/activities/:id/share', (req, res) => {\n try {\n const { id } = req.params;\n const userId = ${UID};`,
replace: `app.post('/activities/:id/share', (req, res) => {\n try {\n const { id } = req.params;\n ${AUTH401}`,
},
// B. POST /activities/:id/join @1061
{
id: 'B-post-join',
anchor: `app.post('/activities/:id/join', (req, res) => {\n try {\n const { id } = req.params;\n const userId = ${UID};`,
replace: `app.post('/activities/:id/join', (req, res) => {\n try {\n const { id } = req.params;\n ${AUTH401}`,
},
// B. DELETE /activities/:id/join @1100
{
id: 'B-delete-join',
anchor: `app.delete('/activities/:id/join', (req, res) => {\n try {\n const { id } = req.params;\n const userId = ${UID};`,
replace: `app.delete('/activities/:id/join', (req, res) => {\n try {\n const { id } = req.params;\n ${AUTH401}`,
},
// A. GET /activities/:id/checkin-status @1122
{
id: 'A-get-checkin-status',
anchor: `app.get('/activities/:id/checkin-status', (req, res) => {\n try {\n const { id } = req.params;\n const userId = ${UID};`,
replace: `app.get('/activities/:id/checkin-status', (req, res) => {\n try {\n const { id } = req.params;\n const userId = req.headers['x-user-id'] || null;`,
},
// B. POST /activities/:id/checkin @1214
{
id: 'B-post-checkin',
anchor: `app.post('/activities/:id/checkin', (req, res) => {\n try {\n const { id } = req.params;\n const userId = ${UID};`,
replace: `app.post('/activities/:id/checkin', (req, res) => {\n try {\n const { id } = req.params;\n ${AUTH401}`,
},
// C. DELETE /activities/:id @1239
{
id: 'C-delete-activity',
anchor: `app.delete('/activities/:id', requireActivityAdmin, (req, res) => {\n try {\n const { id } = req.params;\n const userId = ${UID};`,
replace: `app.delete('/activities/:id', requireActivityAdmin, (req, res) => {\n try {\n const { id } = req.params;\n const userId = req.authUser.id;`,
},
// B. POST /ai/collaboration-analysis @1355
{
id: 'B-post-collab',
anchor: `app.post('/ai/collaboration-analysis', async (req, res) => {\n try {\n const userId = ${UID};`,
replace: `app.post('/ai/collaboration-analysis', async (req, res) => {\n try {\n ${AUTH401}`,
},
];
// 第一遍:全量校验锚点唯一性
const failures = [];
for (const p of patches) {
const n = src.split(p.anchor).length - 1;
if (n !== 1) failures.push(`${p.id}: 锚点命中 ${n} 次(需 1 次)`);
}
if (failures.length) {
console.error('补丁中止,锚点校验失败:');
failures.forEach((f) => console.error(' ' + f));
process.exit(1);
}
// 第二遍:逐个替换
for (const p of patches) {
src = src.replace(p.anchor, p.replace);
console.log(`✓ ${p.id}`);
}
if (src.split(UID).length - 1 !== 0) {
console.error(`中止:替换后仍残留 ${UID} 共 ${src.split(UID).length - 1} 处`);
process.exit(1);
}
fs.writeFileSync(file, src);
console.log(`\n19 处补丁全部写入 ${file}`);
console.log(`残留 fallback 检查:${(src.match(/\|\| 'user-1'/g) || []).length} 处(预期 0)`);
console.log(`新增 401 守卫:${(src.match(/authUser = authenticateUser\(req\)/g) || []).length} 处(预期 9:8 路由 + avatar 守卫中间件)`);
+122 -54
View File
@@ -172,7 +172,6 @@ async function generateParticipantSuggestion(participant, activityTitle) {
// 中间件
app.use(cors());
app.use(cors());
app.use(express.json());
// 静态文件服务 - 用于上传的图片
@@ -193,7 +192,7 @@ const storage = multer.diskStorage({
cb(null, dir);
},
filename: (req, file, cb) => {
const userId = req.headers['x-user-id'] || 'user-1';
const userId = req.headers['x-user-id'] || 'guest';
const ext = path.extname(file.originalname) || '.jpg';
cb(null, `${userId}_${Date.now()}${ext}`);
}
@@ -284,6 +283,8 @@ function initDatabase() {
shifu_id TEXT DEFAULT '',
tudi_names TEXT DEFAULT '[]',
tudi_ids TEXT DEFAULT '[]',
level INTEGER DEFAULT 1,
level1 TEXT DEFAULT '',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_chaishu_branch ON chaishu_members(branch);
@@ -291,6 +292,17 @@ function initDatabase() {
console.log('已创建 chaishu_members 表');
}
// 迁移:chaishu_members 表添加 level/level1 字段(老库补列,幂等)
const chaishuCols = db.prepare('PRAGMA table_info(chaishu_members)').all();
if (!chaishuCols.some(col => col.name === 'level')) {
db.prepare('ALTER TABLE chaishu_members ADD COLUMN level INTEGER DEFAULT 1').run();
console.log('已添加 chaishu_members.level 字段');
}
if (!chaishuCols.some(col => col.name === 'level1')) {
db.prepare("ALTER TABLE chaishu_members ADD COLUMN level1 TEXT DEFAULT ''").run();
console.log('已添加 chaishu_members.level1 字段');
}
// 迁移:users 表添加拆书帮身份字段
const userInfoCols = db.prepare('PRAGMA table_info(users)').all();
if (!userInfoCols.some(col => col.name === 'weixin')) {
@@ -420,6 +432,14 @@ function getUserWithCompanies(userId) {
}
// ==================== 拆书帮会员自动绑定与补全 ====================
// 等级展示:以 level 段位为准(4=三级 3=二级 2=一级 1=学员),编号作补充展示,学员不显编号
function memberLevelLabel(member) {
const lvl = Number(member && member.level) || 1;
const name = lvl === 4 ? '三级' : lvl === 3 ? '二级' : lvl === 2 ? '一级' : '学员';
const no = lvl === 4 ? member.level3 : lvl === 3 ? member.level2 : lvl === 2 ? member.level1 : '';
return lvl >= 2 ? `${name}(${no})`.replace(/\(\)$/, '') : name;
}
// 按 微信号/邮箱/手机号 匹配 chaishu_members;命中即绑定 uid 并回填 users 空字段(不覆盖已有值)
function bindChaishuMember(user, hints = {}) {
if (!user || !user.id) return null;
@@ -433,11 +453,8 @@ function bindChaishuMember(user, hints = {}) {
if (!member && phone) member = db.prepare("SELECT * FROM chaishu_members WHERE email = ?").get(phone); // 少数会员邮箱字段存的是手机号
if (!member) return null;
// 回填规则:只填空字段;等级以 level 段位为准(4=三级 3=二级 2=一级 1=学员),编号作补充展示
const lvl = Number(member.level) || 1;
const lvlName = lvl === 4 ? '三级' : lvl === 3 ? '二级' : lvl === 2 ? '一级' : '学员';
const lvlNo = lvl === 4 ? member.level3 : lvl === 2 ? member.level2 : lvl === 1 ? member.level1 : '';
const level = lvl >= 2 ? `${lvlName}(${lvlNo})`.replace(/\(\)$/, '') : lvlName;
// 回填规则:只填空字段;等级统一走 memberLevelLabel(level 段位判级,编号作补充展示)
const level = memberLevelLabel(member);
const now = new Date().toISOString();
db.prepare(`
UPDATE users SET
@@ -487,7 +504,11 @@ app.use((req, res, next) => {
// 登录
app.post('/auth/login', async (req, res) => {
try {
const { code, phone, email } = req.body;
const { code, phone: rawPhone, email: rawEmail } = req.body;
// 归一化:手机号栏误填邮箱 → 分流到邮箱登录,避免邮箱串被写入 weixin
const looksEmail = (v) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(v || '').trim());
const email = rawEmail || (looksEmail(rawPhone) ? String(rawPhone).trim().toLowerCase() : undefined);
const phone = looksEmail(rawPhone) ? undefined : rawPhone;
if (!code && !phone && !email) {
return res.json({ success: false, message: '缺少登录凭证' });
@@ -531,13 +552,13 @@ app.post('/auth/login', async (req, res) => {
}
const userId = uuidv4();
const now = new Date().toISOString();
const memberLevel = member.level3 ? `三级(${member.level3})` : (member.level2 ? `二级(${member.level2})` : (member.level1 ? `一级(${member.level1})` : ''));
db.prepare(`
INSERT INTO users (id, openid, nickname, avatar_url, phone, weixin, position, industry, hometown, email, expertise, chaishu_uid, chaishu_verified, chaishu_level, created_at, updated_at)
VALUES (?, ?, ?, '', '', ?, '', '', '', ?, ?, ?, 1, ?, ?, ?)
`).run(userId, openid || null, member.name || normEmail.split('@')[0], member.weixin || '', normEmail,
`).run(userId, openid || null, member.name || normEmail.split('@')[0], member.weixin || '',
normEmail,
(safeParseJson(member.tags, []) || []).join('、') || member.description || '',
member.uid, memberLevel, now, now);
member.uid, memberLevelLabel(member), now, now);
user = db.prepare('SELECT * FROM users WHERE id = ?').get(userId);
} else if (openid && !user.openid) {
// 账号尚无 openid 且无他人占用时补绑,便于后续纯微信登录识别
@@ -555,29 +576,20 @@ app.post('/auth/login', async (req, res) => {
});
}
// 手机号或微信号登录:优先手机号,其次微信号(支持微信小程序登录),有则登录;未知手机号可注册,未知微信号拒绝(防打错字产生孤儿账号)
// 手机号或微信号登录:优先手机号,其次微信号(支持微信小程序登录),有则登录,无则注册
if (phone) {
const isPhone = /^1\d{10}$/.test(phone);
if (!isPhone && phone.includes('@')) {
return res.json({ success: false, message: '请输入完整邮箱(含 @),或使用手机号/微信号登录' });
}
let user = db.prepare('SELECT * FROM users WHERE phone = ?').get(phone);
const weixinUser = !user ? db.prepare("SELECT * FROM users WHERE weixin = ? AND weixin != ''").get(phone) : null;
user = user || weixinUser;
if (!user) {
// 手动输入的未知标识一律拒绝建号(防乱输注册垃圾账号);注册仅两条路:运营商验证手机号按钮 / 会员邮箱认定
const phoneVerified = req.body && req.body.phoneVerified === true;
if (!phoneVerified || !isPhone) {
const kind = isPhone ? '手机号' : '微信号';
return res.json({ success: false, message: `该${kind}未注册。新用户请点上方「手机号快速验证」注册;拆书帮会员可用邮箱直接登录` });
}
// 运营商验证过的手机号 → 创建新用户
// 没注册过 → 创建新用户(输入可能是手机号或微信号)
const userId = uuidv4();
const now = new Date().toISOString();
const isPhone = /^1\d{10}$/.test(phone);
db.prepare(`
INSERT INTO users (id, openid, nickname, avatar_url, phone, weixin, position, industry, hometown, email, expertise, created_at, updated_at)
VALUES (?, ?, ?, '', ?, ?, '', '', '', '', '', ?, ?)
`).run(userId, openid || '', `用户${phone.slice(-4)}`, phone, '', now, now);
`).run(userId, openid || '', isPhone ? `用户${phone.slice(-4)}` : phone, isPhone ? phone : '', isPhone ? '' : phone, now, now);
user = db.prepare('SELECT * FROM users WHERE id = ?').get(userId);
} else {
if (openid && user.openid !== openid) {
@@ -589,7 +601,7 @@ app.post('/auth/login', async (req, res) => {
if (/^1\d{10}$/.test(phone) && user.phone !== phone) {
db.prepare('UPDATE users SET phone = ?, updated_at = ? WHERE id = ?').run(phone, new Date().toISOString(), user.id);
user.phone = phone;
} else if (!/^1\d{10}$/.test(phone) && user.weixin !== phone) {
} else if (!/^1\d{10}$/.test(phone) && !looksEmail(phone) && user.weixin !== phone) {
db.prepare('UPDATE users SET weixin = ?, updated_at = ? WHERE id = ?').run(phone, new Date().toISOString(), user.id);
user.weixin = phone;
}
@@ -641,7 +653,7 @@ app.post('/auth/logout', (req, res) => {
// 获取用户资料
app.get('/user/profile', (req, res) => {
try {
const userId = req.headers['x-user-id'] || 'user-1';
const userId = req.headers['x-user-id'] || null;
const user = getUserWithCompanies(userId);
if (!user) {
return res.json({ success: false, message: '用户不存在' });
@@ -656,7 +668,11 @@ app.get('/user/profile', (req, res) => {
// 更新用户资料(email 为源头身份锚点不可修改;未传字段保持原值)
app.put('/user/profile', (req, res) => {
try {
const userId = req.headers['x-user-id'] || 'user-1';
const authUser = authenticateUser(req);
if (!authUser) {
return res.status(401).json({ success: false, message: '请先登录' });
}
const userId = authUser.id;
const { nickname, position, chaishu_level, industry, hometown, expertise, weixin, phone, companies } = req.body;
const now = new Date().toISOString();
@@ -682,7 +698,7 @@ app.put('/user/profile', (req, res) => {
// 获取用户统计
app.get('/user/stats', (req, res) => {
try {
const userId = req.headers['x-user-id'] || 'user-1';
const userId = req.headers['x-user-id'] || null;
const createdCount = db.prepare('SELECT COUNT(*) as count FROM activities WHERE creator_id = ?').get(userId);
const joinedCount = db.prepare("SELECT COUNT(*) as count FROM activity_participants WHERE user_id = ? AND status != 'cancelled'").get(userId);
res.json({ success: true, data: { createdCount: createdCount.count, joinedCount: joinedCount.count } });
@@ -695,7 +711,11 @@ app.get('/user/stats', (req, res) => {
// 注销账号
app.delete('/user/account', (req, res) => {
try {
const userId = req.headers['x-user-id'] || 'user-1';
const authUser = authenticateUser(req);
if (!authUser) {
return res.status(401).json({ success: false, message: '请先登录' });
}
const userId = authUser.id;
db.prepare('DELETE FROM user_companies WHERE user_id = ?').run(userId);
db.prepare('DELETE FROM activity_participants WHERE user_id = ?').run(userId);
db.prepare('DELETE FROM users WHERE id = ?').run(userId);
@@ -709,6 +729,11 @@ app.delete('/user/account', (req, res) => {
// 上传头像
// 上传用户头像
app.post('/user/avatar', (req, res, next) => {
const authUser = authenticateUser(req);
if (!authUser) {
return res.status(401).json({ success: false, message: '请先登录' });
}
req.authUser = authUser;
req.uploadSubDir = 'avatars';
next();
}, upload.single('file'), (req, res) => {
@@ -716,7 +741,7 @@ app.post('/user/avatar', (req, res, next) => {
if (!req.file) {
return res.json({ success: false, message: '请选择要上传的图片' });
}
const userId = req.headers['x-user-id'] || 'user-1';
const userId = req.authUser.id;
const avatarUrl = `/uploads/avatars/${req.file.filename}`;
// 更新用户头像
@@ -732,7 +757,7 @@ app.post('/user/avatar', (req, res, next) => {
// 获取资料完善度
app.get('/user/profile/completion', (req, res) => {
try {
const userId = req.headers['x-user-id'] || 'user-1';
const userId = req.headers['x-user-id'] || null;
const user = db.prepare('SELECT * FROM users WHERE id = ?').get(userId);
if (!user) {
@@ -764,7 +789,7 @@ app.get('/user/profile/completion', (req, res) => {
app.get('/activities', (req, res) => {
try {
const { tab = 'latest', page, pageSize } = req.query;
const userId = req.headers['x-user-id'] || 'user-1';
const userId = req.headers['x-user-id'] || null;
const pageNum = parseInt(page) || 1;
const pageSizeNum = parseInt(pageSize) || 10;
const offset = (pageNum - 1) * pageSizeNum;
@@ -817,7 +842,7 @@ app.get('/activities', (req, res) => {
createdAt: activity.created_at,
updatedAt: activity.updated_at,
tags: tags.map(t => t.tag_name),
isJoined: participant && participant.status !== 'cancelled'
isJoined: !!(participant && participant.status !== 'cancelled')
};
});
@@ -831,7 +856,7 @@ app.get('/activities', (req, res) => {
// 获取活动模板 - 必须在 /activities/:id 之前
app.get('/activities/templates', (req, res) => {
try {
const userId = req.headers['x-user-id'] || 'user-1';
const userId = req.headers['x-user-id'] || null;
const activities = db.prepare(`
SELECT DISTINCT a.id, a.title, a.cover_url, a.description, a.location, a.start_time, a.duration, a.max_participants, a.fee, a.organizer, a.checkin_enabled
@@ -878,7 +903,7 @@ app.post('/activities/upload/cover', requireActivityAdmin, (req, res, next) => {
app.get('/activities/:id', (req, res) => {
try {
const { id } = req.params;
const userId = req.headers['x-user-id'] || 'user-1';
const userId = req.headers['x-user-id'] || null;
const activity = db.prepare('SELECT * FROM activities WHERE id = ?').get(id);
if (!activity) {
@@ -942,7 +967,7 @@ app.get('/activities/:id', (req, res) => {
position: creator.position,
chaishuLevel: creator.chaishu_level || ''
} : null,
isJoined: userParticipant && userParticipant.status !== 'cancelled',
isJoined: !!(userParticipant && userParticipant.status !== 'cancelled'),
};
res.json({ success: true, data: activityDetail });
@@ -955,7 +980,7 @@ app.get('/activities/:id', (req, res) => {
// 创建活动
app.post('/activities', requireActivityAdmin, (req, res) => {
try {
const userId = req.headers['x-user-id'] || 'user-1';
const userId = req.authUser.id;
const { title, cover_url, description, location, start_time, duration, max_participants, tags, checkin_enabled, fee, organizer } = req.body;
const activityId = uuidv4();
const now = new Date().toISOString();
@@ -990,6 +1015,7 @@ app.post('/activities', requireActivityAdmin, (req, res) => {
app.put('/activities/:id', requireActivityAdmin, (req, res) => {
try {
const { id } = req.params;
const userId = req.authUser.id;
const { title, cover_url, description, location, start_time, duration, max_participants, tags, checkin_enabled, fee, organizer } = req.body;
const activity = db.prepare('SELECT * FROM activities WHERE id = ?').get(id);
@@ -997,6 +1023,10 @@ app.put('/activities/:id', requireActivityAdmin, (req, res) => {
return res.json({ success: false, message: '活动不存在' });
}
if (activity.creator_id !== userId) {
return res.json({ success: false, message: '无权限修改此活动' });
}
const now = new Date().toISOString();
db.prepare(`
UPDATE activities SET title = ?, cover_url = ?, description = ?, location = ?, start_time = ?, duration = ?, max_participants = ?, fee = ?, organizer = ?, checkin_enabled = ?, updated_at = ? WHERE id = ?
@@ -1023,7 +1053,11 @@ app.put('/activities/:id', requireActivityAdmin, (req, res) => {
app.post('/activities/:id/share', (req, res) => {
try {
const { id } = req.params;
const userId = req.headers['x-user-id'] || 'user-1';
const authUser = authenticateUser(req);
if (!authUser) {
return res.status(401).json({ success: false, message: '请先登录' });
}
const userId = authUser.id;
const activity = db.prepare('SELECT * FROM activities WHERE id = ?').get(id);
if (!activity) {
@@ -1044,7 +1078,11 @@ app.post('/activities/:id/share', (req, res) => {
app.post('/activities/:id/join', (req, res) => {
try {
const { id } = req.params;
const userId = req.headers['x-user-id'] || 'user-1';
const authUser = authenticateUser(req);
if (!authUser) {
return res.status(401).json({ success: false, message: '请先登录' });
}
const userId = authUser.id;
const activity = db.prepare('SELECT * FROM activities WHERE id = ?').get(id);
if (!activity) {
@@ -1083,20 +1121,20 @@ app.post('/activities/:id/join', (req, res) => {
app.delete('/activities/:id/join', (req, res) => {
try {
const { id } = req.params;
const userId = req.headers['x-user-id'] || 'user-1';
const authUser = authenticateUser(req);
if (!authUser) {
return res.status(401).json({ success: false, message: '请先登录' });
}
const userId = authUser.id;
const participant = db.prepare('SELECT * FROM activity_participants WHERE activity_id = ? AND user_id = ?').get(id, userId);
if (!participant) {
return res.json({ success: false, message: '您未参与该活动' });
}
if (participant.status === 'cancelled') {
return res.json({ success: false, message: '您已取消该活动报名,无需重复取消' });
}
const now = new Date().toISOString();
db.prepare("UPDATE activity_participants SET status = 'cancelled' WHERE id = ?").run(participant.id);
db.prepare("UPDATE activities SET participant_count = (SELECT COUNT(*) FROM activity_participants WHERE activity_id = activities.id AND status = 'joined'), updated_at = ? WHERE id = ?").run(now, id);
db.prepare('UPDATE activities SET participant_count = participant_count - 1, updated_at = ? WHERE id = ?').run(now, id);
res.json({ success: true, data: null });
} catch (error) {
@@ -1109,7 +1147,7 @@ app.delete('/activities/:id/join', (req, res) => {
app.get('/activities/:id/checkin-status', (req, res) => {
try {
const { id } = req.params;
const userId = req.headers['x-user-id'] || 'user-1';
const userId = req.headers['x-user-id'] || null;
// 获取活动信息
const activity = db.prepare('SELECT * FROM activities WHERE id = ?').get(id);
@@ -1201,7 +1239,11 @@ app.get('/activities/:id/checkin-status', (req, res) => {
app.post('/activities/:id/checkin', (req, res) => {
try {
const { id } = req.params;
const userId = req.headers['x-user-id'] || 'user-1';
const authUser = authenticateUser(req);
if (!authUser) {
return res.status(401).json({ success: false, message: '请先登录' });
}
const userId = authUser.id;
const participant = db.prepare('SELECT * FROM activity_participants WHERE activity_id = ? AND user_id = ?').get(id, userId);
if (!participant) {
@@ -1226,7 +1268,7 @@ app.post('/activities/:id/checkin', (req, res) => {
app.delete('/activities/:id', requireActivityAdmin, (req, res) => {
try {
const { id } = req.params;
const userId = req.headers['x-user-id'] || 'user-1';
const userId = req.authUser.id;
const activity = db.prepare('SELECT * FROM activities WHERE id = ?').get(id);
if (!activity) {
@@ -1341,7 +1383,11 @@ app.delete('/ai/recommendations/:activityId', (req, res) => {
// 合作可能性分析
app.post('/ai/collaboration-analysis', async (req, res) => {
try {
const userId = req.headers['x-user-id'] || 'user-1';
const authUser = authenticateUser(req);
if (!authUser) {
return res.status(401).json({ success: false, message: '请先登录' });
}
const userId = authUser.id;
const { target_user_id } = req.body;
if (!target_user_id) {
@@ -1723,8 +1769,7 @@ app.post('/user/email/bind', (req, res) => {
if (!user.chaishu_uid) {
const member = db.prepare('SELECT * FROM chaishu_members WHERE LOWER(email) = ?').get(email);
if (member && !db.prepare('SELECT id FROM users WHERE chaishu_uid = ? AND id != ?').get(member.uid, userId)) {
const level = member.level3 ? `三级(${member.level3})` : (member.level2 ? `二级(${member.level2})` : (member.level1 ? `一级(${member.level1})` : ''));
db.prepare('UPDATE users SET chaishu_uid = ?, chaishu_verified = 1, chaishu_level = ? WHERE id = ?').run(member.uid, level, userId);
db.prepare('UPDATE users SET chaishu_uid = ?, chaishu_verified = 1, chaishu_level = ? WHERE id = ?').run(member.uid, memberLevelLabel(member), userId);
chaishuAutoBound = true;
}
}
@@ -1988,6 +2033,7 @@ app.get('/api/admin/users', requireAdmin, (req, res) => {
position: r.position || '', chaishuLevel: r.chaishu_level || '',
chaishuUid: r.chaishu_uid || '', chaishuVerified: !!r.chaishu_verified,
role: r.role || 'user', isAdmin: (r.role || 'user') === 'admin',
companies: r.companies ? r.companies.split('||').filter(Boolean) : [],
createdAt: r.created_at, createdCount: r.created_count, joinedCount: r.joined_count,
})),
},
@@ -2031,9 +2077,20 @@ app.put('/api/admin/users/:id', requireAdmin, (req, res) => {
const b = req.body || {};
// 白名单字段:undefined = 不改,null = 清空,'' 空串 = 清空
// email 为源头身份锚点:任何情况下不可修改(含管理员)
// email 可由管理员修改(换绑身份锚点):格式校验 + 全局查重,统一小写存储
if (b.email !== undefined) {
const newEmail = b.email === null ? '' : String(b.email).trim().toLowerCase();
if (newEmail && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(newEmail)) {
return res.json({ success: false, message: '邮箱格式不正确' });
}
if (newEmail && newEmail !== String(target.email || '').toLowerCase()) {
const taken = db.prepare('SELECT id FROM users WHERE LOWER(email) = ? AND id != ?').get(newEmail, id);
if (taken) return res.json({ success: false, message: '该邮箱已被其他用户使用' });
}
b.email = newEmail;
}
const fields = {
nickname: b.nickname, position: b.position, industry: b.industry, hometown: b.hometown,
nickname: b.nickname, email: b.email, position: b.position, industry: b.industry, hometown: b.hometown,
weixin: b.weixin, phone: b.phone, expertise: b.expertise,
};
const sets = [], args = [];
@@ -2045,13 +2102,24 @@ app.put('/api/admin/users/:id', requireAdmin, (req, res) => {
sets.push('chaishu_uid = ?'); args.push(b.chaishu_uid || '');
sets.push('chaishu_verified = ?'); args.push(b.chaishu_uid ? 1 : 0);
}
// 公司列表:数组=整体替换(重排 sort_order),null=清空
let companiesChanged = false;
if (Array.isArray(b.companies)) {
db.prepare('DELETE FROM user_companies WHERE user_id = ?').run(id);
const ins = db.prepare('INSERT INTO user_companies (user_id, company_name, sort_order) VALUES (?, ?, ?)');
b.companies.filter(Boolean).forEach((c, i) => ins.run(id, String(c).trim(), i));
companiesChanged = true;
} else if (b.companies === null) {
db.prepare('DELETE FROM user_companies WHERE user_id = ?').run(id);
companiesChanged = true;
}
let levelChanged = null;
if (sets.length) {
sets.push('updated_at = ?'); args.push(new Date().toISOString());
args.push(id);
db.prepare(`UPDATE users SET ${sets.join(', ')} WHERE id = ?`).run(...args);
writeAdminLog(req.admin, 'update_user', 'user', id,
`${target.nickname || id}: ${sets.filter(s => !s.startsWith('updated_at')).join(', ')}`);
`${target.nickname || id}: ${[...sets.filter(s => !s.startsWith('updated_at')), companiesChanged ? 'companies' : null].filter(Boolean).join(', ')}`);
}
if (b.chaishu_uid === '') {
// 解绑操作