515 lines
20 KiB
JavaScript
515 lines
20 KiB
JavaScript
'use strict';
|
||
|
||
const { Service } = require('egg');
|
||
const crypto = require('crypto');
|
||
const qrcode = require('qrcode-generator');
|
||
|
||
/** 扫码串码字符集:数字 + 大写字母,去掉了 0/O/1/I 等容易看错的字符 */
|
||
const CODE_ALPHABET = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
|
||
|
||
/** 生成 6 位数字 + 字母的随机串码 */
|
||
function randomCode(length = 6) {
|
||
let out = '';
|
||
for (let i = 0; i < length; i++) {
|
||
out += CODE_ALPHABET[crypto.randomInt(CODE_ALPHABET.length)];
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/**
|
||
* 微信公众号「网页授权」地址(在微信内置浏览器里打开时用,scope=snsapi_base 静默拿 openid)
|
||
* 手机扫码后先落到本站 `/wechat?spm=…`,再重定向到这里。
|
||
*/
|
||
function webAuthorizeUrl({ appid, redirectUri, state }) {
|
||
const query = new URLSearchParams({
|
||
appid,
|
||
redirect_uri: redirectUri,
|
||
response_type: 'code',
|
||
scope: 'snsapi_base',
|
||
state,
|
||
});
|
||
return `https://open.weixin.qq.com/connect/oauth2/authorize?${query.toString()}#wechat_redirect`;
|
||
}
|
||
|
||
/**
|
||
* 登录页的微信扫码登录
|
||
*
|
||
* - **二维码内容是本站地址**:`http://<域名>/wechat?spm=1.0.<code>.1`,`<code>` 是服务端生成的
|
||
* 6 位数字 + 字母随机串码(存 Redis,TTL 内有效);二维码本身用零依赖的 qrcode-generator
|
||
* 现场画成 SVG(`/api/wechat/qrcode.svg`),**全程不加载任何第三方图片/脚本**。
|
||
* - **扫码后**:手机打开**前端路由** `/wechat?spm=…` → 配了微信就重定向到公众号网页授权(静默拿 openid),
|
||
* 回到后端 `/api/wechat/callback` 后把「已确认的用户 id」写进 Redis;
|
||
* 没配微信时退化成「手机确认登录」——扫码的人已经登录才能确认(`POST /api/wechat/confirm`)。
|
||
* - **不自动建号**:只对「已绑定微信」的账号生效(绑定关系在 `wechat_oauth` 表里,
|
||
* 可用 `POST /api/wechat/bind` 建立),未绑定就提示先用账号密码登录再绑定。
|
||
* - 串码一次性:确认结果被电脑端取走后立即删除。
|
||
*/
|
||
class WechatLoginService extends Service {
|
||
get cfg() {
|
||
return this.app.config.wechat;
|
||
}
|
||
|
||
get redis() {
|
||
return this.app.redis;
|
||
}
|
||
|
||
/** 是否配好了微信登录 */
|
||
get enabled() {
|
||
return Boolean(this.cfg.appid && this.cfg.secret);
|
||
}
|
||
|
||
/** 扫码状态在 Redis 里的 key(value:'pending' = 等扫码;数字 = 已确认的用户 id) */
|
||
stateKey(code) {
|
||
return `${this.app.config.cache.prefix}wechat:state:${code}`;
|
||
}
|
||
|
||
/** 长轮询用的广播频道 */
|
||
channel(code) {
|
||
return `${this.app.config.cache.prefix}wechat:login:${code}`;
|
||
}
|
||
|
||
/** 设备专用登录:设备自报信息(sn / 名称等)的暂存 key(发码时写入,确认/换码时取走) */
|
||
deviceKey(code) {
|
||
return `${this.app.config.cache.prefix}device:info:${code}`;
|
||
}
|
||
|
||
/**
|
||
* 暂存设备自报信息(发码时调用;什么都没传就不写)
|
||
*
|
||
* 建记录发生在「扫码确认成功」那一刻,而设备可能只在发码时带了 sn/名称 ——
|
||
* 存一份就能在确认/换码时沿用,不用要求设备每次都把参数补齐
|
||
* @param {string} code 登录码
|
||
* @param {object} info { sn, name, vendor, model, firmware }
|
||
*/
|
||
async saveDeviceInfo(code, info = {}) {
|
||
if (!this.redis || !code) return;
|
||
|
||
const payload = {};
|
||
for (const key of [ 'sn', 'name', 'vendor', 'model', 'firmware' ]) {
|
||
if (info[key]) payload[key] = info[key];
|
||
}
|
||
if (!Object.keys(payload).length) return;
|
||
|
||
try {
|
||
await this.redis.setex(this.deviceKey(code), this.stateTtl, JSON.stringify(payload));
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[wechat] 暂存设备信息失败: %s', err.message);
|
||
}
|
||
}
|
||
|
||
/** 取走设备自报信息(确认成功 / 换码时调用,取走即删),取不到返回 null */
|
||
async takeDeviceInfo(code) {
|
||
if (!this.redis || !code) return null;
|
||
try {
|
||
const raw = await this.redis.get(this.deviceKey(code));
|
||
await this.redis.del(this.deviceKey(code));
|
||
return raw ? JSON.parse(raw) : null;
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[wechat] 读取设备信息失败: %s', err.message);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 回调地址:优先用配置,否则按当前请求的 origin 拼
|
||
* (这是**后端**地址,微信授权后会带 ?code=&state= 重定向到这里,见 controller/auth/wechat.js#callback)
|
||
*/
|
||
redirectUri(origin) {
|
||
if (this.cfg.redirectUri) return this.cfg.redirectUri;
|
||
return `${String(origin || '').replace(/\/+$/, '')}/api/wechat/callback`;
|
||
}
|
||
|
||
/** 把串码拼成 spm(默认 `1.0.<code>.1`,格式可用 `WECHAT_SPM_PATTERN` 配) */
|
||
spm(code) {
|
||
return String(this.cfg.spmPattern || '1.0.{code}.1').replace('{code}', code);
|
||
}
|
||
|
||
/** 从 spm 里把串码抠出来(`1.0.AB12CD.1` → `AB12CD`),格式不对返回空串 */
|
||
parseSpm(spm) {
|
||
const length = Number(this.cfg.codeLength || 6);
|
||
const pattern = new RegExp(`^[0-9A-Za-z]{${length}}$`);
|
||
for (const seg of String(spm || '').split('.')) {
|
||
if (pattern.test(seg)) return seg.toUpperCase();
|
||
}
|
||
return '';
|
||
}
|
||
|
||
/**
|
||
* 二维码里要编码的内容:本站 `/wechat?spm=1.0.<code>.1`(前端的 origin 由请求带)
|
||
* @param {object} params { code, origin }
|
||
* @return {string}
|
||
*/
|
||
qrContent({ code, origin } = {}) {
|
||
if (!code) this.ctx.throw(422, '缺少登录码');
|
||
return `${String(origin || '').replace(/\/+$/, '')}/wechat?spm=${this.spm(code)}`;
|
||
}
|
||
|
||
/** 公众号网页授权地址(手机在微信里打开 `/wechat?spm=…` 时重定向过去) */
|
||
oauthAuthorizeUrl({ origin, code }) {
|
||
return webAuthorizeUrl({
|
||
appid: this.cfg.appid,
|
||
redirectUri: this.redirectUri(origin),
|
||
state: code,
|
||
});
|
||
}
|
||
|
||
/** 这个串码还在等扫码吗(存在且是 pending) */
|
||
async isPending(code) {
|
||
if (!this.redis || !code) return false;
|
||
try {
|
||
return await this.redis.get(this.stateKey(code)) === 'pending';
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[wechat] 查询扫码状态失败: %s', err.message);
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 给前端 API 用:生成一个新串码并登记为 pending(不依赖 session)
|
||
* @return {Promise<string>} 6 位串码
|
||
*/
|
||
async newCode() {
|
||
const code = randomCode(Number(this.cfg.codeLength || 6));
|
||
await this.openState(code);
|
||
return code;
|
||
}
|
||
|
||
/**
|
||
* 给前端 API 用:轮询串码状态(**长轮询**)
|
||
*
|
||
* 行为:
|
||
* - 已经确认过 → 立刻返回 `{ status:'confirmed', user, token, … }`(取走即删,一次性);
|
||
* - 串码不存在/已过期 → 立刻返回 `{ status:'refreshed', code }`(附新串码,前端直接换二维码);
|
||
* - 还在等扫码 → 挂起最多 `wait` 秒(受 `WECHAT_POLL_WAIT` 限制):
|
||
* - 期间有人确认 → **立即**返回 `confirmed`(靠 Redis 发布订阅通知,不轮询); * - 客户端提前断开(切回账号密码登录 / 关页签 / fetch abort)→ 立即返回 `{ status:'aborted' }`,
|
||
* **不再挂满 wait 秒**,也不把串码换掉; * - 到时间没动静 → 返回 `{ status:'refreshed', code }` 换一张新码;
|
||
* - `wait=0`(默认)时不挂起,只返回 `{ status:'pending' }`。
|
||
*
|
||
* @param {string} code 串码
|
||
* @param {object} options { wait 挂起秒数, withToken 是否顺手签发用户 JWT(设备端登录时为 false,
|
||
* 由调用方自己签发长期令牌,见 app/controller/device.js)}
|
||
* @return {Promise<{status:string, user?:object, token?:string, code?:string, waited?:number}>}
|
||
*/
|
||
async awaitLogin(code, { wait = 0, withToken = true } = {}) {
|
||
if (!this.redis || !code) {
|
||
return { status: 'refreshed', code: await this.newCode() };
|
||
}
|
||
|
||
const maxWait = Number(this.cfg.pollWait || 25);
|
||
const seconds = Math.min(Math.max(Number(wait) || 0, 0), maxWait);
|
||
const channel = this.channel(code);
|
||
|
||
// 先订阅、再查状态:这样「查的时候还是 pending、随后立刻被确认」的那一下不会漏掉
|
||
const subscriber = seconds > 0 ? this.subscriber() : null;
|
||
if (subscriber) await subscriber.subscribe(channel);
|
||
|
||
// 客户端断开的信号:页面导航(切回账号密码登录)或前端 abort 时立刻结束等待
|
||
const closed = seconds > 0 ? this.clientClosed() : null;
|
||
|
||
try {
|
||
const login = await this.takeLogin(code, withToken);
|
||
if (login) return Object.assign({ status: 'confirmed' }, login);
|
||
|
||
if (!(await this.isPending(code))) {
|
||
return { status: 'refreshed', code: await this.newCode() };
|
||
}
|
||
if (!seconds) return { status: 'pending' };
|
||
|
||
const hit = await this.waitPublish(subscriber, seconds * 1000, closed);
|
||
if (hit === 'closed') {
|
||
this.ctx.logger.info('[wechat] 客户端已断开,停止等待串码 %s', code);
|
||
return { status: 'aborted' };
|
||
}
|
||
if (hit) {
|
||
const after = await this.takeLogin(code, withToken);
|
||
if (after) return Object.assign({ status: 'confirmed' }, after);
|
||
}
|
||
// 到时间还没人扫 → 直接给新码,让前端换二维码
|
||
this.ctx.logger.info('[wechat] 串码 %s 等待 %ss 无变化,换新码', code, seconds);
|
||
return { status: 'refreshed', code: await this.newCode(), waited: seconds };
|
||
} finally {
|
||
if (subscriber) subscriber.disconnect();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 取走确认结果(`withToken=false` 时只给用户,不签用户 JWT)
|
||
* 设备端扫码登录用它取用户,再自己签发**长期**扫描器令牌
|
||
* @param {string} code 串码
|
||
* @param {boolean} withToken 是否顺手签发用户 JWT
|
||
* @return {Promise<{user:object, token?:string, tokenType?:string, expiresIn?:string}|null>}
|
||
*/
|
||
async takeLogin(code, withToken = true) {
|
||
if (withToken) return this.takeConfirmedWithToken(code);
|
||
|
||
const user = await this.takeConfirmed(code);
|
||
return user ? { user } : null;
|
||
}
|
||
|
||
/**
|
||
* 取走确认结果,顺手签发用户 JWT(写 session / 返回前端都用这一份)
|
||
* @param {string} code 串码
|
||
* @return {Promise<{user:object, token:string, tokenType:string, expiresIn:string}|null>}
|
||
*/
|
||
async takeConfirmedWithToken(code) {
|
||
const user = await this.takeConfirmed(code);
|
||
if (!user) return null;
|
||
return {
|
||
user,
|
||
token: this.ctx.service.jwt.signUser(user),
|
||
tokenType: 'Bearer',
|
||
expiresIn: this.app.config.jwt.userExpiresIn,
|
||
};
|
||
}
|
||
|
||
/** 确认登录后广播一次(长轮询的请求靠它立即醒来) */
|
||
async notify(code) {
|
||
if (!this.redis) return;
|
||
try {
|
||
await this.redis.publish(this.channel(code), 'confirmed');
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[wechat] 广播确认失败: %s', err.message);
|
||
}
|
||
}
|
||
|
||
/** 订阅用的独立连接(duplicate 出来的,用完即 disconnect) */
|
||
subscriber() {
|
||
const redis = this.app.redis;
|
||
return typeof redis.duplicate === 'function' ? redis.duplicate() : null;
|
||
}
|
||
|
||
/**
|
||
* 客户端断开(页面导航 / fetch abort)时 resolve `'closed'` 的 promise,拿不到底层连接时返回 null
|
||
* 用途:长轮询没人在等了就别再挂满 wait 秒(也避免白换一张新码)
|
||
*/
|
||
clientClosed() {
|
||
const res = this.ctx && this.ctx.res;
|
||
if (!res || typeof res.on !== 'function') return null;
|
||
|
||
return new Promise(resolve => {
|
||
const onClose = () => {
|
||
res.removeListener('close', onClose);
|
||
// 响应正常写完后 close 也会触发,那种不算断开
|
||
if (!res.writableEnded) resolve('closed');
|
||
};
|
||
res.on('close', onClose);
|
||
});
|
||
}
|
||
|
||
/** 等一条消息(或超时返回 null;`closed` 提前 resolve 就返回 'closed') */
|
||
waitPublish(subscriber, waitMs, closed) {
|
||
const wait = new Promise(resolve => {
|
||
if (!subscriber) return setTimeout(() => resolve(null), waitMs);
|
||
let done = false;
|
||
const finish = (value) => {
|
||
if (done) return;
|
||
done = true;
|
||
clearTimeout(timer);
|
||
resolve(value);
|
||
};
|
||
const timer = setTimeout(() => finish(null), waitMs);
|
||
subscriber.on('message', () => finish('confirmed'));
|
||
});
|
||
|
||
return closed ? Promise.race([ wait, closed ]) : wait;
|
||
}
|
||
|
||
/** 读串码当前的值:'pending' / 用户 id / null(不存在或已过期) */
|
||
async valueOf(code) {
|
||
if (!this.redis || !code) return null;
|
||
try {
|
||
return await this.redis.get(this.stateKey(code));
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[wechat] 读取串码失败: %s', err.message);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 确认登录(把「谁登录」写进 Redis 等电脑端取走)
|
||
* @param {string} code 串码
|
||
* @param {number} userId 确认者的用户 id(调用方保证已登录)
|
||
* @return {Promise<{ok:boolean, reason?:string, message?:string}>}
|
||
* reason: no_redis(Redis 不可用)/ bad_param(参数不全)/ expired(码不存在或已过期)/ used(已经被用过)
|
||
*/
|
||
async confirm(code, userId) {
|
||
if (!this.redis) return { ok: false, reason: 'no_redis', message: '服务暂时不可用,请稍后再试' };
|
||
if (!code || !userId) return { ok: false, reason: 'bad_param', message: '参数不完整' };
|
||
|
||
const value = await this.valueOf(code);
|
||
if (!value) return { ok: false, reason: 'expired', message: '登录码已失效,请刷新后重新扫码' };
|
||
if (value !== 'pending') return { ok: false, reason: 'used', message: '该登录码已经用过了' };
|
||
|
||
await this.redis.setex(this.stateKey(code), this.stateTtl, String(userId));
|
||
await this.notify(code); // 写完立刻广播:正在长轮询的请求马上就能返回
|
||
this.ctx.logger.info('[wechat] 扫码确认登录: code=%s userId=%s', code, userId);
|
||
return { ok: true };
|
||
}
|
||
|
||
/**
|
||
* 串码当前状态(给小程序/前端查询用,无副作用)
|
||
* @param {string} code 串码
|
||
* @return {Promise<{status:string, expiresIn:number}>}
|
||
* pending(待扫码)/ confirmed(已被确认,等电脑端取走)/ expired(不存在或已过期)
|
||
*/
|
||
async statusOf(code) {
|
||
const value = await this.valueOf(code);
|
||
if (!value) return { status: 'expired', expiresIn: 0 };
|
||
return {
|
||
status: value === 'pending' ? 'pending' : 'confirmed',
|
||
expiresIn: await this.ttlOf(code),
|
||
};
|
||
}
|
||
|
||
/** 串码剩余有效期(秒),取不到返回 0 */
|
||
async ttlOf(code) {
|
||
if (!this.redis || !code) return 0;
|
||
try {
|
||
const ttl = Number(await this.redis.ttl(this.stateKey(code)));
|
||
return ttl > 0 ? ttl : 0;
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[wechat] 读取串码有效期失败: %s', err.message);
|
||
return 0;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 本地把内容画成二维码 SVG(零依赖库,不请求外部服务)
|
||
* ⚠️ qrcode-generator 的 margin 参数单位是**像素**(不是格),所以这里把「格」换算成像素:
|
||
* 默认 4 格静默区(QR 规范要求 ≥ 4 格,不够会影响扫码识别率)。
|
||
* @param {string} content 编码内容
|
||
* @return {string} SVG 源码
|
||
*/
|
||
qrSvg(content) {
|
||
const cellSize = this.cfg.qrCellSize;
|
||
const qr = qrcode(0, 'M'); // 版本自动、纠错等级 M
|
||
qr.addData(String(content));
|
||
qr.make();
|
||
return qr.createSvgTag({
|
||
cellSize,
|
||
margin: this.cfg.qrMargin * cellSize,
|
||
scalable: true,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 同一个内容画成 **GIF 图片字节**(桌面端 WPF 不能渲染 SVG,只能吃位图)
|
||
* @param {string} content 编码内容
|
||
* @return {Buffer} GIF 字节
|
||
*/
|
||
qrGif(content) {
|
||
const cellSize = this.cfg.qrCellSize;
|
||
const qr = qrcode(0, 'M');
|
||
qr.addData(String(content));
|
||
qr.make();
|
||
const dataUrl = qr.createDataURL(cellSize, this.cfg.qrMargin * cellSize);
|
||
const base64 = String(dataUrl).split(',').pop() || '';
|
||
return Buffer.from(base64, 'base64');
|
||
}
|
||
|
||
/** 用 code 换 openid(只有配好 appid/secret 才会走到这里) */
|
||
async exchangeCode(code) {
|
||
const apiBase = String(this.cfg.apiBase || 'https://api.weixin.qq.com').replace(/\/+$/, '');
|
||
const res = await this.ctx.curl(`${apiBase}/sns/oauth2/access_token`, {
|
||
method: 'GET',
|
||
data: {
|
||
appid: this.cfg.appid,
|
||
secret: this.cfg.secret,
|
||
code,
|
||
grant_type: 'authorization_code',
|
||
},
|
||
dataType: 'json',
|
||
timeout: 5000,
|
||
});
|
||
const data = res.data || {};
|
||
if (data.errcode) {
|
||
this.ctx.logger.warn('[wechat] 换 openid 失败: %s %s', data.errcode, data.errmsg);
|
||
return { ok: false, message: `微信返回错误(${data.errcode}):${data.errmsg || '未知'}` };
|
||
}
|
||
if (!data.openid) {
|
||
this.ctx.logger.warn('[wechat] 微信未返回 openid: %j', data);
|
||
return { ok: false, message: '微信未返回 openid,请重试' };
|
||
}
|
||
return { ok: true, openid: data.openid, unionid: data.unionid || null };
|
||
}
|
||
|
||
/**
|
||
* 扫码后微信授权回来的处理(在**扫码那台设备**上执行):串码存在 → 换 openid → 找已绑定账号 →
|
||
* 把「已确认的用户 id」写进 Redis(key 就是串码),等电脑端登录页轮询取走。
|
||
* @param {string} code 微信回传的 code(换 openid 用)
|
||
* @param {string} state 微信回传的 state(= 本次扫码的 6 位串码)
|
||
* @return {Promise<{ok:boolean, message?:string, user?:object}>}
|
||
*/
|
||
async login(code, state) {
|
||
if (!this.enabled) {
|
||
return { ok: false, message: '服务端未配置微信登录(WECHAT_APPID / WECHAT_SECRET)' };
|
||
}
|
||
if (!state || !this.redis) {
|
||
return { ok: false, message: '登录状态已失效,请重新扫码' };
|
||
}
|
||
|
||
let pending;
|
||
try {
|
||
pending = await this.redis.get(this.stateKey(state));
|
||
} catch (err) {
|
||
this.ctx.logger.error('[wechat] 读取扫码状态失败: %s', err.message);
|
||
return { ok: false, message: '服务暂时不可用,请稍后再试' };
|
||
}
|
||
if (!pending) return { ok: false, message: '二维码已过期,请重新扫码' };
|
||
if (!code) return { ok: false, message: '微信未回传 code,请重新扫码' };
|
||
|
||
const exchanged = await this.exchangeCode(code);
|
||
if (!exchanged.ok) return exchanged;
|
||
|
||
const user = await this.ctx.service.user.findByOpenid(this.cfg.appid, exchanged.openid);
|
||
if (!user) {
|
||
this.ctx.logger.info('[wechat] openid 未绑定任何账号: %s', exchanged.openid);
|
||
return { ok: false, message: '这个微信还没绑定账号,请先用账号密码登录,绑定微信后再扫码' };
|
||
}
|
||
if (Number(user.status) !== 1) {
|
||
return { ok: false, message: '账号已被禁用,请联系管理员' };
|
||
}
|
||
|
||
await this.redis.setex(this.stateKey(state), this.stateTtl, String(user.id));
|
||
await this.notify(state); // 长轮询的请求靠这条广播立即醒来
|
||
this.ctx.logger.info('[wechat] 扫码确认成功: %s (id=%s)', user.username, user.id);
|
||
return { ok: true, user };
|
||
}
|
||
|
||
/** state 有效期(秒):与二维码有效期一致 */
|
||
get stateTtl() {
|
||
return Number(this.cfg.stateTtl || 600);
|
||
}
|
||
|
||
/** 登记一个待扫码的 state(桌面端渲染二维码时调用,重复调用只是刷新有效期) */
|
||
async openState(state) {
|
||
if (!this.redis) return;
|
||
try {
|
||
await this.redis.setex(this.stateKey(state), this.stateTtl, 'pending');
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[wechat] 登记扫码状态失败: %s', err.message);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 取走已确认的登录(桌面端轮询时调用)
|
||
* @return {Promise<object|null>} 已确认的用户,未确认/已过期返回 null
|
||
*/
|
||
async takeConfirmed(state) {
|
||
if (!this.redis || !state) return null;
|
||
let value;
|
||
try {
|
||
value = await this.redis.get(this.stateKey(state));
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[wechat] 查询扫码状态失败: %s', err.message);
|
||
return null;
|
||
}
|
||
if (!value || value === 'pending') return null;
|
||
|
||
await this.redis.del(this.stateKey(state)); // 一次性,用完即失效
|
||
return this.ctx.service.user.findById(Number(value));
|
||
}
|
||
}
|
||
|
||
module.exports = WechatLoginService;
|