feat(auth): 手机号一键登录——微信 getPhoneNumber 授权 + 三重安全收口
新增: - /auth/phone/login:getuserphonenumber 换真实手机号(access_token 带缓存提前5分钟刷新) - find-or-create:手机号精确匹配 → 未激活会员行合并 → 建新号;openid 关联 - 小程序登录页「手机号一键登录」主按钮(open-type=getPhoneNumber),失败/个人主体自动降级引导邮箱登录 - requireContact 宽守卫:报名/取消/签到只需邮箱或手机号任一(手机号验证用户免绑邮箱即可报名) 安全收口: - 关闭裸手机号/微信号登录路径(无所有权验证即登录=任何人可冒充任意用户) - 误导文案修正:拒绝时引导邮箱登录/一键登录,不再指向已关闭路径 - 邮箱仍为拆书帮身份绑定锚点(requireEmail 保留于 chaishu/bind、tags、AI 共拆场景) E2E P1-P5c 全绿:参数校验/伪造授权码降级/裸 phone 拒/邮箱 OTP 回归/手机号-only 用户报名成功/无联系方式 CONTACT_REQUIRED 拒
This commit is contained in:
@@ -30,6 +30,7 @@ Page({
|
||||
emailOtp: '',
|
||||
otpSending: false,
|
||||
otpCountdown: 0,
|
||||
phoneLoading: false,
|
||||
},
|
||||
|
||||
goBack() {
|
||||
@@ -72,6 +73,46 @@ Page({
|
||||
}, 1000);
|
||||
},
|
||||
|
||||
// 微信手机号一键登录:getPhoneNumber 授权码 + wx.login code → /auth/phone/login
|
||||
// 失败(个人主体/权限未开/网络)→ 明确降级提示引导邮箱登录
|
||||
async handlePhoneLogin(e) {
|
||||
if (this.data.phoneLoading) return;
|
||||
const detail = e.detail || {};
|
||||
// 用户点拒绝/取消:静默返回,不打扰
|
||||
if (!detail.code) {
|
||||
if (detail.errMsg && detail.errMsg.includes('deny')) return;
|
||||
// errMsg 无 deny 但无 code(老基础库/个人主体)→ 引导邮箱
|
||||
wx.showToast({ title: '当前环境不支持一键登录,请使用邮箱登录', icon: 'none', duration: 2500 });
|
||||
return;
|
||||
}
|
||||
this.setData({ phoneLoading: true });
|
||||
try {
|
||||
let wxCode = '';
|
||||
try { wxCode = await getWechatCode(); } catch (err) { /* 不阻断:openid 补绑可选 */ }
|
||||
const res = await post('/auth/phone/login', { phoneCode: detail.code, wxCode }, { 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 if (res.code === 'PHONE_AUTH_FAILED') {
|
||||
// 服务端明确失败(40029/48001 等)→ 降级引导
|
||||
wx.showModal({
|
||||
title: '一键登录暂不可用',
|
||||
content: (res.message || '手机号授权失败') + '。可在下方使用邮箱验证码登录。',
|
||||
showCancel: false,
|
||||
confirmText: '知道了',
|
||||
});
|
||||
} else {
|
||||
wx.showToast({ title: res.message || '登录失败,请重试', icon: 'none' });
|
||||
}
|
||||
} catch (err) {
|
||||
wx.showToast({ title: (err && err.message) || '登录失败,请重试', icon: 'none' });
|
||||
} finally {
|
||||
this.setData({ phoneLoading: false });
|
||||
}
|
||||
},
|
||||
|
||||
async handleSendOtp() {
|
||||
const email = (this.data.email || '').trim();
|
||||
if (!email) {
|
||||
|
||||
@@ -16,7 +16,28 @@
|
||||
<text>遇见更多拆为己用的拆书家</text>
|
||||
</view>
|
||||
|
||||
<!-- 邮箱验证码登录(开放所有用户:未注册邮箱自动创建账号) -->
|
||||
<!-- 手机号一键登录(主推:微信授权手机号,一键完成) -->
|
||||
<view class="phone-section">
|
||||
<button
|
||||
class="phone-login-btn"
|
||||
open-type="getPhoneNumber"
|
||||
bindgetphonenumber="handlePhoneLogin"
|
||||
loading="{{phoneLoading}}"
|
||||
>
|
||||
<text class="phone-btn-text">{{phoneLoading ? '登录中...' : '手机号一键登录'}}</text>
|
||||
</button>
|
||||
<view class="phone-tip">
|
||||
<text>使用微信绑定的手机号快速登录,未注册将自动创建账号</text>
|
||||
</view>
|
||||
|
||||
<view class="divider">
|
||||
<view class="divider-line"></view>
|
||||
<text class="divider-text">其他登录方式</text>
|
||||
<view class="divider-line"></view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<!-- 邮箱验证码登录(次选:开放所有用户,未注册邮箱自动创建账号) -->
|
||||
<view class="email-form">
|
||||
<view class="email-row">
|
||||
<input
|
||||
|
||||
@@ -288,3 +288,22 @@
|
||||
.email-login-btn[disabled] {
|
||||
background-color: #777777;
|
||||
}
|
||||
|
||||
/* 手机号一键登录(主推) */
|
||||
.phone-section { margin-bottom: 8rpx; }
|
||||
.phone-login-btn {
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
width: 100%; height: 96rpx; margin-top: 24rpx;
|
||||
background: linear-gradient(135deg, #07c160 0%, #06ad56 100%);
|
||||
border-radius: 48rpx; border: none;
|
||||
box-shadow: 0 8rpx 24rpx rgba(7, 193, 96, 0.25);
|
||||
}
|
||||
.phone-login-btn::after { border: none; }
|
||||
.phone-btn-text { color: #fff; font-size: 32rpx; font-weight: 600; letter-spacing: 2rpx; }
|
||||
.phone-tip { margin-top: 16rpx; text-align: center; }
|
||||
.phone-tip text { font-size: 22rpx; color: #8a93a6; }
|
||||
|
||||
/* 分隔线「其他登录方式」 */
|
||||
.divider { display: flex; align-items: center; margin: 48rpx 0 8rpx; }
|
||||
.divider-line { flex: 1; height: 1rpx; background: #e5e9f2; }
|
||||
.divider-text { padding: 0 24rpx; font-size: 24rpx; color: #8a93a6; }
|
||||
|
||||
@@ -29,6 +29,23 @@ async function callWechatAPI(url) {
|
||||
return res.json();
|
||||
}
|
||||
|
||||
// 微信接口调用凭据(getuserphonenumber 等全局接口用;jscode2session 不需要)
|
||||
let wechatAccessToken = { token: '', expiresAt: 0 };
|
||||
async function getWechatAccessToken() {
|
||||
if (wechatAccessToken.token && Date.now() < wechatAccessToken.expiresAt) {
|
||||
return wechatAccessToken.token;
|
||||
}
|
||||
const d = await callWechatAPI(
|
||||
`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${WECHAT_APPID}&secret=${WECHAT_SECRET}`
|
||||
);
|
||||
if (!d.access_token) {
|
||||
throw new Error(`获取 access_token 失败: ${d.errcode} ${d.errmsg}`);
|
||||
}
|
||||
// 提前 5 分钟过期,避免边界失效
|
||||
wechatAccessToken = { token: d.access_token, expiresAt: Date.now() + ((d.expires_in || 7200) - 300) * 1000 };
|
||||
return wechatAccessToken.token;
|
||||
}
|
||||
|
||||
// 调用智谱 GLM API
|
||||
async function callGLMAPI(prompt) {
|
||||
if (!GLM_ENABLED) {
|
||||
@@ -949,6 +966,82 @@ app.post('/auth/email/otp/send', async (req, res) => {
|
||||
|
||||
// 邮箱验证码登录:OTP 通过即证明邮箱所有权 → 登录或建号(v8 单表,会员行就地激活)
|
||||
// body: { email, code, wxCode? } wxCode 可选:小程序内登录时携带,用于补绑 openid
|
||||
// 微信手机号一键登录(open-type=getPhoneNumber 的 code 换真实手机号)
|
||||
// 适用:企业主体小程序;个人主体调用会失败 → 前端自动降级邮箱登录
|
||||
app.post('/auth/phone/login', async (req, res) => {
|
||||
try {
|
||||
const phoneCode = String(req.body.phoneCode || req.body.phone_code || '').trim();
|
||||
const wxCode = String(req.body.wxCode || req.body.wx_code || '').trim();
|
||||
if (!phoneCode) {
|
||||
return res.json({ success: false, code: 'PHONE_AUTH_FAILED', message: '缺少手机号授权码,请重试或改用邮箱登录' });
|
||||
}
|
||||
|
||||
// 1) wx.login 的 code 换 openid(用于账号关联)
|
||||
let openid = '';
|
||||
if (wxCode) {
|
||||
try {
|
||||
const wechatRes = await callWechatAPI(
|
||||
`https://api.weixin.qq.com/sns/jscode2session?appid=${WECHAT_APPID}&secret=${WECHAT_SECRET}&js_code=${wxCode}&grant_type=authorization_code`
|
||||
);
|
||||
if (!wechatRes.errcode && wechatRes.openid) openid = wechatRes.openid;
|
||||
} catch (e) { console.warn('手机号登录换 openid 失败(不阻断):', e.message); }
|
||||
}
|
||||
|
||||
// 2) access_token + getuserphonenumber 换真实手机号
|
||||
let phone = '';
|
||||
let purePhone = false;
|
||||
try {
|
||||
const at = await getWechatAccessToken();
|
||||
const r = await fetch(`https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${at}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code: phoneCode }),
|
||||
}).then(x => x.json());
|
||||
if (r.errcode !== 0 || !(r.phone_info && r.phone_info.purePhoneNumber)) {
|
||||
// 典型 errcode: 40029 code 无效 / 48001 无 api 权限(个人主体)
|
||||
console.error('getuserphonenumber 失败:', r.errcode, r.errmsg);
|
||||
return res.json({ success: false, code: 'PHONE_AUTH_FAILED', message: '手机号授权失败(' + (r.errcode || '未知') + '),请改用邮箱登录' });
|
||||
}
|
||||
phone = String(r.phone_info.purePhoneNumber).trim();
|
||||
purePhone = true;
|
||||
} catch (e) {
|
||||
console.error('手机号登录调用微信接口失败:', e.message);
|
||||
return res.json({ success: false, code: 'PHONE_AUTH_FAILED', message: '手机号服务暂不可用,请改用邮箱登录' });
|
||||
}
|
||||
|
||||
// 3) find-or-create:手机号精确匹配(中国大陆 11 位)→ 未激活会员行按手机号合并 → 建新号
|
||||
let user = db.prepare('SELECT * FROM users WHERE phone = ? AND has_account = 1').get(phone);
|
||||
if (!user) {
|
||||
const member = db.prepare("SELECT * FROM users WHERE uid != '' AND has_account = 0 AND phone = ?").get(phone);
|
||||
if (member) {
|
||||
user = activateMemberRow(member, openid);
|
||||
}
|
||||
}
|
||||
if (!user) {
|
||||
const userId = uuidv4();
|
||||
const now = new Date().toISOString();
|
||||
db.prepare(`
|
||||
INSERT INTO users (id, has_account, openid, nickname, avatar_url, phone, weixin, position, industry, hometown, email, expertise, created_at, updated_at)
|
||||
VALUES (?, 1, ?, ?, '', ?, '', '', '', '', '', '', ?, ?)
|
||||
`).run(userId, openid || null, `用户${phone.slice(-4)}`, phone, now, now);
|
||||
user = db.prepare('SELECT * FROM users WHERE id = ?').get(userId);
|
||||
} else if (openid && user.openid !== openid) {
|
||||
db.prepare('UPDATE users SET openid = ?, updated_at = ? WHERE id = ?').run(openid, new Date().toISOString(), user.id);
|
||||
user.openid = openid;
|
||||
}
|
||||
|
||||
db.prepare('UPDATE users SET login_count = login_count + 1 WHERE id = ?').run(user.id);
|
||||
const userWithCompanies = getUserWithCompanies(user.id);
|
||||
res.json({
|
||||
success: true,
|
||||
data: { token: signUserToken(user.id), user: userWithCompanies, phoneVerified: purePhone },
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('手机号登录失败:', error);
|
||||
res.json({ success: false, message: '登录失败,请重试或改用邮箱登录' });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/auth/email/login', async (req, res) => {
|
||||
try {
|
||||
const email = String(req.body.email || '').trim().toLowerCase();
|
||||
@@ -1023,6 +1116,18 @@ function requireEmail(req, res, next) {
|
||||
next();
|
||||
}
|
||||
|
||||
// 宽联系方式守卫:邮箱或验证手机号任一即可(报名/签到/取消场景)
|
||||
// 手机号一键登录(/auth/phone/login 微信授权实测)的用户无需再绑邮箱即可报名
|
||||
function requireContact(req, res, next) {
|
||||
const userId = req.headers["x-user-id"];
|
||||
if (!userId) return res.json({ success: false, code: "LOGIN_REQUIRED", message: "未登录" });
|
||||
const u = db.prepare("SELECT email, phone FROM users WHERE id = ? AND has_account = 1").get(userId);
|
||||
if (!u || (!u.email && !u.phone)) {
|
||||
return res.json({ success: false, code: "CONTACT_REQUIRED", message: "请先登录并完善联系方式(邮箱或手机号)后再操作" });
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
// 用户会话密钥:复用 app_settings 中的 admin_session_secret 体系(独立 user key)
|
||||
function getUserSessionSecret() {
|
||||
const row = db.prepare("SELECT value FROM app_settings WHERE key = 'user_session_secret'").get();
|
||||
@@ -1147,9 +1252,9 @@ app.post('/auth/login', async (req, res) => {
|
||||
return res.json({ success: false, message: '邮箱登录需验证码:请输入邮箱点「获取验证码」,凭验证码登录(未注册邮箱将自动创建账号)' });
|
||||
}
|
||||
|
||||
// 手机号或微信号登录:优先手机号,其次微信号(支持微信小程序登录),有则登录,无则注册
|
||||
// v8 单表:只匹配已激活账号;未激活会员行由 bindChaishuMember 在建号后合并绑定
|
||||
if (phone) {
|
||||
// 裸手机号/微信号登录已关闭(2026-11-17 安全收口:无所有权验证即登录=任何人可冒充)
|
||||
// 可信登录路径仅剩:微信 code 换 openid / 邮箱 OTP(/auth/email/login)/ 手机号一键授权(/auth/phone/login)
|
||||
if (false && phone) {
|
||||
let user = db.prepare('SELECT * FROM users WHERE phone = ? AND has_account = 1').get(phone);
|
||||
const weixinUser = !user ? db.prepare("SELECT * FROM users WHERE weixin = ? AND weixin != '' AND has_account = 1").get(phone) : null;
|
||||
user = user || weixinUser;
|
||||
@@ -1190,7 +1295,7 @@ app.post('/auth/login', async (req, res) => {
|
||||
|
||||
// 无手机号 → 纯微信登录,用 openid 查
|
||||
if (!openid) {
|
||||
return res.json({ success: false, message: '微信登录失败,请输入手机号或微信号登录' });
|
||||
return res.json({ success: false, code: 'AUTH_PATH_CLOSED', message: '请使用邮箱验证码登录,或返回首页用手机号一键登录' });
|
||||
}
|
||||
let user = db.prepare('SELECT * FROM users WHERE openid = ?').get(openid);
|
||||
if (!user) {
|
||||
@@ -1704,7 +1809,7 @@ app.post('/activities/:id/share', (req, res) => {
|
||||
});
|
||||
|
||||
// 报名活动
|
||||
app.post('/activities/:id/join', requireEmail, (req, res) => {
|
||||
app.post('/activities/:id/join', requireContact, (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const authUser = authenticateUser(req);
|
||||
@@ -1746,7 +1851,7 @@ app.post('/activities/:id/join', requireEmail, (req, res) => {
|
||||
});
|
||||
|
||||
// 取消报名
|
||||
app.delete('/activities/:id/join', requireEmail, (req, res) => {
|
||||
app.delete('/activities/:id/join', requireContact, (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const authUser = authenticateUser(req);
|
||||
@@ -1862,7 +1967,7 @@ app.get('/activities/:id/checkin-status', (req, res) => {
|
||||
});
|
||||
|
||||
// 签到
|
||||
app.post('/activities/:id/checkin', requireEmail, (req, res) => {
|
||||
app.post('/activities/:id/checkin', requireContact, (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const authUser = authenticateUser(req);
|
||||
|
||||
Reference in New Issue
Block a user