From 9b4e97fafe238e5b7ed0423a7ef0516614441034 Mon Sep 17 00:00:00 2001 From: kenyanghui Date: Tue, 17 Nov 2026 00:03:24 +0800 Subject: [PATCH] =?UTF-8?q?feat(auth):=20=E9=82=AE=E7=AE=B1=E9=AA=8C?= =?UTF-8?q?=E8=AF=81=E7=A0=81=E7=99=BB=E5=BD=95=E5=BC=80=E6=94=BE=E6=89=80?= =?UTF-8?q?=E6=9C=89=E7=94=A8=E6=88=B7=E2=80=94=E2=80=94=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=20/auth/email/otp/send=20+=20/auth/email/login=EF=BC=88OTP?= =?UTF-8?q?=E9=AA=8C=E8=AF=81=E5=BB=BA=E5=8F=B7/=E4=BC=9A=E5=91=98?= =?UTF-8?q?=E8=A1=8C=E6=BF=80=E6=B4=BB/=E8=A3=B8=E5=8F=B7=E5=90=88?= =?UTF-8?q?=E5=B9=B6=E5=8D=87=E7=BA=A7=EF=BC=89=EF=BC=8C=E6=97=A7=E6=97=A0?= =?UTF-8?q?=E9=AA=8C=E8=AF=81=E7=A0=81=E9=82=AE=E7=AE=B1=E7=9B=B4=E7=99=BB?= =?UTF-8?q?=E6=94=B6=E7=B4=A7=EF=BC=8C=E7=99=BB=E5=BD=95=E9=A1=B5=E6=94=B9?= =?UTF-8?q?=E7=89=88=E9=82=AE=E7=AE=B1+=E9=AA=8C=E8=AF=81=E7=A0=81?= =?UTF-8?q?=E4=B8=BA=E4=B8=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- wechat-miniprogram/pages/login/index.js | 130 +++++++++++---------- wechat-miniprogram/pages/login/index.wxml | 70 ++++++------ wechat-miniprogram/pages/login/index.wxss | 74 ++++++++++++ yaoyue-sever/server/server.js | 132 +++++++++++++++++----- 4 files changed, 283 insertions(+), 123 deletions(-) diff --git a/wechat-miniprogram/pages/login/index.js b/wechat-miniprogram/pages/login/index.js index d50f0f4..75db90a 100644 --- a/wechat-miniprogram/pages/login/index.js +++ b/wechat-miniprogram/pages/login/index.js @@ -26,8 +26,10 @@ const isLoggedIn = () => { Page({ data: { loading: false, - showIdentifierLogin: false, - identifier: '', + email: '', + emailOtp: '', + otpSending: false, + otpCountdown: 0, }, goBack() { @@ -40,74 +42,85 @@ Page({ } }, - async handleWechatLogin(e) { - console.log('handleWechatLogin 被调用', e.detail); - if (this.data.loading) return; - - this.setData({ loading: true }); - - try { - // 获取微信登录 code - const code = await getWechatCode(); - - // 从 e.detail 提取手机号(如果有) - const phoneNumber = e.detail?.phoneNumber || null; - - // 发送 code 和手机号到后端;带 e.detail.phoneNumber 即视为运营商验证过的注册凭证 - const res = await post('/auth/login', { - code, - phone: phoneNumber, - phoneVerified: !!e.detail?.phoneNumber, - }); - - console.log('登录返回:', res); - - if (res.success && res.data) { - const { token, user } = res.data; - const userId = user?.id; - saveLoginState(token, userId, 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 }); + onUnload() { + if (this._otpTimer) { + clearInterval(this._otpTimer); + this._otpTimer = null; } }, - toggleIdentifierLogin() { - this.setData({ showIdentifierLogin: !this.data.showIdentifierLogin }); + onEmailInput(e) { + this.setData({ email: e.detail.value }); }, - onIdentifierInput(e) { - this.setData({ identifier: e.detail.value }); + onOtpInput(e) { + this.setData({ emailOtp: e.detail.value }); }, - async handleIdentifierLogin() { - const raw = (this.data.identifier || '').trim(); - if (!raw) { - wx.showToast({ title: '请输入拆书帮注册邮箱', icon: 'none' }); + startOtpCountdown() { + this.setData({ otpCountdown: 60 }); + if (this._otpTimer) clearInterval(this._otpTimer); + this._otpTimer = setInterval(() => { + const next = this.data.otpCountdown - 1; + if (next <= 0) { + clearInterval(this._otpTimer); + this._otpTimer = null; + this.setData({ otpCountdown: 0 }); + } else { + this.setData({ otpCountdown: next }); + } + }, 1000); + }, + + async handleSendOtp() { + const email = (this.data.email || '').trim(); + if (!email) { + wx.showToast({ title: '请输入邮箱', icon: 'none' }); + return; + } + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { + wx.showToast({ title: '邮箱格式不正确', icon: 'none' }); + return; + } + if (this.data.otpSending || this.data.otpCountdown > 0) return; + this.setData({ otpSending: true }); + try { + const res = await post('/auth/email/otp/send', { email }); + if (res.success) { + wx.showToast({ title: '验证码已发送', icon: 'none' }); + this.startOtpCountdown(); + } else { + wx.showToast({ title: res.message || '发送失败', icon: 'none' }); + } + } catch (err) { + wx.showToast({ title: err.message || '发送失败', icon: 'none' }); + } finally { + this.setData({ otpSending: false }); + } + }, + + async handleEmailLogin() { + const email = (this.data.email || '').trim(); + const code = (this.data.emailOtp || '').trim(); + if (!email) { + wx.showToast({ title: '请输入邮箱', icon: 'none' }); + return; + } + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { + wx.showToast({ title: '邮箱格式不正确', icon: 'none' }); + return; + } + if (!code) { + wx.showToast({ title: '请输入邮箱验证码', icon: 'none' }); return; } if (this.data.loading) return; this.setData({ loading: true }); try { - const isEmail = /^[\w.+-]+@[\w-]+(\.[\w-]+)+$/.test(raw); - if (!isEmail) { - wx.showToast({ title: '请输入正确的邮箱地址', icon: 'none' }); - return; - } - const payload = { email: raw }; - const res = await post('/auth/login', payload, { showLoading: false }); - + // 携带微信 code:登录成功后服务端补绑 openid(用于裸号合并升级) + let wxCode = ''; + try { wxCode = await getWechatCode(); } catch (e) { /* 不阻断邮箱登录 */ } + const res = await post('/auth/email/login', { email, code, wxCode }, { showLoading: false }); if (res.success && res.data) { const { token, user } = res.data; saveLoginState(token, user?.id, user); @@ -119,7 +132,6 @@ Page({ wx.showToast({ title: res.message || '登录失败', icon: 'none' }); } } catch (err) { - console.error('登录异常:', err); wx.showToast({ title: err.message || '登录失败,请重试', icon: 'none' }); } finally { this.setData({ loading: false }); diff --git a/wechat-miniprogram/pages/login/index.wxml b/wechat-miniprogram/pages/login/index.wxml index 76db920..fc07eb4 100644 --- a/wechat-miniprogram/pages/login/index.wxml +++ b/wechat-miniprogram/pages/login/index.wxml @@ -16,50 +16,46 @@ 遇见更多拆为己用的拆书家 - - - - - 其他登录方式 - - - - - + + - - - - - - © 2024 拆约 · 客服邮箱:554176937@qq.com diff --git a/wechat-miniprogram/pages/login/index.wxss b/wechat-miniprogram/pages/login/index.wxss index ed2ecfa..4f5e1e3 100644 --- a/wechat-miniprogram/pages/login/index.wxss +++ b/wechat-miniprogram/pages/login/index.wxss @@ -178,6 +178,7 @@ .toggle-login-wrap { display: flex; + justify-content: center; margin-top: 40rpx; } @@ -214,3 +215,76 @@ font-size: 24rpx; color: #cccccc; } + +/* 邮箱验证码登录(2026-11-16 方案Z:开放所有用户) */ +.email-form { + display: flex; + flex-direction: column; + width: 100%; + margin-top: 8rpx; +} + +.email-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; +} + +.email-otp-row { + display: flex; + align-items: center; + margin-top: 24rpx; +} + +.email-otp-input { + flex: 1; + height: 96rpx; + box-sizing: border-box; + padding: 0 32rpx; + border: 2rpx solid #eeeeee; + border-radius: 48rpx; + background-color: #f7f8fa; + font-size: 30rpx; + color: #333333; +} + +.email-otp-btn { + margin-left: 20rpx; + display: flex; + align-items: center; + justify-content: center; + height: 96rpx; + padding: 0 32rpx; + background-color: #f0f1f3; + border-radius: 48rpx; + border: none; + font-size: 26rpx; + color: #333333; + white-space: nowrap; +} + +.email-otp-btn[disabled] { + color: #999999; +} + +.email-login-btn { + display: flex; + align-items: center; + justify-content: center; + width: 100%; + height: 96rpx; + margin-top: 32rpx; + background-color: #333333; + border-radius: 48rpx; + border: none; +} + +.email-login-btn[disabled] { + background-color: #777777; +} diff --git a/yaoyue-sever/server/server.js b/yaoyue-sever/server/server.js index f9199e3..488f1d3 100644 --- a/yaoyue-sever/server/server.js +++ b/yaoyue-sever/server/server.js @@ -902,16 +902,116 @@ function verifyOtpStrict(email, code) { const entry = emailOtpStore.get(email); if (!entry) return { ok: false, message: '请先获取验证码' }; if (Date.now() > entry.expiresAt) { emailOtpStore.delete(email); return { ok: false, message: '验证码已过期,请重新获取' }; } - if (entry.attempts >= OTP_MAX_ATTEMPTS) { emailOtpStore.delete(email); return { ok: false, message: '尝试次数过多,请重新获取验证码' }; } + if (entry.attempts >= OTP_MAX_ATTEMPTS) { emailOtpStore.delete(email); return { ok: false, message: '尝试次数过多,请重新获取' }; } entry.attempts += 1; if (entry.code !== code) { - if (entry.attempts >= OTP_MAX_ATTEMPTS) return { ok: false, message: "尝试次数过多,请重新获取验证码" }; + if (entry.attempts >= OTP_MAX_ATTEMPTS) return { ok: false, message: "尝试次数过多,请重新获取" }; return { ok: false, message: `验证码错误(剩 ${OTP_MAX_ATTEMPTS - entry.attempts} 次机会)` }; } emailOtpStore.delete(email); return { ok: true }; } +// ==================== 邮箱验证码登录(开放所有用户,2026-11-16 方案Z) ==================== +// 未登录发码:注册/登录前置校验只拦「已激活账号占用」,未激活会员行放行(登录时就地激活) +app.post('/auth/email/otp/send', async (req, res) => { + try { + if (!SMTP_READY) return res.json({ success: false, message: '邮件服务未配置,请联系管理员' }); + const ip = (req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim(); + if (!otpIpAllow(ip)) return res.status(429).json({ success: false, message: '请求过于频繁,请稍后再试' }); + const email = String(req.body.email || '').trim().toLowerCase(); + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { + return res.json({ success: false, message: '邮箱格式不正确' }); + } + const taken = db.prepare("SELECT id FROM users WHERE LOWER(email) = ? AND has_account = 1").get(email); + if (taken) { + // 已激活账号:允许发码走「验证码登录」(等价邮箱所有权证明),不泄露账号是否存在 + } + const now = Date.now(); + const prev = emailOtpStore.get(email); + if (prev && now - prev.sentAt < OTP_RESEND_COOLDOWN_MS) { + return res.json({ success: false, message: '发送太频繁,请 60 秒后再试' }); + } + const code = String(crypto.randomInt(100000, 999999)); + try { + await smtpSend(email, 'AI心光登录验证码', `您正在登录 AI心光(拆约)。\n\n验证码:${code}\n\n5 分钟内有效。若非本人操作请忽略本邮件。`); + } catch (e) { + console.error('登录 OTP 邮件发送失败:', e.message); + return res.json({ success: false, message: '验证码邮件发送失败,请稍后重试或联系客服 554176937@qq.com' }); + } + emailOtpStore.set(email, { code, expiresAt: now + OTP_TTL_MS, attempts: 0, sentAt: now }); + res.json({ success: true, data: { message: '验证码已发送,请查收(含垃圾箱)' } }); + } catch (error) { + console.error('发送登录验证码失败:', error); + res.json({ success: false, message: '发送验证码失败' }); + } +}); + +// 邮箱验证码登录:OTP 通过即证明邮箱所有权 → 登录或建号(v8 单表,会员行就地激活) +// body: { email, code, wxCode? } wxCode 可选:小程序内登录时携带,用于补绑 openid +app.post('/auth/email/login', async (req, res) => { + try { + const email = String(req.body.email || '').trim().toLowerCase(); + const code = String(req.body.code || '').trim(); + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { + return res.json({ success: false, message: '邮箱格式不正确' }); + } + const otp = verifyOtpStrict(email, code); + if (!otp.ok) return res.json({ success: false, message: otp.message }); + + // 可选:小程序侧带 wx code → 换 openid 补绑(失败不阻断邮箱登录) + let openid = ''; + const wxCode = req.body.wxCode || req.body.wx_code; + 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); } + } + + let user = db.prepare("SELECT * FROM users WHERE LOWER(email) = ? AND has_account = 1").get(email); + if (!user && openid) { + // 存量合并:该 openid 已有无邮箱裸账号 → 就地绑邮箱升级(避免同人双号) + const bare = db.prepare("SELECT * FROM users WHERE openid = ? AND has_account = 1 AND IFNULL(email, '') = ''").get(openid); + if (bare) { + db.prepare('UPDATE users SET email = ?, updated_at = ? WHERE id = ?').run(email, new Date().toISOString(), bare.id); + try { bindChaishuMember(bare, { email }); } catch (e) { console.warn('裸号升级自动绑定会员失败:', e.message); } + user = db.prepare('SELECT * FROM users WHERE id = ?').get(bare.id); + } + } + if (!user) { + const member = db.prepare("SELECT * FROM users WHERE uid != '' AND has_account = 0 AND LOWER(email) = ?").get(email); + if (member) { + user = activateMemberRow(member, openid); + } else { + const userId = uuidv4(); + const now = new Date().toISOString(); + db.prepare(` + INSERT INTO users (id, has_account, openid, nickname, avatar_url, phone, position, industry, hometown, email, expertise, created_at, updated_at) + VALUES (?, 1, ?, ?, '', '', '', '', '', ?, ?, ?, ?) + `).run(userId, openid || '', `用户${email.slice(0, email.indexOf('@'))}`.slice(0, 20), now, now); + user = db.prepare('SELECT * FROM users WHERE id = ?').get(userId); + } + } else if (openid && !user.openid) { + const owner = db.prepare('SELECT id FROM users WHERE openid = ?').get(openid); + if (!owner) { + db.prepare('UPDATE users SET openid = ?, updated_at = ? WHERE id = ?').run(openid, new Date().toISOString(), user.id); + user.openid = openid; + } + } + // 命中未激活会员行邮箱时合并绑定(已是会员行则内部直接返回) + try { bindChaishuMember(user, { email }); } catch (e) { console.warn('邮箱登录自动绑定会员失败:', e.message); } + 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 } }); + } catch (error) { + console.error('邮箱验证码登录失败:', error); + res.json({ success: false, message: '登录失败,请重试' }); + } +}); + // 强制绑邮箱:无邮箱用户的关键业务写操作拦截(EMAIL_REQUIRED) function requireEmail(req, res, next) { const userId = req.headers["x-user-id"]; @@ -1037,36 +1137,14 @@ app.post('/auth/login', async (req, res) => { console.warn('微信 API 不可达,回退手机号/微信号/邮箱登录'); } - // 邮箱登录:邮箱是拆书帮会员唯一身份认定键。v8 单表: - // 命中已激活账号直接登录;否则命中未激活会员行 → 就地激活(不建新行);都未命中则拒绝 + // 邮箱登录(2026-11-16 方案Z):统一走 /auth/email/login 验证码登录; + // 旧无验证码直登关闭——任何人拿到会员邮箱即可冒登,属安全漏洞 if (email) { const normEmail = String(email).trim().toLowerCase(); if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normEmail)) { return res.json({ success: false, message: '邮箱格式不正确' }); } - let user = db.prepare("SELECT * FROM users WHERE LOWER(email) = ? AND has_account = 1").get(normEmail); - if (!user) { - const member = db.prepare("SELECT * FROM users WHERE uid != '' AND has_account = 0 AND LOWER(email) = ?").get(normEmail); - if (!member) { - return res.json({ success: false, message: '该邮箱未注册为拆书帮会员,请先用手机号或微信号登录,并在「我的-编辑资料」中绑定邮箱' }); - } - user = activateMemberRow(member, openid); - } else if (openid && !user.openid) { - // 账号尚无 openid 且无他人占用时补绑,便于后续纯微信登录识别 - const owner = db.prepare('SELECT id FROM users WHERE openid = ?').get(openid); - if (!owner) { - db.prepare('UPDATE users SET openid = ?, updated_at = ? WHERE id = ?').run(openid, new Date().toISOString(), user.id); - user.openid = openid; - } - } - // 非会员账号命中未激活会员邮箱时仍尝试合并绑定(已是会员行则内部直接返回) - try { bindChaishuMember(user, { email: normEmail }); } catch (e) { console.warn('拆书帮自动绑定失败:', e.message); } - db.prepare('UPDATE users SET login_count = login_count + 1 WHERE id = ?').run(user.id); - const userWithCompanies = getUserWithCompanies(user.id); - return res.json({ - success: true, - data: { token: signUserToken(user.id), user: userWithCompanies } - }); + return res.json({ success: false, message: '邮箱登录需验证码:请输入邮箱点「获取验证码」,凭验证码登录(未注册邮箱将自动创建账号)' }); } // 手机号或微信号登录:优先手机号,其次微信号(支持微信小程序登录),有则登录,无则注册