Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a429079cd9 | ||
|
|
1bf584ad35 | ||
|
|
30d9a8503f | ||
|
|
be60104f21 |
+38
-26
@@ -2,20 +2,23 @@ import Joi from 'joi';
|
|||||||
import { DBModel } from "../models/index.js";
|
import { DBModel } from "../models/index.js";
|
||||||
import ResponseUtil from "../utils/api_response.js";
|
import ResponseUtil from "../utils/api_response.js";
|
||||||
import { hashPassword, verifyPassword, hashToken } from "../utils/crypto.js";
|
import { hashPassword, verifyPassword, hashToken } from "../utils/crypto.js";
|
||||||
import { sanitizeUser } from "../middleware/auth.js";
|
import { sanitizeUser, isAdmin } from "../middleware/auth.js";
|
||||||
import config from "../conf.json" with { type: "json" };
|
import config from "../conf.json" with { type: "json" };
|
||||||
|
|
||||||
// 微信 access_token 进程内缓存(有效期 7200s,提前 5 分钟刷新)
|
// 微信 access_token 进程内缓存(有效期 7200s,提前 5 分钟刷新)
|
||||||
const wxAccessTokenCache = new Map();
|
const wxAccessTokenCache = new Map();
|
||||||
|
|
||||||
|
// 微信接口超时:微信侧偶发慢响应,不设超时会让请求一直挂起并占用连接
|
||||||
|
const WX_REQUEST_TIMEOUT = 8000;
|
||||||
|
|
||||||
async function getWxAccessToken(appConfig) {
|
async function getWxAccessToken(appConfig) {
|
||||||
const cached = wxAccessTokenCache.get(appConfig.appid);
|
const cached = wxAccessTokenCache.get(appConfig.appid);
|
||||||
if (cached && Date.now() < cached.expiresAt) {
|
if (cached && Date.now() < cached.expiresAt) {
|
||||||
return cached.token;
|
return cached.token;
|
||||||
}
|
}
|
||||||
const fetch = (await import("node-fetch")).default;
|
|
||||||
const tokenUrl = `https://api.weixin.qq.com/cgi-bin/token?appid=${appConfig.appid}&secret=${appConfig.secret}&grant_type=client_credential`;
|
const tokenUrl = `https://api.weixin.qq.com/cgi-bin/token?appid=${appConfig.appid}&secret=${appConfig.secret}&grant_type=client_credential`;
|
||||||
const resp = await (await fetch(tokenUrl)).json();
|
const response = await fetch(tokenUrl, { signal: AbortSignal.timeout(WX_REQUEST_TIMEOUT) });
|
||||||
|
const resp = await response.json();
|
||||||
if (!resp.access_token) {
|
if (!resp.access_token) {
|
||||||
throw new Error(resp.errmsg || "获取微信 access_token 失败");
|
throw new Error(resp.errmsg || "获取微信 access_token 失败");
|
||||||
}
|
}
|
||||||
@@ -48,7 +51,8 @@ const registerSchema = Joi.object({
|
|||||||
district: Joi.string().allow(''),
|
district: Joi.string().allow(''),
|
||||||
}).optional(),
|
}).optional(),
|
||||||
addresses: Joi.array().optional(),
|
addresses: Joi.array().optional(),
|
||||||
app: Joi.object().optional(),
|
// 不接受客户端 app:app 里的角色决定管理端权限,只能由服务端/库内维护,
|
||||||
|
// 否则任何人都能在注册时自封管理员(历史漏洞)。
|
||||||
}).required(),
|
}).required(),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -82,16 +86,15 @@ const LOCK_AFTER_FAILED_ATTEMPTS = 10;
|
|||||||
|
|
||||||
class HandlerUser {
|
class HandlerUser {
|
||||||
// 生成 token(DB 中只存哈希,原始 token 仅在登录响应中返回一次)
|
// 生成 token(DB 中只存哈希,原始 token 仅在登录响应中返回一次)
|
||||||
async genToken(uid) {
|
// 必须用 CSPRNG:Math.random 的输出可预测,token 可预测就等于可冒充任意用户
|
||||||
|
async genToken() {
|
||||||
const crypto = await import("crypto");
|
const crypto = await import("crypto");
|
||||||
const hash = crypto.createHash("sha256");
|
return crypto.randomBytes(32).toString("hex");
|
||||||
hash.update(uid + Date.now() + Math.random());
|
|
||||||
return hash.digest("hex");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 签发 token:哈希入库,返回原始值供响应
|
// 签发 token:哈希入库,返回原始值供响应
|
||||||
async issueToken(user) {
|
async issueToken(user) {
|
||||||
const raw = await this.genToken(user._id.toString());
|
const raw = await this.genToken();
|
||||||
user.security.token = await hashToken(raw);
|
user.security.token = await hashToken(raw);
|
||||||
user.security.tokenExpiry = new Date(Date.now() + 15 * 24 * 60 * 60 * 1000);
|
user.security.tokenExpiry = new Date(Date.now() + 15 * 24 * 60 * 60 * 1000);
|
||||||
user.security.lastLoginAt = new Date();
|
user.security.lastLoginAt = new Date();
|
||||||
@@ -146,20 +149,22 @@ class HandlerUser {
|
|||||||
status: {
|
status: {
|
||||||
account: "normal",
|
account: "normal",
|
||||||
},
|
},
|
||||||
app: userInfo.app || {},
|
// 注册一律不带 app:管理端角色只能由服务端在库内授予
|
||||||
|
app: {},
|
||||||
};
|
};
|
||||||
|
|
||||||
const user = await DBModel.User.setUser(newUser);
|
// 手机号唯一性由库内唯一索引兜底(先查后插在并发下存在竞态)
|
||||||
if (!user) {
|
const user = await DBModel.User.create(newUser);
|
||||||
return ResponseUtil.internalError(ctx, "注册失败");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 生成 token(哈希入库,响应附原始 token)
|
// 生成 token(哈希入库,响应附原始 token)
|
||||||
const { raw } = await this.issueToken(user);
|
const { raw } = await this.issueToken(user);
|
||||||
|
|
||||||
return ResponseUtil.success(ctx, { user: this.buildLoginResponse(user, raw) }, "注册成功");
|
return ResponseUtil.success(ctx, { user: this.buildLoginResponse(user, raw) }, "注册成功");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return ResponseUtil.internalError(ctx, err.message);
|
if (err?.code === 11000) {
|
||||||
|
return ResponseUtil.error(ctx, "手机号已注册", null, 409);
|
||||||
|
}
|
||||||
|
return ResponseUtil.internalError(ctx, err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -175,8 +180,9 @@ class HandlerUser {
|
|||||||
|
|
||||||
// 查找用户
|
// 查找用户
|
||||||
let user = await DBModel.User.findOne({ "profile.mobile": mobile });
|
let user = await DBModel.User.findOne({ "profile.mobile": mobile });
|
||||||
|
// 不区分「用户不存在」与「密码错误」:避免被用来枚举已注册手机号
|
||||||
if (!user) {
|
if (!user) {
|
||||||
return ResponseUtil.unauthorized(ctx, "用户不存在");
|
return ResponseUtil.unauthorized(ctx, "账号或密码错误");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 锁定账户拒绝登录
|
// 锁定账户拒绝登录
|
||||||
@@ -197,7 +203,7 @@ class HandlerUser {
|
|||||||
await updated.save();
|
await updated.save();
|
||||||
return ResponseUtil.forbidden(ctx, "失败次数过多,账户已锁定,请联系管理员");
|
return ResponseUtil.forbidden(ctx, "失败次数过多,账户已锁定,请联系管理员");
|
||||||
}
|
}
|
||||||
return ResponseUtil.unauthorized(ctx, "密码错误");
|
return ResponseUtil.unauthorized(ctx, "账号或密码错误");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 渐进式迁移:如果是旧 MD5 密码,登录时升级为 bcrypt
|
// 渐进式迁移:如果是旧 MD5 密码,登录时升级为 bcrypt
|
||||||
@@ -217,7 +223,7 @@ class HandlerUser {
|
|||||||
|
|
||||||
return ResponseUtil.success(ctx, { user: this.buildLoginResponse(user, raw) }, "登录成功");
|
return ResponseUtil.success(ctx, { user: this.buildLoginResponse(user, raw) }, "登录成功");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return ResponseUtil.internalError(ctx, err.message);
|
return ResponseUtil.internalError(ctx, err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -268,7 +274,11 @@ class HandlerUser {
|
|||||||
|
|
||||||
return ResponseUtil.success(ctx, { user: sanitizeUser(updatedUser) }, "更新成功");
|
return ResponseUtil.success(ctx, { user: sanitizeUser(updatedUser) }, "更新成功");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return ResponseUtil.internalError(ctx, err.message);
|
// 手机号允许用户自助修改,但必须是全局唯一的:撞号时给出明确提示而不是通用错误
|
||||||
|
if (err?.code === 11000) {
|
||||||
|
return ResponseUtil.error(ctx, "该手机号已被使用", null, 409);
|
||||||
|
}
|
||||||
|
return ResponseUtil.internalError(ctx, err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -280,7 +290,7 @@ class HandlerUser {
|
|||||||
return ResponseUtil.unauthorized(ctx, "用户未登录或 token 无效");
|
return ResponseUtil.unauthorized(ctx, "用户未登录或 token 无效");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!("wxapp-escort-admin" in (user.app || {}))) {
|
if (!isAdmin(user)) {
|
||||||
return ResponseUtil.unauthorized(ctx, "用户无管理员权限");
|
return ResponseUtil.unauthorized(ctx, "用户无管理员权限");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -297,7 +307,7 @@ class HandlerUser {
|
|||||||
const safeUsers = users.map((u) => sanitizeUser(u));
|
const safeUsers = users.map((u) => sanitizeUser(u));
|
||||||
return ResponseUtil.success(ctx, { users: safeUsers, total, page, pageSize }, "获取用户列表成功");
|
return ResponseUtil.success(ctx, { users: safeUsers, total, page, pageSize }, "获取用户列表成功");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return ResponseUtil.internalError(ctx, err.message);
|
return ResponseUtil.internalError(ctx, err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -328,6 +338,7 @@ class HandlerUser {
|
|||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ code: value.phoneCode }),
|
body: JSON.stringify({ code: value.phoneCode }),
|
||||||
|
signal: AbortSignal.timeout(WX_REQUEST_TIMEOUT),
|
||||||
});
|
});
|
||||||
const phoneData = await phoneRes.json();
|
const phoneData = await phoneRes.json();
|
||||||
if (phoneData.errcode) {
|
if (phoneData.errcode) {
|
||||||
@@ -335,13 +346,13 @@ class HandlerUser {
|
|||||||
}
|
}
|
||||||
verifiedPhoneNumber = phoneData.phone_info?.phoneNumber || null;
|
verifiedPhoneNumber = phoneData.phone_info?.phoneNumber || null;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return ResponseUtil.internalError(ctx, err.message);
|
return ResponseUtil.internalError(ctx, err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 通过 code 换取 openid/session_key
|
// 通过 code 换取 openid/session_key
|
||||||
const sessionUrl = `https://api.weixin.qq.com/sns/jscode2session?appid=${app.appid}&secret=${app.secret}&js_code=${code}&grant_type=authorization_code`;
|
const sessionUrl = `https://api.weixin.qq.com/sns/jscode2session?appid=${app.appid}&secret=${app.secret}&js_code=${code}&grant_type=authorization_code`;
|
||||||
const wxSessionRes = await fetch(sessionUrl);
|
const wxSessionRes = await fetch(sessionUrl, { signal: AbortSignal.timeout(WX_REQUEST_TIMEOUT) });
|
||||||
const sessionData = await wxSessionRes.json();
|
const sessionData = await wxSessionRes.json();
|
||||||
if (sessionData.errcode) {
|
if (sessionData.errcode) {
|
||||||
return ResponseUtil.error(ctx, `微信接口错误: ${sessionData.errmsg}`, null, 400);
|
return ResponseUtil.error(ctx, `微信接口错误: ${sessionData.errmsg}`, null, 400);
|
||||||
@@ -397,7 +408,7 @@ class HandlerUser {
|
|||||||
|
|
||||||
return ResponseUtil.success(ctx, { user: this.buildLoginResponse(user, raw) }, "登录成功");
|
return ResponseUtil.success(ctx, { user: this.buildLoginResponse(user, raw) }, "登录成功");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return ResponseUtil.internalError(ctx, err.message);
|
return ResponseUtil.internalError(ctx, err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -424,7 +435,8 @@ class HandlerUser {
|
|||||||
const phoneRes = await fetch(phoneUrl, {
|
const phoneRes = await fetch(phoneUrl, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ code: code })
|
body: JSON.stringify({ code: code }),
|
||||||
|
signal: AbortSignal.timeout(WX_REQUEST_TIMEOUT),
|
||||||
});
|
});
|
||||||
const phoneData = await phoneRes.json();
|
const phoneData = await phoneRes.json();
|
||||||
if (phoneData.errcode) {
|
if (phoneData.errcode) {
|
||||||
@@ -434,7 +446,7 @@ class HandlerUser {
|
|||||||
const phoneNumber = phoneData.phone_info?.phoneNumber;
|
const phoneNumber = phoneData.phone_info?.phoneNumber;
|
||||||
return ResponseUtil.success(ctx, { phoneNumber }, "获取手机号成功");
|
return ResponseUtil.success(ctx, { phoneNumber }, "获取手机号成功");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return ResponseUtil.internalError(ctx, err.message);
|
return ResponseUtil.internalError(ctx, err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+28
-1
@@ -87,6 +87,33 @@ function auth(options = {}) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 管理端身份判定(与 health 服务 utils/permissions.js 同一口径)
|
||||||
|
*
|
||||||
|
* 不再用「app 里存在 wxapp-escort-admin 键」:该键历史上可由 /user/register 的
|
||||||
|
* 客户端入参写入,任何人都能据此自封管理员。现在注册侧拒绝写 app,
|
||||||
|
* 但库里可能残留历史账号,因此要求显式 role === 'admin';
|
||||||
|
* role 缺失的历史账号暂按管理员放行并打告警,待库中补齐 role 后收紧。
|
||||||
|
*
|
||||||
|
* @param {Object} user 用户文档或脱敏后的用户对象
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
function isAdmin(user) {
|
||||||
|
const entry = user?.app?.['wxapp-escort-admin'];
|
||||||
|
if (!entry) return false;
|
||||||
|
|
||||||
|
const roles = Array.isArray(entry.role) ? entry.role : [entry.role].filter(Boolean);
|
||||||
|
if (roles.includes('admin')) return true;
|
||||||
|
|
||||||
|
if (entry.role === undefined) {
|
||||||
|
console.warn(
|
||||||
|
"[auth] 管理员账号缺少 role 字段,请补齐 app.wxapp-escort-admin.role = ['admin']"
|
||||||
|
);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 返回用户安全对象(去除密码、token 等敏感字段)
|
* 返回用户安全对象(去除密码、token 等敏感字段)
|
||||||
* 注意:登录/注册响应中的 token 由 handler 单独附加
|
* 注意:登录/注册响应中的 token 由 handler 单独附加
|
||||||
@@ -102,4 +129,4 @@ function sanitizeUser(user) {
|
|||||||
return obj;
|
return obj;
|
||||||
}
|
}
|
||||||
|
|
||||||
export { auth, extractToken, sanitizeUser, findUserByToken };
|
export { auth, extractToken, sanitizeUser, findUserByToken, isAdmin };
|
||||||
|
|||||||
+9
-10
@@ -15,7 +15,9 @@ const UserSchema = mongoose.Schema(
|
|||||||
name: { type: String, comment: '用户姓名' },
|
name: { type: String, comment: '用户姓名' },
|
||||||
pinyin: { type: String, default: '', comment: '姓名的拼音,用于搜索' },
|
pinyin: { type: String, default: '', comment: '姓名的拼音,用于搜索' },
|
||||||
pinyinFL: { type: String, default: '', comment: '姓名拼音的首字母,用于搜索' },
|
pinyinFL: { type: String, default: '', comment: '姓名拼音的首字母,用于搜索' },
|
||||||
mobile: { type: String, index: true, trim: true, comment: '手机号码' },
|
// 手机号既用于登录,也是账号识别键:必须全局唯一,
|
||||||
|
// 否则并发注册可能产生两个同号账号,登录结果不确定
|
||||||
|
mobile: { type: String, index: true, unique: true, sparse: true, trim: true, comment: '手机号码' },
|
||||||
email: { type: String, index: true, trim: true, unique: true, sparse: true, comment: '电子邮箱' },
|
email: { type: String, index: true, trim: true, unique: true, sparse: true, comment: '电子邮箱' },
|
||||||
idnumber: { type: String, index: true, trim: true, unique: true, sparse: true, comment: '身份证号码' },
|
idnumber: { type: String, index: true, trim: true, unique: true, sparse: true, comment: '身份证号码' },
|
||||||
ssn: { type: String, index: true, trim: true, unique: true, sparse: true, comment: '社保卡号' },
|
ssn: { type: String, index: true, trim: true, unique: true, sparse: true, comment: '社保卡号' },
|
||||||
@@ -172,15 +174,12 @@ UserSchema.statics.updateFromUserInfo = async function (userId, userInfo) {
|
|||||||
updateData['addresses'] = userInfo.addresses;
|
updateData['addresses'] = userInfo.addresses;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
// 保留原有异常:唯一索引冲突(手机号撞号)需要由 handler 给出明确提示
|
||||||
return await this.findOneAndUpdate(
|
return await this.findOneAndUpdate(
|
||||||
{ _id: userId },
|
{ _id: userId },
|
||||||
{ $set: updateData },
|
{ $set: updateData },
|
||||||
{ new: true, upsert: false }
|
{ new: true, upsert: false, runValidators: true }
|
||||||
);
|
);
|
||||||
} catch (error) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+19
-3
@@ -1,6 +1,11 @@
|
|||||||
|
import logger from "./logger.js";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 响应工具类
|
* 响应工具类
|
||||||
* 提供统一的响应格式
|
* 提供统一的响应格式
|
||||||
|
*
|
||||||
|
* 约定:业务状态一律走 body.code,HTTP 状态码固定 200;
|
||||||
|
* 同时把 code 写进 X-Biz-Code 响应头,便于网关/监控按业务码告警。
|
||||||
*/
|
*/
|
||||||
class ResponseUtil {
|
class ResponseUtil {
|
||||||
/**
|
/**
|
||||||
@@ -11,6 +16,7 @@ class ResponseUtil {
|
|||||||
*/
|
*/
|
||||||
static success(ctx, data, message = '操作成功') {
|
static success(ctx, data, message = '操作成功') {
|
||||||
ctx.status = 200;
|
ctx.status = 200;
|
||||||
|
ctx.set('X-Biz-Code', '0');
|
||||||
ctx.body = {
|
ctx.body = {
|
||||||
code: 0,
|
code: 0,
|
||||||
msg: message,
|
msg: message,
|
||||||
@@ -28,6 +34,7 @@ class ResponseUtil {
|
|||||||
static error(ctx, message, data = null, errorCode = 500) {
|
static error(ctx, message, data = null, errorCode = 500) {
|
||||||
// 根据规则,只要进入controller,http状态码都是200
|
// 根据规则,只要进入controller,http状态码都是200
|
||||||
ctx.status = 200;
|
ctx.status = 200;
|
||||||
|
ctx.set('X-Biz-Code', String(errorCode));
|
||||||
ctx.body = {
|
ctx.body = {
|
||||||
code: errorCode,
|
code: errorCode,
|
||||||
msg: message,
|
msg: message,
|
||||||
@@ -74,11 +81,20 @@ class ResponseUtil {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 服务器内部错误响应
|
* 服务器内部错误响应
|
||||||
|
*
|
||||||
|
* 详细原因只进日志:err.message 可能含 Mongo 连接串、字段名等内部信息,
|
||||||
|
* 直接回传等于把服务端实现细节暴露给前端。
|
||||||
|
*
|
||||||
* @param {Object} ctx - Koa上下文对象
|
* @param {Object} ctx - Koa上下文对象
|
||||||
* @param {string} message - 错误消息
|
* @param {string|Error} detail - 内部错误详情(仅用于日志)
|
||||||
|
* @param {Object} data - 附加数据
|
||||||
*/
|
*/
|
||||||
static internalError(ctx, message = '服务器内部错误', data = null) {
|
static internalError(ctx, detail = null, data = null) {
|
||||||
return ResponseUtil.error(ctx, message, data, 500);
|
if (detail) {
|
||||||
|
const text = detail instanceof Error ? detail.stack : String(detail);
|
||||||
|
logger.error(`[internal] ${ctx.method} ${ctx.path}: ${text}`);
|
||||||
|
}
|
||||||
|
return ResponseUtil.error(ctx, '服务器繁忙,请稍后重试', data, 500);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user