refactor: relocate backend into backend/ directory
This commit is contained in:
parent
7fc414e06f
commit
b1f90b1c15
26
.gitignore
vendored
26
.gitignore
vendored
@ -1,10 +1,32 @@
|
||||
# dependencies
|
||||
node_modules/
|
||||
.pnp
|
||||
.pnp.js
|
||||
|
||||
# backend (egg / sequelize)
|
||||
logs/
|
||||
swagger.json
|
||||
run/
|
||||
swagger.json
|
||||
coverage/
|
||||
.nyc_output/
|
||||
|
||||
# frontend build output
|
||||
dist/
|
||||
build/
|
||||
out/
|
||||
.next/
|
||||
*.tsbuildinfo
|
||||
|
||||
# env files
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
# logs
|
||||
*.log
|
||||
|
||||
# editor / OS
|
||||
.idea/
|
||||
.vscode/
|
||||
.DS_Store
|
||||
*.log
|
||||
Thumbs.db
|
||||
|
||||
@ -1,16 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Swagger 契约(数据结构)定义。
|
||||
* 在 Controller 注释中通过 `@Request` / `@Response` 引用这里的 key。
|
||||
*/
|
||||
module.exports = {
|
||||
baseResponse: {
|
||||
code: { type: 'integer', description: '业务状态码,0 表示成功' },
|
||||
message: { type: 'string', description: '提示信息' },
|
||||
data: { type: 'string', description: '业务数据(JSON)' },
|
||||
},
|
||||
homeResponse: {
|
||||
text: { type: 'string', description: '欢迎文本' },
|
||||
},
|
||||
};
|
||||
@ -1,21 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 示例 Model,演示 egg-sequelize 用法,可删除后按业务创建。
|
||||
* 目录约定:app/model/** 下每个文件导出 define 的 model,
|
||||
* 通过 app.model.xxx 访问(此处文件名为 user.js => app.model.User)。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} user model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { STRING, INTEGER, DATE } = app.Sequelize;
|
||||
|
||||
const User = app.model.define('user', {
|
||||
id: { type: INTEGER, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
name: { type: STRING(50), allowNull: false, comment: '用户名' },
|
||||
created_at: { type: DATE, allowNull: false, comment: '创建时间' },
|
||||
updated_at: { type: DATE, allowNull: false, comment: '更新时间' },
|
||||
});
|
||||
|
||||
return User;
|
||||
};
|
||||
@ -1,9 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* @param {Egg.Application} app - egg application
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { router, controller } = app;
|
||||
router.get('/', controller.home.index);
|
||||
};
|
||||
0
backend/.dev.err
Normal file
0
backend/.dev.err
Normal file
@ -14,6 +14,12 @@
|
||||
"rules": {
|
||||
"no-restricted-modules": "off"
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": [ "app/lib/**/*.js" ],
|
||||
"rules": {
|
||||
"no-restricted-modules": "off"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
379
backend/app/contract/index.js
Normal file
379
backend/app/contract/index.js
Normal file
@ -0,0 +1,379 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Swagger 契约(数据结构)定义。
|
||||
* 在 Controller 注释中通过 `@Request` / `@Response` 引用这里的 key。
|
||||
*
|
||||
* 插件约定(egg-swagger-doc):
|
||||
* 1. 每个字段必须声明 type,可选值:string / number / boolean / integer / array / file
|
||||
* 2. type 非上述基础类型时,会被解析为契约引用 `$ref: #/definitions/{type}`
|
||||
* 3. type 为 array 时必须声明 itemType,itemType 可为基础类型或其他契约名
|
||||
* 4. 字段加 required: true 表示必填
|
||||
*/
|
||||
|
||||
/** 通用响应:data 为任意业务数据 */
|
||||
const baseResponse = {
|
||||
code: { type: 'integer', description: '业务状态码,0 成功,非 0 失败' },
|
||||
message: { type: 'string', description: '提示信息' },
|
||||
data: { type: 'string', description: '业务数据(JSON)' },
|
||||
};
|
||||
|
||||
/**
|
||||
* 分页数据结构契约
|
||||
* @param {String} itemContract 列表项契约名,如 userItem
|
||||
* @param {String} listDesc 列表描述
|
||||
* @return {Object} 分页契约
|
||||
*/
|
||||
const buildPage = (itemContract, listDesc) => ({
|
||||
page: { type: 'integer', description: '当前页码' },
|
||||
pageSize: { type: 'integer', description: '每页条数' },
|
||||
total: { type: 'integer', description: '总条数' },
|
||||
list: { type: 'array', itemType: itemContract, description: listDesc },
|
||||
});
|
||||
|
||||
/**
|
||||
* 列表响应契约(data 引用对应的分页契约)
|
||||
* @param {String} pageContract 分页契约名,如 userPage
|
||||
* @return {Object} 列表响应契约
|
||||
*/
|
||||
const buildListResponse = pageContract => ({
|
||||
code: { type: 'integer', description: '业务状态码,0 成功' },
|
||||
message: { type: 'string', description: '提示信息' },
|
||||
data: { type: pageContract, description: '分页数据:page / pageSize / total / list' },
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
baseResponse,
|
||||
|
||||
// ---------- 登录鉴权 ----------
|
||||
loginRequest: {
|
||||
account: { type: 'string', required: true, description: '登录账号或邮箱' },
|
||||
password: { type: 'string', required: true, description: '登录密码(明文,HTTPS 传输)' },
|
||||
},
|
||||
sendEmailCodeRequest: {
|
||||
email: { type: 'string', required: true, description: '接收验证码的邮箱,需未在系统中注册' },
|
||||
},
|
||||
registerRequest: {
|
||||
username: { type: 'string', required: true, description: '登录账号,全局唯一' },
|
||||
password: { type: 'string', required: true, description: '登录密码(明文,不少于 6 位),服务端生成盐并加盐哈希存储' },
|
||||
email: { type: 'string', required: true, description: '邮箱,全局唯一,需通过邮箱验证码认证' },
|
||||
code: { type: 'string', required: true, description: '邮箱收到的 6 位验证码,10 分钟内有效' },
|
||||
nickname: { type: 'string', description: '昵称,不传则默认与账号相同' },
|
||||
phone: { type: 'string', description: '手机号' },
|
||||
},
|
||||
loginData: {
|
||||
token: { type: 'string', description: 'JWT 令牌,载荷仅含 user_id' },
|
||||
user_id: { type: 'integer', description: '用户ID' },
|
||||
expires_in: { type: 'integer', description: '有效秒数,如 7200' },
|
||||
},
|
||||
loginResponse: {
|
||||
code: { type: 'integer', description: '业务状态码,0 成功' },
|
||||
message: { type: 'string', description: '提示信息' },
|
||||
data: { type: 'loginData', description: '登录结果' },
|
||||
},
|
||||
|
||||
// ---------- 用户 users ----------
|
||||
userItem: {
|
||||
id: { type: 'integer', description: '主键' },
|
||||
username: { type: 'string', description: '登录账号' },
|
||||
nickname: { type: 'string', description: '昵称' },
|
||||
avatar: { type: 'string', description: '头像' },
|
||||
email: { type: 'string', description: '邮箱' },
|
||||
phone: { type: 'string', description: '手机号' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用' },
|
||||
last_login_at: { type: 'string', description: '最后登录时间' },
|
||||
created_at: { type: 'string', description: '创建时间' },
|
||||
updated_at: { type: 'string', description: '更新时间' },
|
||||
},
|
||||
userPage: buildPage('userItem', '用户列表'),
|
||||
userListResponse: buildListResponse('userPage'),
|
||||
createUserRequest: {
|
||||
username: { type: 'string', required: true, description: '登录账号,唯一' },
|
||||
password: { type: 'string', required: true, description: '登录密码(明文传入,服务端生成盐并加盐哈希存储)' },
|
||||
nickname: { type: 'string', description: '昵称' },
|
||||
avatar: { type: 'string', description: '头像URL' },
|
||||
email: { type: 'string', description: '邮箱' },
|
||||
phone: { type: 'string', description: '手机号' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用,默认1' },
|
||||
},
|
||||
updateUserRequest: {
|
||||
nickname: { type: 'string', description: '昵称' },
|
||||
avatar: { type: 'string', description: '头像URL' },
|
||||
email: { type: 'string', description: '邮箱' },
|
||||
phone: { type: 'string', description: '手机号' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用' },
|
||||
},
|
||||
resetPasswordRequest: {
|
||||
password: { type: 'string', required: true, description: '新密码(明文),服务端重新生成盐值并加盐哈希' },
|
||||
},
|
||||
|
||||
// ---------- 主体 principals ----------
|
||||
principalItem: {
|
||||
id: { type: 'integer', description: '主键' },
|
||||
code: { type: 'string', description: '主体编码,唯一' },
|
||||
name: { type: 'string', description: '主体名称' },
|
||||
type: { type: 'integer', description: '主体类型:1自营 2加盟 3外部' },
|
||||
contact_name: { type: 'string', description: '联系人' },
|
||||
contact_phone: { type: 'string', description: '联系电话' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
created_at: { type: 'string', description: '创建时间' },
|
||||
updated_at: { type: 'string', description: '更新时间' },
|
||||
},
|
||||
principalPage: buildPage('principalItem', '主体列表'),
|
||||
principalListResponse: buildListResponse('principalPage'),
|
||||
createPrincipalRequest: {
|
||||
code: { type: 'string', required: true, description: '主体编码,唯一' },
|
||||
name: { type: 'string', required: true, description: '主体名称' },
|
||||
type: { type: 'integer', description: '主体类型:1自营 2加盟 3外部,默认1' },
|
||||
contact_name: { type: 'string', description: '联系人' },
|
||||
contact_phone: { type: 'string', description: '联系电话' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用,默认1' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
},
|
||||
updatePrincipalRequest: {
|
||||
name: { type: 'string', description: '主体名称' },
|
||||
type: { type: 'integer', description: '主体类型:1自营 2加盟 3外部' },
|
||||
contact_name: { type: 'string', description: '联系人' },
|
||||
contact_phone: { type: 'string', description: '联系电话' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
},
|
||||
|
||||
// ---------- 主体用户关联 principal_users ----------
|
||||
principalUserItem: {
|
||||
id: { type: 'integer', description: '主键' },
|
||||
principal_id: { type: 'integer', description: '主体ID' },
|
||||
user_id: { type: 'integer', description: '用户ID' },
|
||||
role: { type: 'string', description: '该主体下的角色标识' },
|
||||
is_default: { type: 'integer', description: '是否默认主体:1是 0否' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用' },
|
||||
created_at: { type: 'string', description: '创建时间' },
|
||||
updated_at: { type: 'string', description: '更新时间' },
|
||||
},
|
||||
principalUserPage: buildPage('principalUserItem', '关联记录列表'),
|
||||
principalUserListResponse: buildListResponse('principalUserPage'),
|
||||
bindPrincipalUserRequest: {
|
||||
principal_id: { type: 'integer', required: true, description: '主体ID' },
|
||||
user_id: { type: 'integer', required: true, description: '用户ID' },
|
||||
role: { type: 'string', description: '角色标识,如 admin' },
|
||||
is_default: { type: 'integer', description: '是否默认主体:1是 0否,默认0' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用,默认1' },
|
||||
},
|
||||
|
||||
// ---------- 商品 products ----------
|
||||
productItem: {
|
||||
id: { type: 'integer', description: '主键' },
|
||||
principal_id: { type: 'integer', description: '所属主体ID' },
|
||||
code: { type: 'string', description: '商品编码' },
|
||||
name: { type: 'string', description: '商品名称' },
|
||||
type: { type: 'integer', description: '商品类型' },
|
||||
category: { type: 'string', description: '分类' },
|
||||
spec: { type: 'string', description: '规格' },
|
||||
unit: { type: 'string', description: '单位' },
|
||||
price: { type: 'number', description: '销售价' },
|
||||
cost_price: { type: 'number', description: '成本价' },
|
||||
image: { type: 'string', description: '图片URL' },
|
||||
status: { type: 'integer', description: '状态:1上架 0下架' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
created_at: { type: 'string', description: '创建时间' },
|
||||
updated_at: { type: 'string', description: '更新时间' },
|
||||
},
|
||||
productPage: buildPage('productItem', '商品列表'),
|
||||
productListResponse: buildListResponse('productPage'),
|
||||
createProductRequest: {
|
||||
principal_id: { type: 'integer', required: true, description: '所属主体ID' },
|
||||
code: { type: 'string', required: true, description: '商品编码,主体内唯一' },
|
||||
name: { type: 'string', required: true, description: '商品名称' },
|
||||
type: { type: 'integer', description: '商品类型,默认1' },
|
||||
category: { type: 'string', description: '分类' },
|
||||
spec: { type: 'string', description: '规格' },
|
||||
unit: { type: 'string', description: '单位' },
|
||||
price: { type: 'number', required: true, description: '销售价' },
|
||||
cost_price: { type: 'number', description: '成本价' },
|
||||
image: { type: 'string', description: '图片URL' },
|
||||
status: { type: 'integer', description: '状态:1上架 0下架,默认1' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
},
|
||||
updateProductRequest: {
|
||||
principal_id: { type: 'integer', description: '所属主体ID' },
|
||||
code: { type: 'string', description: '商品编码' },
|
||||
name: { type: 'string', description: '商品名称' },
|
||||
type: { type: 'integer', description: '商品类型' },
|
||||
category: { type: 'string', description: '分类' },
|
||||
spec: { type: 'string', description: '规格' },
|
||||
unit: { type: 'string', description: '单位' },
|
||||
price: { type: 'number', description: '销售价' },
|
||||
cost_price: { type: 'number', description: '成本价' },
|
||||
image: { type: 'string', description: '图片URL' },
|
||||
status: { type: 'integer', description: '状态:1上架 0下架' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
},
|
||||
|
||||
// ---------- 组合商品 combo_products ----------
|
||||
comboProductItem: {
|
||||
id: { type: 'integer', description: '主键' },
|
||||
principal_id: { type: 'integer', description: '所属主体ID' },
|
||||
code: { type: 'string', description: '组合商品编码' },
|
||||
name: { type: 'string', description: '组合商品名称' },
|
||||
price: { type: 'number', description: '组合售价' },
|
||||
items: { type: 'string', description: '组合明细 JSON:[{ product_id: 1, quantity: 2 }]' },
|
||||
status: { type: 'integer', description: '状态:1上架 0下架' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
created_at: { type: 'string', description: '创建时间' },
|
||||
updated_at: { type: 'string', description: '更新时间' },
|
||||
},
|
||||
comboProductPage: buildPage('comboProductItem', '组合商品列表'),
|
||||
comboProductListResponse: buildListResponse('comboProductPage'),
|
||||
createComboProductRequest: {
|
||||
principal_id: { type: 'integer', required: true, description: '所属主体ID' },
|
||||
code: { type: 'string', required: true, description: '组合商品编码,主体内唯一' },
|
||||
name: { type: 'string', required: true, description: '组合商品名称' },
|
||||
price: { type: 'number', required: true, description: '组合售价' },
|
||||
items: { type: 'string', description: '组合明细 JSON 数组:[{ product_id: 1, quantity: 2 }]' },
|
||||
status: { type: 'integer', description: '状态:1上架 0下架,默认1' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
},
|
||||
updateComboProductRequest: {
|
||||
principal_id: { type: 'integer', description: '所属主体ID' },
|
||||
code: { type: 'string', description: '组合商品编码' },
|
||||
name: { type: 'string', description: '组合商品名称' },
|
||||
price: { type: 'number', description: '组合售价' },
|
||||
items: { type: 'string', description: '组合明细 JSON 数组' },
|
||||
status: { type: 'integer', description: '状态:1上架 0下架' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
},
|
||||
|
||||
// ---------- 菜单 menus ----------
|
||||
menuItem: {
|
||||
id: { type: 'integer', description: '主键' },
|
||||
parent_id: { type: 'integer', description: '父菜单ID,0 为根节点' },
|
||||
name: { type: 'string', description: '菜单名称' },
|
||||
type: { type: 'integer', description: '类型:1目录 2菜单 3按钮' },
|
||||
path: { type: 'string', description: '前端路由/地址' },
|
||||
icon: { type: 'string', description: '图标' },
|
||||
permission: { type: 'string', description: '权限标识,如 order:create' },
|
||||
sort: { type: 'integer', description: '排序,值越大越靠前' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用' },
|
||||
created_at: { type: 'string', description: '创建时间' },
|
||||
updated_at: { type: 'string', description: '更新时间' },
|
||||
},
|
||||
menuPage: buildPage('menuItem', '菜单列表'),
|
||||
menuListResponse: buildListResponse('menuPage'),
|
||||
createMenuRequest: {
|
||||
parent_id: { type: 'integer', description: '父菜单ID,默认0(根节点)' },
|
||||
name: { type: 'string', required: true, description: '菜单名称' },
|
||||
type: { type: 'integer', description: '类型:1目录 2菜单 3按钮,默认2' },
|
||||
path: { type: 'string', description: '前端路由/地址' },
|
||||
icon: { type: 'string', description: '图标' },
|
||||
permission: { type: 'string', description: '权限标识,如 order:create' },
|
||||
sort: { type: 'integer', description: '排序,默认0' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用,默认1' },
|
||||
},
|
||||
updateMenuRequest: {
|
||||
parent_id: { type: 'integer', description: '父菜单ID' },
|
||||
name: { type: 'string', description: '菜单名称' },
|
||||
type: { type: 'integer', description: '类型:1目录 2菜单 3按钮' },
|
||||
path: { type: 'string', description: '前端路由/地址' },
|
||||
icon: { type: 'string', description: '图标' },
|
||||
permission: { type: 'string', description: '权限标识' },
|
||||
sort: { type: 'integer', description: '排序' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用' },
|
||||
},
|
||||
|
||||
// ---------- 主体外部接口 principal_external_apis ----------
|
||||
externalApiItem: {
|
||||
id: { type: 'integer', description: '主键' },
|
||||
principal_id: { type: 'integer', description: '所属主体ID' },
|
||||
code: { type: 'string', description: '外部系统标识,如 wms / erp' },
|
||||
name: { type: 'string', description: '接口名称' },
|
||||
base_url: { type: 'string', description: '接口基础地址' },
|
||||
app_key: { type: 'string', description: '应用Key' },
|
||||
app_secret: { type: 'string', description: '应用密钥(建议加密存储)' },
|
||||
extra: { type: 'string', description: '扩展配置 JSON' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用' },
|
||||
created_at: { type: 'string', description: '创建时间' },
|
||||
updated_at: { type: 'string', description: '更新时间' },
|
||||
},
|
||||
externalApiPage: buildPage('externalApiItem', '接口配置列表'),
|
||||
externalApiListResponse: buildListResponse('externalApiPage'),
|
||||
createExternalApiRequest: {
|
||||
principal_id: { type: 'integer', required: true, description: '所属主体ID' },
|
||||
code: { type: 'string', required: true, description: '外部系统标识,如 wms;主体内唯一' },
|
||||
name: { type: 'string', required: true, description: '接口名称' },
|
||||
base_url: { type: 'string', description: '接口基础地址' },
|
||||
app_key: { type: 'string', description: '应用Key' },
|
||||
app_secret: { type: 'string', description: '应用密钥' },
|
||||
extra: { type: 'string', description: '扩展配置 JSON' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用,默认1' },
|
||||
},
|
||||
updateExternalApiRequest: {
|
||||
principal_id: { type: 'integer', description: '所属主体ID' },
|
||||
code: { type: 'string', description: '外部系统标识' },
|
||||
name: { type: 'string', description: '接口名称' },
|
||||
base_url: { type: 'string', description: '接口基础地址' },
|
||||
app_key: { type: 'string', description: '应用Key' },
|
||||
app_secret: { type: 'string', description: '应用密钥' },
|
||||
extra: { type: 'string', description: '扩展配置 JSON' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用' },
|
||||
},
|
||||
|
||||
// ---------- 订单 orders ----------
|
||||
orderItem: {
|
||||
id: { type: 'integer', description: '主键' },
|
||||
order_no: { type: 'string', description: '业务订单号,唯一' },
|
||||
principal_id: { type: 'integer', description: '所属主体ID' },
|
||||
order_type: { type: 'integer', description: '订单类型' },
|
||||
status: { type: 'integer', description: '主状态:1待处理 2处理中 3已完成 4已取消' },
|
||||
wms_status: { type: 'string', description: '外部WMS状态,如 CREATED/PICKING/SHIPPED' },
|
||||
wms_order_no: { type: 'string', description: '外部WMS单号' },
|
||||
wms_synced_at: { type: 'string', description: '最近一次WMS同步时间' },
|
||||
submit_status: { type: 'integer', description: '上交状态:0未上交 1上交中 2已上交 3上交失败' },
|
||||
submit_order_no: { type: 'string', description: '上交后返回的单号' },
|
||||
submit_at: { type: 'string', description: '上交时间' },
|
||||
submit_msg: { type: 'string', description: '上交结果/失败原因' },
|
||||
total_amount: { type: 'number', description: '订单金额' },
|
||||
pay_amount: { type: 'number', description: '实付金额' },
|
||||
receiver: { type: 'string', description: '收货人信息 JSON:{ name, phone, address }' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
created_at: { type: 'string', description: '创建时间' },
|
||||
updated_at: { type: 'string', description: '更新时间' },
|
||||
},
|
||||
orderPage: buildPage('orderItem', '订单列表'),
|
||||
orderListResponse: buildListResponse('orderPage'),
|
||||
createOrderRequest: {
|
||||
order_no: { type: 'string', required: true, description: '业务订单号,唯一' },
|
||||
principal_id: { type: 'integer', required: true, description: '所属主体ID' },
|
||||
order_type: { type: 'integer', description: '订单类型,默认1' },
|
||||
status: { type: 'integer', description: '主状态,默认1(待处理)' },
|
||||
wms_status: { type: 'string', description: '外部WMS状态' },
|
||||
wms_order_no: { type: 'string', description: '外部WMS单号' },
|
||||
total_amount: { type: 'number', description: '订单金额' },
|
||||
pay_amount: { type: 'number', description: '实付金额' },
|
||||
receiver: { type: 'string', description: '收货人信息 JSON:{ name, phone, address }' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
},
|
||||
updateOrderRequest: {
|
||||
order_no: { type: 'string', description: '业务订单号' },
|
||||
order_type: { type: 'integer', description: '订单类型' },
|
||||
status: { type: 'integer', description: '主状态:1待处理 2处理中 3已完成 4已取消' },
|
||||
total_amount: { type: 'number', description: '订单金额' },
|
||||
pay_amount: { type: 'number', description: '实付金额' },
|
||||
receiver: { type: 'string', description: '收货人信息 JSON' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
},
|
||||
/** 订单状态流转:主状态 + 上交(上报)状态 */
|
||||
updateOrderStatusRequest: {
|
||||
status: { type: 'integer', description: '主状态:1待处理 2处理中 3已完成 4已取消' },
|
||||
submit_status: { type: 'integer', description: '上交状态:0未上交 1上交中 2已上交 3上交失败' },
|
||||
submit_order_no: { type: 'string', description: '上交后返回的单号' },
|
||||
submit_msg: { type: 'string', description: '上交结果/失败原因' },
|
||||
},
|
||||
/** 外部 WMS 状态回写 */
|
||||
wmsStatusRequest: {
|
||||
wms_status: { type: 'string', required: true, description: '外部WMS状态,如 CREATED/PICKING/SHIPPED' },
|
||||
wms_order_no: { type: 'string', description: '外部WMS单号' },
|
||||
status: { type: 'integer', description: '同时更新主状态(可选)' },
|
||||
message: { type: 'string', description: '状态说明/异常原因' },
|
||||
},
|
||||
};
|
||||
220
backend/app/controller/auth.js
Normal file
220
backend/app/controller/auth.js
Normal file
@ -0,0 +1,220 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { generateSalt, hashPassword } = require('../lib/password');
|
||||
const { CODE_TTL, sendCode, verifyCode } = require('../lib/emailCode');
|
||||
|
||||
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
|
||||
/**
|
||||
* @controller AuthController 登录鉴权
|
||||
*/
|
||||
class AuthController extends Controller {
|
||||
/**
|
||||
* @summary 发送邮箱验证码
|
||||
* @description 注册前置步骤:校验邮箱格式与唯一性后,发送 6 位验证码(10 分钟内有效);
|
||||
* 受频率限制:同一邮箱 60 秒一次、每日上限 10 次,超限返回 429
|
||||
* @router post /api/auth/email-code
|
||||
* @request body sendEmailCodeRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async sendEmailCode() {
|
||||
const { ctx, app } = this;
|
||||
const { email } = ctx.request.body;
|
||||
|
||||
if (!email || !EMAIL_REGEX.test(email)) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '请填写正确的邮箱地址' };
|
||||
return;
|
||||
}
|
||||
|
||||
const exist = await ctx.model.User.findOne({ where: { email } });
|
||||
if (exist) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '邮箱已被注册' };
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await sendCode(app, email, { ip: ctx.ip, scene: 'register' });
|
||||
if (!result.ok) {
|
||||
ctx.status = 429;
|
||||
ctx.body = { code: 429, message: result.message };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
message: 'success',
|
||||
data: { email, expires_in: CODE_TTL },
|
||||
};
|
||||
}
|
||||
/**
|
||||
* @summary 账号密码登录(支持用户名或邮箱)
|
||||
* @description 校验登录账号或邮箱(account 字段)与加盐密码,成功后签发 JWT;token 载荷仅包含 user_id,不含敏感信息
|
||||
* @router post /api/auth/login
|
||||
* @request body loginRequest *body
|
||||
* @response 200 loginResponse success
|
||||
*/
|
||||
async login() {
|
||||
const { ctx, app } = this;
|
||||
const { account, password } = ctx.request.body;
|
||||
|
||||
if (!account || !password) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'account 与 password 为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await ctx.model.User.findOne({
|
||||
where: {
|
||||
[app.Sequelize.Op.or]: [{ username: account }, { email: account }],
|
||||
},
|
||||
});
|
||||
if (!user) {
|
||||
ctx.status = 401;
|
||||
ctx.body = { code: 401, message: '账号或密码错误' };
|
||||
return;
|
||||
}
|
||||
|
||||
if (Number(user.status) !== 1) {
|
||||
ctx.status = 403;
|
||||
ctx.body = { code: 403, message: '账号已禁用' };
|
||||
return;
|
||||
}
|
||||
|
||||
if (hashPassword(password, user.salt) !== user.password) {
|
||||
ctx.status = 401;
|
||||
ctx.body = { code: 401, message: '账号或密码错误' };
|
||||
return;
|
||||
}
|
||||
|
||||
const expiresIn = app.config.jwt.expiresIn || '2h';
|
||||
const token = app.jwt.sign({ user_id: user.id }, app.config.jwt.secret, { expiresIn });
|
||||
|
||||
await user.update({ last_login_at: new Date() });
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
message: 'success',
|
||||
data: {
|
||||
token,
|
||||
user_id: user.id,
|
||||
expires_in: this.parseExpiresIn(expiresIn),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 用户注册
|
||||
* @description 公开接口,无需登录;需先调用发送邮箱验证码接口完成邮箱认证,邮箱全局唯一;
|
||||
* 密码加盐存储,注册成功后直接返回 token
|
||||
* @router post /api/auth/register
|
||||
* @request body registerRequest *body
|
||||
* @response 200 loginResponse success
|
||||
*/
|
||||
async register() {
|
||||
const { ctx, app } = this;
|
||||
const { username, password, email, code, nickname, phone } = ctx.request.body;
|
||||
|
||||
if (!username || !password || !email || !code) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'username、password、email、code 为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
if (String(password).length < 6) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '密码长度不能少于 6 位' };
|
||||
return;
|
||||
}
|
||||
|
||||
if (!EMAIL_REGEX.test(email)) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '请填写正确的邮箱地址' };
|
||||
return;
|
||||
}
|
||||
|
||||
const usernameExist = await ctx.model.User.findOne({ where: { username } });
|
||||
if (usernameExist) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '账号已存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
const emailExist = await ctx.model.User.findOne({ where: { email } });
|
||||
if (emailExist) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '邮箱已被注册' };
|
||||
return;
|
||||
}
|
||||
|
||||
// 邮箱认证:校验验证码,通过后该验证码立即失效
|
||||
const verified = await verifyCode(app, email, code);
|
||||
if (!verified) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '邮箱验证码错误或已过期' };
|
||||
return;
|
||||
}
|
||||
|
||||
const salt = generateSalt();
|
||||
const user = await ctx.model.User.create({
|
||||
username,
|
||||
nickname: nickname || username,
|
||||
email,
|
||||
phone,
|
||||
salt,
|
||||
password: hashPassword(password, salt),
|
||||
status: 1,
|
||||
});
|
||||
|
||||
const expiresIn = app.config.jwt.expiresIn || '2h';
|
||||
const token = app.jwt.sign({ user_id: user.id }, app.config.jwt.secret, { expiresIn });
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
message: 'success',
|
||||
data: {
|
||||
token,
|
||||
user_id: user.id,
|
||||
expires_in: this.parseExpiresIn(expiresIn),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 当前登录用户信息
|
||||
* @description 需要登录:请求头 Authorization: Bearer <token>
|
||||
* @router get /api/auth/profile
|
||||
* @apikey
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async profile() {
|
||||
const { ctx } = this;
|
||||
const user = await ctx.model.User.findByPk(ctx.userId, {
|
||||
attributes: { exclude: [ 'password', 'salt' ] },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '用户不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: user };
|
||||
}
|
||||
|
||||
/**
|
||||
* 将有效期配置转换为秒数(如 2h => 7200)
|
||||
* @param {String|Number} expiresIn 有效期,如 2h / 7200
|
||||
* @return {Number} 有效秒数
|
||||
*/
|
||||
parseExpiresIn(expiresIn) {
|
||||
if (typeof expiresIn === 'number') return expiresIn;
|
||||
const matched = /^(\d+)([smhd])$/.exec(expiresIn);
|
||||
if (!matched) return 0;
|
||||
const units = { s: 1, m: 60, h: 3600, d: 86400 };
|
||||
return Number(matched[1]) * units[matched[2]];
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = AuthController;
|
||||
146
backend/app/controller/comboProduct.js
Normal file
146
backend/app/controller/comboProduct.js
Normal file
@ -0,0 +1,146 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* @controller ComboProductController 组合商品管理
|
||||
*/
|
||||
class ComboProductController extends Controller {
|
||||
/**
|
||||
* @summary 组合商品列表
|
||||
* @description 分页查询组合商品,支持按主体、关键词与状态过滤
|
||||
* @router get /api/combo-products
|
||||
* @apikey
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体)
|
||||
* @request query string keyword 关键词,匹配组合商品编码或名称
|
||||
* @request query integer status 状态:1上架 0下架,不传则不过滤
|
||||
* @response 200 comboProductListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const page = Number(ctx.query.page || 1);
|
||||
const pageSize = Number(ctx.query.pageSize || 20);
|
||||
const { keyword, status } = ctx.query;
|
||||
const principalId = ctx.state.principalId;
|
||||
|
||||
const where = {};
|
||||
where.principal_id = principalId;
|
||||
if (keyword) {
|
||||
where[Op.or] = [
|
||||
{ code: { [Op.like]: `%${keyword}%` } },
|
||||
{ name: { [Op.like]: `%${keyword}%` } },
|
||||
];
|
||||
}
|
||||
if (status !== undefined && status !== '') where.status = Number(status);
|
||||
|
||||
const { count, rows } = await ctx.model.ComboProduct.findAndCountAll({
|
||||
where,
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 组合商品详情
|
||||
* @description 按主键查询组合商品,items 为组合明细 JSON
|
||||
* @router get /api/combo-products/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 组合商品主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const combo = await ctx.model.ComboProduct.findByPk(ctx.params.id);
|
||||
|
||||
if (!combo) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '组合商品不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: combo };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 新增组合商品
|
||||
* @description 同一主体下组合商品编码 code 唯一;items 为组合明细
|
||||
* @router post /api/combo-products
|
||||
* @apikey
|
||||
* @request body createComboProductRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
const { principal_id: principalId, code, name, price } = ctx.request.body;
|
||||
|
||||
if (!principalId || !code || !name || price === undefined) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'principal_id、code、name、price 为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
const exist = await ctx.model.ComboProduct.findOne({ where: { principal_id: principalId, code } });
|
||||
if (exist) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '该主体下组合商品编码已存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
const combo = await ctx.model.ComboProduct.create(ctx.request.body);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: combo.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 更新组合商品
|
||||
* @description 未传入的字段保持原值;items 传 JSON 数组覆盖原明细
|
||||
* @router put /api/combo-products/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 组合商品主键ID
|
||||
* @request body updateComboProductRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const combo = await ctx.model.ComboProduct.findByPk(ctx.params.id);
|
||||
|
||||
if (!combo) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '组合商品不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
delete ctx.request.body.principal_id;
|
||||
await combo.update(ctx.request.body);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: combo.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 删除组合商品
|
||||
* @description 物理删除组合商品
|
||||
* @router delete /api/combo-products/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 组合商品主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const combo = await ctx.model.ComboProduct.findByPk(ctx.params.id);
|
||||
|
||||
if (!combo) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '组合商品不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
await combo.destroy();
|
||||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ComboProductController;
|
||||
178
backend/app/controller/menu.js
Normal file
178
backend/app/controller/menu.js
Normal file
@ -0,0 +1,178 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* @controller MenuController 菜单管理
|
||||
*/
|
||||
class MenuController extends Controller {
|
||||
/**
|
||||
* @summary 菜单列表
|
||||
* @description 分页查询菜单,支持按父级、类型与状态过滤
|
||||
* @router get /api/menus
|
||||
* @apikey
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query integer parent_id 父菜单ID,0 表示根节点
|
||||
* @request query integer type 类型:1目录 2菜单 3按钮,不传则不过滤
|
||||
* @request query integer status 状态:1启用 0禁用,不传则不过滤
|
||||
* @response 200 menuListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const page = Number(ctx.query.page || 1);
|
||||
const pageSize = Number(ctx.query.pageSize || 20);
|
||||
const { parent_id: parentId, type, status } = ctx.query;
|
||||
|
||||
const where = {};
|
||||
if (parentId !== undefined && parentId !== '') where.parent_id = Number(parentId);
|
||||
if (type !== undefined && type !== '') where.type = Number(type);
|
||||
if (status !== undefined && status !== '') where.status = Number(status);
|
||||
|
||||
const { count, rows } = await ctx.model.Menu.findAndCountAll({
|
||||
where,
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
order: [[ 'sort', 'DESC' ], [ 'id', 'ASC' ]],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 菜单树
|
||||
* @description 一次性返回全部菜单并按 parent_id 组装为树形结构
|
||||
* @router get /api/menus/tree
|
||||
* @apikey
|
||||
* @request query integer status 状态:1启用 0禁用,不传则返回全部
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async tree() {
|
||||
const { ctx } = this;
|
||||
const { status } = ctx.query;
|
||||
|
||||
const where = {};
|
||||
if (status !== undefined && status !== '') where.status = Number(status);
|
||||
|
||||
const list = await ctx.model.Menu.findAll({
|
||||
where,
|
||||
order: [[ 'sort', 'DESC' ], [ 'id', 'ASC' ]],
|
||||
});
|
||||
|
||||
const rows = list.map(item => item.toJSON());
|
||||
const map = new Map();
|
||||
const tree = [];
|
||||
|
||||
rows.forEach(item => {
|
||||
item.children = [];
|
||||
map.set(item.id, item);
|
||||
});
|
||||
rows.forEach(item => {
|
||||
const parent = map.get(item.parent_id);
|
||||
if (parent) {
|
||||
parent.children.push(item);
|
||||
} else {
|
||||
tree.push(item);
|
||||
}
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: tree };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 菜单详情
|
||||
* @description 按主键查询菜单
|
||||
* @router get /api/menus/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 菜单主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const menu = await ctx.model.Menu.findByPk(ctx.params.id);
|
||||
|
||||
if (!menu) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '菜单不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: menu };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 新增菜单
|
||||
* @description parent_id 不传默认为 0(根节点)
|
||||
* @router post /api/menus
|
||||
* @apikey
|
||||
* @request body createMenuRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
const { name } = ctx.request.body;
|
||||
|
||||
if (!name) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'name 为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
const menu = await ctx.model.Menu.create({
|
||||
parent_id: 0,
|
||||
type: 2,
|
||||
sort: 0,
|
||||
status: 1,
|
||||
...ctx.request.body,
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: { id: menu.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 更新菜单
|
||||
* @description 未传入的字段保持原值
|
||||
* @router put /api/menus/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 菜单主键ID
|
||||
* @request body updateMenuRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const menu = await ctx.model.Menu.findByPk(ctx.params.id);
|
||||
|
||||
if (!menu) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '菜单不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
await menu.update(ctx.request.body);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: menu.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 删除菜单
|
||||
* @description 物理删除菜单;存在子菜单时需先删除子菜单
|
||||
* @router delete /api/menus/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 菜单主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const menu = await ctx.model.Menu.findByPk(ctx.params.id);
|
||||
|
||||
if (!menu) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '菜单不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
await menu.destroy();
|
||||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = MenuController;
|
||||
226
backend/app/controller/order.js
Normal file
226
backend/app/controller/order.js
Normal file
@ -0,0 +1,226 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* @controller OrderController 订单管理
|
||||
*/
|
||||
class OrderController extends Controller {
|
||||
/**
|
||||
* @summary 订单列表
|
||||
* @description 分页查询订单,支持按主体、订单号、主状态、WMS 状态、上交状态过滤
|
||||
* @router get /api/orders
|
||||
* @apikey
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体)
|
||||
* @request query string order_no 业务订单号,支持模糊匹配
|
||||
* @request query integer status 主状态:1待处理 2处理中 3已完成 4已取消
|
||||
* @request query string wms_status 外部WMS状态,如 CREATED/PICKING/SHIPPED
|
||||
* @request query integer submit_status 上交状态:0未上交 1上交中 2已上交 3上交失败
|
||||
* @response 200 orderListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const page = Number(ctx.query.page || 1);
|
||||
const pageSize = Number(ctx.query.pageSize || 20);
|
||||
const {
|
||||
order_no: orderNo,
|
||||
status,
|
||||
wms_status: wmsStatus,
|
||||
submit_status: submitStatus,
|
||||
} = ctx.query;
|
||||
const principalId = ctx.state.principalId;
|
||||
|
||||
const where = {};
|
||||
where.principal_id = principalId;
|
||||
if (orderNo) where.order_no = { [Op.like]: `%${orderNo}%` };
|
||||
if (status !== undefined && status !== '') where.status = Number(status);
|
||||
if (wmsStatus) where.wms_status = wmsStatus;
|
||||
if (submitStatus !== undefined && submitStatus !== '') where.submit_status = Number(submitStatus);
|
||||
|
||||
const { count, rows } = await ctx.model.Order.findAndCountAll({
|
||||
where,
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 订单详情
|
||||
* @description 按主键查询订单,含主状态、WMS 状态与上交状态
|
||||
* @router get /api/orders/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 订单主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const order = await ctx.model.Order.findByPk(ctx.params.id);
|
||||
|
||||
if (!order) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '订单不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: order };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 新增订单
|
||||
* @description 订单号 order_no 全局唯一;初始主状态默认 1(待处理)
|
||||
* @router post /api/orders
|
||||
* @apikey
|
||||
* @request body createOrderRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
const { order_no: orderNo, principal_id: principalId } = ctx.request.body;
|
||||
|
||||
if (!orderNo || !principalId) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'order_no 与 principal_id 为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
const exist = await ctx.model.Order.findOne({ where: { order_no: orderNo } });
|
||||
if (exist) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '订单号已存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
const order = await ctx.model.Order.create({
|
||||
status: 1,
|
||||
submit_status: 0,
|
||||
...ctx.request.body,
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 更新订单
|
||||
* @description 未传入的字段保持原值;状态流转建议使用专用状态接口
|
||||
* @router put /api/orders/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 订单主键ID
|
||||
* @request body updateOrderRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const order = await ctx.model.Order.findByPk(ctx.params.id);
|
||||
|
||||
if (!order) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '订单不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
delete ctx.request.body.principal_id;
|
||||
await order.update(ctx.request.body);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 订单状态流转(主状态/上交状态)
|
||||
* @description 更新主状态与上交(上报)状态;上交成功时自动写入 submit_at
|
||||
* @router put /api/orders/{id}/status
|
||||
* @apikey
|
||||
* @request path integer *id 订单主键ID
|
||||
* @request body updateOrderStatusRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async updateStatus() {
|
||||
const { ctx } = this;
|
||||
const { status, submit_status: submitStatus, submit_order_no: submitOrderNo, submit_msg: submitMsg } = ctx.request.body;
|
||||
const order = await ctx.model.Order.findByPk(ctx.params.id);
|
||||
|
||||
if (!order) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '订单不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
const data = {};
|
||||
if (status !== undefined && status !== '') data.status = Number(status);
|
||||
if (submitStatus !== undefined && submitStatus !== '') {
|
||||
data.submit_status = Number(submitStatus);
|
||||
data.submit_at = new Date();
|
||||
}
|
||||
if (submitOrderNo !== undefined) data.submit_order_no = submitOrderNo;
|
||||
if (submitMsg !== undefined) data.submit_msg = submitMsg;
|
||||
|
||||
await order.update(data);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 外部WMS状态回写
|
||||
* @description 由 WMS 回调调用,更新外部WMS状态、WMS单号与同步时间
|
||||
* @router put /api/orders/{id}/wms-status
|
||||
* @apikey
|
||||
* @request path integer *id 订单主键ID
|
||||
* @request body wmsStatusRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async updateWmsStatus() {
|
||||
const { ctx } = this;
|
||||
const { wms_status: wmsStatus, wms_order_no: wmsOrderNo, status, message } = ctx.request.body;
|
||||
|
||||
if (!wmsStatus) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'wms_status 为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
const order = await ctx.model.Order.findByPk(ctx.params.id);
|
||||
if (!order) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '订单不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
const data = {
|
||||
wms_status: wmsStatus,
|
||||
wms_synced_at: new Date(),
|
||||
};
|
||||
if (wmsOrderNo !== undefined) data.wms_order_no = wmsOrderNo;
|
||||
if (status !== undefined && status !== '') data.status = Number(status);
|
||||
if (message !== undefined) data.submit_msg = message;
|
||||
|
||||
await order.update(data);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 删除订单
|
||||
* @description 物理删除订单
|
||||
* @router delete /api/orders/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 订单主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const order = await ctx.model.Order.findByPk(ctx.params.id);
|
||||
|
||||
if (!order) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '订单不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
await order.destroy();
|
||||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OrderController;
|
||||
144
backend/app/controller/principal.js
Normal file
144
backend/app/controller/principal.js
Normal file
@ -0,0 +1,144 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* @controller PrincipalController 主体管理
|
||||
*/
|
||||
class PrincipalController extends Controller {
|
||||
/**
|
||||
* @summary 主体列表
|
||||
* @description 分页查询主体,支持名称/编码模糊搜索、类型与状态过滤
|
||||
* @router get /api/principals
|
||||
* @apikey
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query string keyword 关键词,匹配主体编码或名称
|
||||
* @request query integer type 主体类型:1自营 2加盟 3外部,不传则不过滤
|
||||
* @request query integer status 状态:1启用 0禁用,不传则不过滤
|
||||
* @response 200 principalListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const page = Number(ctx.query.page || 1);
|
||||
const pageSize = Number(ctx.query.pageSize || 20);
|
||||
const { keyword, type, status } = ctx.query;
|
||||
|
||||
const where = {};
|
||||
if (keyword) {
|
||||
where[Op.or] = [
|
||||
{ code: { [Op.like]: `%${keyword}%` } },
|
||||
{ name: { [Op.like]: `%${keyword}%` } },
|
||||
];
|
||||
}
|
||||
if (type !== undefined && type !== '') where.type = Number(type);
|
||||
if (status !== undefined && status !== '') where.status = Number(status);
|
||||
|
||||
const { count, rows } = await ctx.model.Principal.findAndCountAll({
|
||||
where,
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 主体详情
|
||||
* @description 按主键查询主体
|
||||
* @router get /api/principals/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 主体主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const principal = await ctx.model.Principal.findByPk(ctx.params.id);
|
||||
|
||||
if (!principal) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '主体不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: principal };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 新增主体
|
||||
* @description 主体编码 code 全局唯一
|
||||
* @router post /api/principals
|
||||
* @apikey
|
||||
* @request body createPrincipalRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
const { code, name } = ctx.request.body;
|
||||
|
||||
if (!code || !name) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'code 与 name 为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
const exist = await ctx.model.Principal.findOne({ where: { code } });
|
||||
if (exist) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '主体编码已存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
const principal = await ctx.model.Principal.create(ctx.request.body);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: principal.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 更新主体
|
||||
* @description 未传入的字段保持原值
|
||||
* @router put /api/principals/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 主体主键ID
|
||||
* @request body updatePrincipalRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const principal = await ctx.model.Principal.findByPk(ctx.params.id);
|
||||
|
||||
if (!principal) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '主体不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
await principal.update(ctx.request.body);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: principal.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 删除主体
|
||||
* @description 物理删除主体;存在关联商品/订单时需先清理关联数据
|
||||
* @router delete /api/principals/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 主体主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const principal = await ctx.model.Principal.findByPk(ctx.params.id);
|
||||
|
||||
if (!principal) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '主体不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
await principal.destroy();
|
||||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PrincipalController;
|
||||
140
backend/app/controller/principalExternalApi.js
Normal file
140
backend/app/controller/principalExternalApi.js
Normal file
@ -0,0 +1,140 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* @controller PrincipalExternalApiController 主体外部接口管理
|
||||
*/
|
||||
class PrincipalExternalApiController extends Controller {
|
||||
/**
|
||||
* @summary 外部接口列表
|
||||
* @description 分页查询主体外部接口配置,支持按主体、系统标识与状态过滤
|
||||
* @router get /api/principal-external-apis
|
||||
* @apikey
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体)
|
||||
* @request query string code 外部系统标识,如 wms / erp
|
||||
* @request query integer status 状态:1启用 0禁用,不传则不过滤
|
||||
* @response 200 externalApiListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const page = Number(ctx.query.page || 1);
|
||||
const pageSize = Number(ctx.query.pageSize || 20);
|
||||
const { code, status } = ctx.query;
|
||||
const principalId = ctx.state.principalId;
|
||||
|
||||
const where = {};
|
||||
where.principal_id = principalId;
|
||||
if (code) where.code = code;
|
||||
if (status !== undefined && status !== '') where.status = Number(status);
|
||||
|
||||
const { count, rows } = await ctx.model.PrincipalExternalApi.findAndCountAll({
|
||||
where,
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 外部接口详情
|
||||
* @description 按主键查询接口配置,含密钥等敏感字段,注意权限控制
|
||||
* @router get /api/principal-external-apis/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 接口配置主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const api = await ctx.model.PrincipalExternalApi.findByPk(ctx.params.id);
|
||||
|
||||
if (!api) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '接口配置不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: api };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 新增外部接口配置
|
||||
* @description 同一主体下系统标识 code 唯一(如 wms)
|
||||
* @router post /api/principal-external-apis
|
||||
* @apikey
|
||||
* @request body createExternalApiRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
const { principal_id: principalId, code, name } = ctx.request.body;
|
||||
|
||||
if (!principalId || !code || !name) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'principal_id、code、name 为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
const exist = await ctx.model.PrincipalExternalApi.findOne({ where: { principal_id: principalId, code } });
|
||||
if (exist) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '该主体下该系统标识已配置' };
|
||||
return;
|
||||
}
|
||||
|
||||
const api = await ctx.model.PrincipalExternalApi.create(ctx.request.body);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: api.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 更新外部接口配置
|
||||
* @description 未传入的字段保持原值;app_secret 建议加密存储
|
||||
* @router put /api/principal-external-apis/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 接口配置主键ID
|
||||
* @request body updateExternalApiRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const api = await ctx.model.PrincipalExternalApi.findByPk(ctx.params.id);
|
||||
|
||||
if (!api) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '接口配置不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
delete ctx.request.body.principal_id;
|
||||
await api.update(ctx.request.body);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: api.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 删除外部接口配置
|
||||
* @description 物理删除接口配置
|
||||
* @router delete /api/principal-external-apis/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 接口配置主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const api = await ctx.model.PrincipalExternalApi.findByPk(ctx.params.id);
|
||||
|
||||
if (!api) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '接口配置不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
await api.destroy();
|
||||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PrincipalExternalApiController;
|
||||
149
backend/app/controller/principalUser.js
Normal file
149
backend/app/controller/principalUser.js
Normal file
@ -0,0 +1,149 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* @controller PrincipalUserController 主体用户关联管理
|
||||
*/
|
||||
class PrincipalUserController extends Controller {
|
||||
/**
|
||||
* @summary 关联列表
|
||||
* @description 分页查询主体与用户的关联关系,可按主体或用户过滤
|
||||
* @router get /api/principal-users
|
||||
* @apikey
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query integer principal_id 主体ID(必填,需当前账号已绑定该主体)
|
||||
* @request query integer user_id 用户ID,不传则不过滤
|
||||
* @request query string role 角色标识,精确匹配
|
||||
* @request query integer status 状态:1启用 0禁用,不传则不过滤
|
||||
* @response 200 principalUserListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const page = Number(ctx.query.page || 1);
|
||||
const pageSize = Number(ctx.query.pageSize || 20);
|
||||
const { user_id: userId, role, status } = ctx.query;
|
||||
const principalId = ctx.state.principalId;
|
||||
|
||||
const where = {};
|
||||
where.principal_id = principalId;
|
||||
if (userId) where.user_id = Number(userId);
|
||||
if (role) where.role = role;
|
||||
if (status !== undefined && status !== '') where.status = Number(status);
|
||||
|
||||
const { count, rows } = await ctx.model.PrincipalUser.findAndCountAll({
|
||||
where,
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 关联详情
|
||||
* @description 按主键查询关联记录,并带出用户与主体信息
|
||||
* @router get /api/principal-users/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 关联记录主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const relation = await ctx.model.PrincipalUser.findByPk(ctx.params.id, {
|
||||
include: [
|
||||
{ model: ctx.model.User, as: 'user', attributes: { exclude: [ 'password', 'salt' ] } },
|
||||
{ model: ctx.model.Principal, as: 'principal' },
|
||||
],
|
||||
});
|
||||
|
||||
if (!relation) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '关联记录不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: relation };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 绑定用户到主体
|
||||
* @description 建立主体与用户的关联;同一主体下同一用户仅允许一条记录
|
||||
* @router post /api/principal-users
|
||||
* @apikey
|
||||
* @request body bindPrincipalUserRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
const { principal_id: principalId, user_id: userId } = ctx.request.body;
|
||||
|
||||
if (!principalId || !userId) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'principal_id 与 user_id 为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
const exist = await ctx.model.PrincipalUser.findOne({
|
||||
where: { principal_id: principalId, user_id: userId },
|
||||
});
|
||||
if (exist) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '该用户已绑定到该主体' };
|
||||
return;
|
||||
}
|
||||
|
||||
const relation = await ctx.model.PrincipalUser.create(ctx.request.body);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: relation.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 更新关联信息
|
||||
* @description 可修改角色、默认主体标识与状态
|
||||
* @router put /api/principal-users/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 关联记录主键ID
|
||||
* @request body bindPrincipalUserRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const relation = await ctx.model.PrincipalUser.findByPk(ctx.params.id);
|
||||
|
||||
if (!relation) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '关联记录不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
delete ctx.request.body.principal_id;
|
||||
await relation.update(ctx.request.body);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: relation.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 解绑用户与主体
|
||||
* @description 物理删除关联记录
|
||||
* @router delete /api/principal-users/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 关联记录主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const relation = await ctx.model.PrincipalUser.findByPk(ctx.params.id);
|
||||
|
||||
if (!relation) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '关联记录不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
await relation.destroy();
|
||||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PrincipalUserController;
|
||||
149
backend/app/controller/product.js
Normal file
149
backend/app/controller/product.js
Normal file
@ -0,0 +1,149 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* @controller ProductController 商品管理
|
||||
*/
|
||||
class ProductController extends Controller {
|
||||
/**
|
||||
* @summary 商品列表
|
||||
* @description 分页查询商品,支持按主体、关键词与状态过滤
|
||||
* @router get /api/products
|
||||
* @apikey
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体)
|
||||
* @request query string keyword 关键词,匹配商品编码或名称
|
||||
* @request query string category 分类,精确匹配
|
||||
* @request query integer status 状态:1上架 0下架,不传则不过滤
|
||||
* @response 200 productListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const page = Number(ctx.query.page || 1);
|
||||
const pageSize = Number(ctx.query.pageSize || 20);
|
||||
const { keyword, category, status } = ctx.query;
|
||||
const principalId = ctx.state.principalId;
|
||||
|
||||
const where = {};
|
||||
where.principal_id = principalId;
|
||||
if (keyword) {
|
||||
where[Op.or] = [
|
||||
{ code: { [Op.like]: `%${keyword}%` } },
|
||||
{ name: { [Op.like]: `%${keyword}%` } },
|
||||
];
|
||||
}
|
||||
if (category) where.category = category;
|
||||
if (status !== undefined && status !== '') where.status = Number(status);
|
||||
|
||||
const { count, rows } = await ctx.model.Product.findAndCountAll({
|
||||
where,
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 商品详情
|
||||
* @description 按主键查询商品
|
||||
* @router get /api/products/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 商品主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const product = await ctx.model.Product.findByPk(ctx.params.id);
|
||||
|
||||
if (!product) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '商品不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: product };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 新增商品
|
||||
* @description 同一主体下商品编码 code 唯一
|
||||
* @router post /api/products
|
||||
* @apikey
|
||||
* @request body createProductRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
const { principal_id: principalId, code, name, price } = ctx.request.body;
|
||||
|
||||
if (!principalId || !code || !name || price === undefined) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'principal_id、code、name、price 为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
const exist = await ctx.model.Product.findOne({ where: { principal_id: principalId, code } });
|
||||
if (exist) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '该主体下商品编码已存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
const product = await ctx.model.Product.create(ctx.request.body);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: product.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 更新商品
|
||||
* @description 未传入的字段保持原值
|
||||
* @router put /api/products/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 商品主键ID
|
||||
* @request body updateProductRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const product = await ctx.model.Product.findByPk(ctx.params.id);
|
||||
|
||||
if (!product) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '商品不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
// 主体归属不可通过更新篡改,防止把资源移动到其它主体
|
||||
delete ctx.request.body.principal_id;
|
||||
await product.update(ctx.request.body);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: product.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 删除商品
|
||||
* @description 物理删除商品;被组合商品引用时需先解除引用
|
||||
* @router delete /api/products/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 商品主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const product = await ctx.model.Product.findByPk(ctx.params.id);
|
||||
|
||||
if (!product) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '商品不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
await product.destroy();
|
||||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ProductController;
|
||||
183
backend/app/controller/user.js
Normal file
183
backend/app/controller/user.js
Normal file
@ -0,0 +1,183 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { generateSalt, hashPassword } = require('../lib/password');
|
||||
|
||||
/**
|
||||
* @controller UserController 用户管理
|
||||
*/
|
||||
class UserController extends Controller {
|
||||
/**
|
||||
* @summary 用户列表
|
||||
* @description 分页查询用户,支持关键词模糊匹配(账号/昵称)与状态过滤
|
||||
* @router get /api/users
|
||||
* @apikey
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query string keyword 关键词,匹配登录账号或昵称
|
||||
* @request query integer status 状态:1启用 0禁用,不传则不过滤
|
||||
* @response 200 userListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const page = Number(ctx.query.page || 1);
|
||||
const pageSize = Number(ctx.query.pageSize || 20);
|
||||
const { keyword, status } = ctx.query;
|
||||
|
||||
const where = {};
|
||||
if (keyword) {
|
||||
where[Op.or] = [
|
||||
{ username: { [Op.like]: `%${keyword}%` } },
|
||||
{ nickname: { [Op.like]: `%${keyword}%` } },
|
||||
];
|
||||
}
|
||||
if (status !== undefined && status !== '') where.status = Number(status);
|
||||
|
||||
const { count, rows } = await ctx.model.User.findAndCountAll({
|
||||
where,
|
||||
attributes: { exclude: [ 'password', 'salt' ] },
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 用户详情
|
||||
* @description 按主键查询用户,不返回密码与盐值
|
||||
* @router get /api/users/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 用户主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const user = await ctx.model.User.findByPk(ctx.params.id, {
|
||||
attributes: { exclude: [ 'password', 'salt' ] },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '用户不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: user };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 新增用户
|
||||
* @description 密码传明文,服务端生成 salt 并以 sha256(password:salt) 落库
|
||||
* @router post /api/users
|
||||
* @apikey
|
||||
* @request body createUserRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
const { username, password } = ctx.request.body;
|
||||
|
||||
if (!username || !password) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'username 与 password 为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
const exist = await ctx.model.User.findOne({ where: { username } });
|
||||
if (exist) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '登录账号已存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
const salt = generateSalt();
|
||||
const user = await ctx.model.User.create({
|
||||
...ctx.request.body,
|
||||
salt,
|
||||
password: hashPassword(password, salt),
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: { id: user.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 更新用户
|
||||
* @description 未传入的字段保持原值;修改密码请调用重置密码接口
|
||||
* @router put /api/users/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 用户主键ID
|
||||
* @request body updateUserRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const user = await ctx.model.User.findByPk(ctx.params.id);
|
||||
|
||||
if (!user) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '用户不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
await user.update(ctx.request.body);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: user.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 重置用户密码
|
||||
* @description 重新生成盐值并更新加盐哈希密码
|
||||
* @router put /api/users/{id}/password
|
||||
* @apikey
|
||||
* @request path integer *id 用户主键ID
|
||||
* @request body resetPasswordRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async resetPassword() {
|
||||
const { ctx } = this;
|
||||
const { password } = ctx.request.body;
|
||||
|
||||
if (!password) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'password 为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await ctx.model.User.findByPk(ctx.params.id);
|
||||
if (!user) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '用户不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
const salt = generateSalt();
|
||||
await user.update({ salt, password: hashPassword(password, salt) });
|
||||
ctx.body = { code: 0, message: 'success', data: { id: user.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 删除用户
|
||||
* @description 物理删除用户记录
|
||||
* @router delete /api/users/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 用户主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const user = await ctx.model.User.findByPk(ctx.params.id);
|
||||
|
||||
if (!user) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '用户不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
await user.destroy();
|
||||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = UserController;
|
||||
194
backend/app/lib/emailCode.js
Normal file
194
backend/app/lib/emailCode.js
Normal file
@ -0,0 +1,194 @@
|
||||
'use strict';
|
||||
|
||||
const nodemailer = require('nodemailer');
|
||||
|
||||
/** 验证码有效期:10 分钟 */
|
||||
const CODE_TTL = 10 * 60;
|
||||
/** 每日计数缓存时间:24 小时 */
|
||||
const DAY_TTL = 24 * 60 * 60;
|
||||
/** 邮件主题 */
|
||||
const SUBJECT = 'OMS 注册邮箱验证码';
|
||||
|
||||
/**
|
||||
* 验证码在 Redis 中的 key
|
||||
* @param {String} email 邮箱
|
||||
* @return {String} redis key
|
||||
*/
|
||||
function codeKey(email) {
|
||||
return `oms:email:code:${email}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送间隔限制的 key
|
||||
* @param {String} email 邮箱
|
||||
* @return {String} redis key
|
||||
*/
|
||||
function intervalKey(email) {
|
||||
return `oms:email:limit:interval:${email}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 每日发送次数统计的 key(按自然日)
|
||||
* @param {String} email 邮箱
|
||||
* @return {String} redis key
|
||||
*/
|
||||
function dailyKey(email) {
|
||||
const now = new Date();
|
||||
const day = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
|
||||
return `oms:email:limit:daily:${email}:${day}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 6 位数字验证码
|
||||
* @return {String} 验证码
|
||||
*/
|
||||
function generateCode() {
|
||||
return String(Math.floor(100000 + Math.random() * 900000));
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录邮件发送日志
|
||||
* @param {Egg.Application} app egg application
|
||||
* @param {Object} data 日志数据
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async function writeLog(app, data) {
|
||||
try {
|
||||
await app.model.EmailLog.create(data);
|
||||
} catch (err) {
|
||||
// 日志写入失败不应影响主流程
|
||||
app.logger.error(`[email-code] 邮件日志写入失败:${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查发送频率是否超限
|
||||
* @param {Egg.Application} app egg application
|
||||
* @param {String} email 邮箱
|
||||
* @return {Promise<String>} 受限原因,空字符串表示通过
|
||||
*/
|
||||
async function checkLimit(app, email) {
|
||||
const { interval, dailyLimit } = app.config.emailCode;
|
||||
const [ locked, sent ] = await Promise.all([
|
||||
app.redis.get(intervalKey(email)),
|
||||
app.redis.get(dailyKey(email)),
|
||||
]);
|
||||
|
||||
if (locked) return `发送过于频繁,请 ${interval} 秒后再试`;
|
||||
if (sent && Number(sent) >= dailyLimit) return `今日发送次数已达上限(${dailyLimit} 次),请明日再试`;
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录一次成功发送
|
||||
* @param {Egg.Application} app egg application
|
||||
* @param {String} email 邮箱
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async function markSent(app, email) {
|
||||
const { interval } = app.config.emailCode;
|
||||
|
||||
await app.redis.set(intervalKey(email), '1', 'EX', interval);
|
||||
|
||||
const dk = dailyKey(email);
|
||||
const count = await app.redis.incr(dk);
|
||||
if (count === 1) await app.redis.expire(dk, DAY_TTL);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送邮箱验证码并缓存到 Redis(含频率限制与发送日志)
|
||||
* 未配置 SMTP(config.mailer.host 为空)时仅记录日志,便于本地开发调试
|
||||
* @param {Egg.Application} app egg application
|
||||
* @param {String} email 目标邮箱
|
||||
* @param {Object} options 附加信息:userId(注册场景为空)、ip、scene
|
||||
* @return {Promise<Object>} { ok: 是否发送成功, message: 失败原因 }
|
||||
*/
|
||||
async function sendCode(app, email, options = {}) {
|
||||
const { userId = null, ip = '', scene = 'register' } = options;
|
||||
|
||||
const limitMessage = await checkLimit(app, email);
|
||||
if (limitMessage) {
|
||||
await writeLog(app, {
|
||||
scene,
|
||||
to_email: email,
|
||||
subject: SUBJECT,
|
||||
content: '',
|
||||
user_id: userId,
|
||||
ip,
|
||||
status: 0,
|
||||
error_msg: limitMessage,
|
||||
});
|
||||
return { ok: false, message: limitMessage };
|
||||
}
|
||||
|
||||
const code = generateCode();
|
||||
const content = `您的注册验证码为:${code},${CODE_TTL / 60} 分钟内有效。`;
|
||||
await app.redis.set(codeKey(email), code, 'EX', CODE_TTL);
|
||||
|
||||
let errorMsg = '';
|
||||
const mailer = app.config.mailer;
|
||||
|
||||
if (!mailer.host) {
|
||||
app.logger.info(`[email-code] 未配置 SMTP,邮箱 ${email} 的验证码为:${code}`);
|
||||
} else {
|
||||
try {
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: mailer.host,
|
||||
port: mailer.port,
|
||||
secure: mailer.secure,
|
||||
auth: mailer.auth,
|
||||
});
|
||||
|
||||
await transporter.sendMail({
|
||||
from: mailer.from,
|
||||
to: email,
|
||||
subject: SUBJECT,
|
||||
text: content,
|
||||
});
|
||||
} catch (err) {
|
||||
errorMsg = err.message;
|
||||
app.logger.error(`[email-code] 邮件发送失败:${errorMsg}`);
|
||||
}
|
||||
}
|
||||
|
||||
await writeLog(app, {
|
||||
scene,
|
||||
to_email: email,
|
||||
subject: SUBJECT,
|
||||
content,
|
||||
user_id: userId,
|
||||
ip,
|
||||
status: errorMsg ? 0 : 1,
|
||||
error_msg: errorMsg || null,
|
||||
});
|
||||
|
||||
if (errorMsg) return { ok: false, message: '邮件发送失败,请稍后重试' };
|
||||
|
||||
await markSent(app, email);
|
||||
return { ok: true, message: '' };
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验邮箱验证码,通过后立即失效
|
||||
* @param {Egg.Application} app egg application
|
||||
* @param {String} email 邮箱
|
||||
* @param {String} code 验证码
|
||||
* @return {Promise<Boolean>} 校验是否通过
|
||||
*/
|
||||
async function verifyCode(app, email, code) {
|
||||
const cached = await app.redis.get(codeKey(email));
|
||||
if (!cached || cached !== String(code)) return false;
|
||||
|
||||
await app.redis.del(codeKey(email));
|
||||
return true;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
CODE_TTL,
|
||||
codeKey,
|
||||
intervalKey,
|
||||
dailyKey,
|
||||
sendCode,
|
||||
verifyCode,
|
||||
};
|
||||
29
backend/app/lib/password.js
Normal file
29
backend/app/lib/password.js
Normal file
@ -0,0 +1,29 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
|
||||
/**
|
||||
* 生成密码盐值
|
||||
* @return {String} 16 位十六进制盐值
|
||||
*/
|
||||
function generateSalt() {
|
||||
return crypto.randomBytes(8).toString('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* 对密码做加盐哈希:sha256(password:salt)
|
||||
* 生产环境建议替换为 bcrypt / scrypt 等慢哈希算法
|
||||
* @param {String} password 明文密码
|
||||
* @param {String} salt 盐值
|
||||
* @return {String} 哈希后的密文
|
||||
*/
|
||||
function hashPassword(password, salt) {
|
||||
return crypto.createHash('sha256')
|
||||
.update(`${password}:${salt}`)
|
||||
.digest('hex');
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
generateSalt,
|
||||
hashPassword,
|
||||
};
|
||||
33
backend/app/middleware/jwt_auth.js
Normal file
33
backend/app/middleware/jwt_auth.js
Normal file
@ -0,0 +1,33 @@
|
||||
'use strict';
|
||||
|
||||
const TOKEN_PREFIX = 'Bearer ';
|
||||
|
||||
/**
|
||||
* JWT 鉴权中间件
|
||||
* 校验请求头 Authorization: Bearer <token>,解析后仅取 user_id 挂载到 ctx.userId
|
||||
* @return {Function} koa 中间件
|
||||
*/
|
||||
module.exports = () => {
|
||||
return async (ctx, next) => {
|
||||
const app = ctx.app;
|
||||
const header = ctx.get('authorization') || '';
|
||||
const token = header.startsWith(TOKEN_PREFIX) ? header.slice(TOKEN_PREFIX.length) : header;
|
||||
|
||||
if (!token) {
|
||||
ctx.status = 401;
|
||||
ctx.body = { code: 401, message: '缺少登录凭证,请先登录' };
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// token 载荷仅包含 user_id,不含任何敏感信息
|
||||
const decoded = app.jwt.verify(token, app.config.jwt.secret);
|
||||
ctx.userId = decoded.user_id;
|
||||
ctx.state.userId = decoded.user_id;
|
||||
await next();
|
||||
} catch (err) {
|
||||
ctx.status = 401;
|
||||
ctx.body = { code: 401, message: '登录凭证无效或已过期' };
|
||||
}
|
||||
};
|
||||
};
|
||||
73
backend/app/middleware/principal_check.js
Normal file
73
backend/app/middleware/principal_check.js
Normal file
@ -0,0 +1,73 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 主体校验中间件(防跨主体操作)
|
||||
* 适用于“需要传入/关联主体ID(principal_id)”的请求:
|
||||
* - 取不到可校验的主体ID -> 400
|
||||
* - 当前账号未与该主体绑定(principal_users 无记录)-> 403
|
||||
* 校验通过后把 principalId 写入 ctx.state.principalId,供控制器做数据隔离(列表过滤、创建归属)。
|
||||
*
|
||||
* 解析与鉴权规则:
|
||||
* - 资源详情/更新/删除(带 :id 且配置了 model):以“资源记录本身的 principal_id”为准做鉴权,
|
||||
* 忽略请求体里的 principal_id,防止通过篡改请求体越权访问/移动其它主体的数据。
|
||||
* - 列表/新建(无 :id):以请求入参(body / query)里的 principal_id 为准。
|
||||
*
|
||||
* @param {Object} options 中间件配置项
|
||||
* @param {string} [options.model] 资源模型名,如 'Product',用于按 :id 反查资源所属主体
|
||||
* @return {Function} koa 中间件
|
||||
*/
|
||||
module.exports = (options = {}) => {
|
||||
const modelName = options.model;
|
||||
return async (ctx, next) => {
|
||||
const userId = ctx.userId;
|
||||
if (!userId) {
|
||||
ctx.status = 401;
|
||||
ctx.body = { code: 401, message: '缺少登录凭证,请先登录' };
|
||||
return;
|
||||
}
|
||||
|
||||
let principalId = null;
|
||||
let recordMissing = false;
|
||||
|
||||
if (modelName && ctx.params && ctx.params.id != null) {
|
||||
// 资源按 id 访问:以记录真实的 principal_id 鉴权
|
||||
const Model = ctx.model[modelName];
|
||||
if (Model) {
|
||||
const record = await Model.findByPk(ctx.params.id, { attributes: [ 'principal_id' ] });
|
||||
if (record) principalId = record.principal_id;
|
||||
else recordMissing = true; // 资源不存在,交给控制器返回 404,无需主体校验
|
||||
}
|
||||
} else {
|
||||
// 列表/新建:从入参取主体ID
|
||||
const body = ctx.request.body || {};
|
||||
const q = ctx.query || {};
|
||||
const p = ctx.params || {};
|
||||
if (body.principal_id != null) principalId = body.principal_id;
|
||||
else if (q.principal_id != null) principalId = q.principal_id;
|
||||
else if (p.principal_id != null) principalId = p.principal_id;
|
||||
else principalId = null;
|
||||
}
|
||||
|
||||
if (principalId == null || principalId === '') {
|
||||
if (recordMissing) return await next();
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '缺少主体ID(principal_id)' };
|
||||
return;
|
||||
}
|
||||
principalId = Number(principalId);
|
||||
|
||||
// 校验账号与主体的绑定关系
|
||||
const bound = await ctx.model.PrincipalUser.findOne({
|
||||
where: { user_id: userId, principal_id: principalId },
|
||||
attributes: [ 'id' ],
|
||||
});
|
||||
if (!bound) {
|
||||
ctx.status = 403;
|
||||
ctx.body = { code: 403, message: '无权操作该主体下的数据' };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.state.principalId = principalId;
|
||||
await next();
|
||||
};
|
||||
};
|
||||
112
backend/app/middleware/request_log.js
Normal file
112
backend/app/middleware/request_log.js
Normal file
@ -0,0 +1,112 @@
|
||||
'use strict';
|
||||
|
||||
/** 需要脱敏的请求头 */
|
||||
const SENSITIVE_HEADERS = [ 'authorization', 'cookie', 'set-cookie' ];
|
||||
/** 请求报文需脱敏字段(含邮箱验证码 code) */
|
||||
const SENSITIVE_REQUEST_FIELDS = [ 'password', 'token', 'app_secret', 'code', 'salt' ];
|
||||
/** 响应报文需脱敏字段(业务状态码 code 不脱敏,仅脱敏凭据类) */
|
||||
const SENSITIVE_RESPONSE_FIELDS = [ 'password', 'token', 'app_secret', 'salt' ];
|
||||
|
||||
/**
|
||||
* 对请求头脱敏
|
||||
* @param {Object} headers 原始请求头
|
||||
* @return {Object} 脱敏后的请求头
|
||||
*/
|
||||
function maskHeaders(headers) {
|
||||
if (!headers) return {};
|
||||
|
||||
const result = {};
|
||||
for (const key of Object.keys(headers)) {
|
||||
result[key] = SENSITIVE_HEADERS.includes(key.toLowerCase()) ? '***' : headers[key];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对报文对象中的敏感字段脱敏(浅层递归)
|
||||
* @param {*} value 原始值
|
||||
* @param {Array} fields 需要脱敏的字段名
|
||||
* @return {*} 脱敏后的值
|
||||
*/
|
||||
function maskValue(value, fields) {
|
||||
if (!value || typeof value !== 'object') return value;
|
||||
|
||||
const result = Array.isArray(value) ? [ ...value ] : { ...value };
|
||||
for (const key of Object.keys(result)) {
|
||||
if (fields.includes(key.toLowerCase())) {
|
||||
result[key] = '***';
|
||||
} else if (result[key] && typeof result[key] === 'object') {
|
||||
result[key] = maskValue(result[key], fields);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 序列化并限制长度
|
||||
* @param {*} value 待序列化的数据
|
||||
* @param {Number} maxLength 最大长度
|
||||
* @param {Array} fields 需要脱敏的字段名,为空则不脱敏
|
||||
* @return {String} 序列化后的字符串
|
||||
*/
|
||||
function serialize(value, maxLength, fields = []) {
|
||||
if (value === undefined || value === null) return '';
|
||||
|
||||
let text;
|
||||
try {
|
||||
text = typeof value === 'string' ? value : JSON.stringify(maskValue(value, fields));
|
||||
} catch (err) {
|
||||
// 循环引用或流对象等无法序列化
|
||||
text = '[unserializable]';
|
||||
}
|
||||
if (!text) return '';
|
||||
|
||||
return text.length > maxLength ? `${text.slice(0, maxLength)}...[truncated]` : text;
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求日志中间件(洋葱模型):
|
||||
* 进入时记录开始时间,await next() 执行后续中间件与控制器,
|
||||
* 返回时再读取 ctx.userId(此时路由级 JWT 中间件已解析出用户)并异步落库
|
||||
* @return {Function} koa 中间件
|
||||
*/
|
||||
module.exports = () => {
|
||||
return async (ctx, next) => {
|
||||
const config = ctx.app.config.requestLog;
|
||||
|
||||
if (config.excludePaths.some(prefix => ctx.path.startsWith(prefix))) {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
const start = Date.now();
|
||||
|
||||
try {
|
||||
await next();
|
||||
} catch (err) {
|
||||
throw err;
|
||||
} finally {
|
||||
const log = {
|
||||
method: ctx.method,
|
||||
url: ctx.originalUrl,
|
||||
headers: serialize(maskHeaders(ctx.request.headers), config.maxBodyLength),
|
||||
request_body: serialize(ctx.request.body, config.maxBodyLength, SENSITIVE_REQUEST_FIELDS),
|
||||
// 响应体仅脱敏凭据类字段(如登录返回的 token),保留业务状态码 code
|
||||
response_body: serialize(ctx.body, config.maxBodyLength, SENSITIVE_RESPONSE_FIELDS),
|
||||
status: ctx.status,
|
||||
user_id: ctx.userId || null,
|
||||
ip: ctx.ip,
|
||||
duration: Date.now() - start,
|
||||
};
|
||||
|
||||
// 后台异步写入,不阻塞响应
|
||||
ctx.runInBackground(async () => {
|
||||
try {
|
||||
await ctx.model.RequestLog.create(log);
|
||||
} catch (err) {
|
||||
ctx.logger.error(`[request-log] 写入失败:${err.message}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
};
|
||||
29
backend/app/model/comboProduct.js
Normal file
29
backend/app/model/comboProduct.js
Normal file
@ -0,0 +1,29 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 组合商品模型,对应 combo_products 表
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} comboProduct model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, DECIMAL, JSON, DATE } = app.Sequelize;
|
||||
|
||||
const ComboProduct = app.model.define('combo_product', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
|
||||
code: { type: STRING(50), allowNull: false, comment: '组合商品编码' },
|
||||
name: { type: STRING(100), allowNull: false, comment: '组合商品名称' },
|
||||
price: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '组合商品售价' },
|
||||
items: { type: JSON, comment: '组合明细:[{ "product_id": 1, "quantity": 2 }]' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1上架 0下架' },
|
||||
remark: { type: STRING(255), comment: '备注' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
});
|
||||
|
||||
ComboProduct.associate = () => {
|
||||
app.model.ComboProduct.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
};
|
||||
|
||||
return ComboProduct;
|
||||
};
|
||||
26
backend/app/model/emailLog.js
Normal file
26
backend/app/model/emailLog.js
Normal file
@ -0,0 +1,26 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 邮件发送日志模型,对应 email_logs 表
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} emailLog model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, TEXT, DATE } = app.Sequelize;
|
||||
|
||||
const EmailLog = app.model.define('email_log', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
scene: { type: STRING(30), allowNull: false, defaultValue: 'register', comment: '业务场景' },
|
||||
to_email: { type: STRING(100), allowNull: false, comment: '收件邮箱' },
|
||||
subject: { type: STRING(200), comment: '邮件标题' },
|
||||
content: { type: TEXT, comment: '邮件正文' },
|
||||
user_id: { type: BIGINT.UNSIGNED, comment: '关联用户ID,注册场景为空' },
|
||||
ip: { type: STRING(45), comment: '请求方IP' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '发送状态:1成功 0失败' },
|
||||
error_msg: { type: STRING(500), comment: '失败原因' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
});
|
||||
|
||||
return EmailLog;
|
||||
};
|
||||
26
backend/app/model/menu.js
Normal file
26
backend/app/model/menu.js
Normal file
@ -0,0 +1,26 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 菜单模型,对应 menus 表(通用菜单,不区分主体)
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} menu model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, INTEGER, DATE } = app.Sequelize;
|
||||
|
||||
const Menu = app.model.define('menu', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
parent_id: { type: BIGINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '父菜单ID,0 为根节点' },
|
||||
name: { type: STRING(50), allowNull: false, comment: '菜单名称' },
|
||||
type: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '类型:1目录 2菜单 3按钮' },
|
||||
path: { type: STRING(200), comment: '前端路由/地址' },
|
||||
icon: { type: STRING(100), comment: '图标' },
|
||||
permission: { type: STRING(100), comment: '权限标识,如 order:create' },
|
||||
sort: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '排序' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
});
|
||||
|
||||
return Menu;
|
||||
};
|
||||
38
backend/app/model/order.js
Normal file
38
backend/app/model/order.js
Normal file
@ -0,0 +1,38 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单模型,对应 orders 表
|
||||
* 含本系统主状态 status、外部 WMS 状态 wms_status、上交状态 submit_status
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} order model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, DECIMAL, JSON, DATE } = app.Sequelize;
|
||||
|
||||
const Order = app.model.define('order', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
order_no: { type: STRING(50), allowNull: false, comment: '业务订单号' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
|
||||
order_type: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '订单类型' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '主状态:1待处理 2处理中 3已完成 4已取消' },
|
||||
wms_status: { type: STRING(50), comment: '外部WMS状态' },
|
||||
wms_order_no: { type: STRING(50), comment: '外部WMS单号' },
|
||||
wms_synced_at: { type: DATE, comment: '最近一次WMS同步时间' },
|
||||
submit_status: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '上交状态:0未上交 1上交中 2已上交 3上交失败' },
|
||||
submit_order_no: { type: STRING(50), comment: '上交后返回的单号' },
|
||||
submit_at: { type: DATE, comment: '上交时间' },
|
||||
submit_msg: { type: STRING(255), comment: '上交结果/失败原因' },
|
||||
total_amount: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '订单金额' },
|
||||
pay_amount: { type: DECIMAL(12, 2), comment: '实付金额' },
|
||||
receiver: { type: JSON, comment: '收货人信息 JSON:{ name, phone, address }' },
|
||||
remark: { type: STRING(255), comment: '备注' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
});
|
||||
|
||||
Order.associate = () => {
|
||||
app.model.Order.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
};
|
||||
|
||||
return Order;
|
||||
};
|
||||
38
backend/app/model/principal.js
Normal file
38
backend/app/model/principal.js
Normal file
@ -0,0 +1,38 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 主体模型,对应 principals 表
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} principal model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize;
|
||||
|
||||
const Principal = app.model.define('principal', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
code: { type: STRING(50), allowNull: false, comment: '主体编码' },
|
||||
name: { type: STRING(100), allowNull: false, comment: '主体名称' },
|
||||
type: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '主体类型:1自营 2加盟 3外部' },
|
||||
contact_name: { type: STRING(50), comment: '联系人' },
|
||||
contact_phone: { type: STRING(20), comment: '联系电话' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
|
||||
remark: { type: STRING(255), comment: '备注' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
});
|
||||
|
||||
Principal.associate = () => {
|
||||
app.model.Principal.belongsToMany(app.model.User, {
|
||||
through: app.model.PrincipalUser,
|
||||
foreignKey: 'principal_id',
|
||||
otherKey: 'user_id',
|
||||
as: 'users',
|
||||
});
|
||||
app.model.Principal.hasMany(app.model.Product, { foreignKey: 'principal_id', as: 'products' });
|
||||
app.model.Principal.hasMany(app.model.ComboProduct, { foreignKey: 'principal_id', as: 'comboProducts' });
|
||||
app.model.Principal.hasMany(app.model.Order, { foreignKey: 'principal_id', as: 'orders' });
|
||||
app.model.Principal.hasMany(app.model.PrincipalExternalApi, { foreignKey: 'principal_id', as: 'externalApis' });
|
||||
};
|
||||
|
||||
return Principal;
|
||||
};
|
||||
30
backend/app/model/principalExternalApi.js
Normal file
30
backend/app/model/principalExternalApi.js
Normal file
@ -0,0 +1,30 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 主体外部接口模型,对应 principal_external_apis 表
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} principalExternalApi model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, JSON, DATE } = app.Sequelize;
|
||||
|
||||
const PrincipalExternalApi = app.model.define('principal_external_api', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
|
||||
code: { type: STRING(50), allowNull: false, comment: '外部系统标识,如 wms / erp' },
|
||||
name: { type: STRING(100), allowNull: false, comment: '接口名称' },
|
||||
base_url: { type: STRING(255), comment: '接口基础地址' },
|
||||
app_key: { type: STRING(100), comment: '应用Key' },
|
||||
app_secret: { type: STRING(255), comment: '应用密钥' },
|
||||
extra: { type: JSON, comment: '扩展配置' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
});
|
||||
|
||||
PrincipalExternalApi.associate = () => {
|
||||
app.model.PrincipalExternalApi.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
};
|
||||
|
||||
return PrincipalExternalApi;
|
||||
};
|
||||
28
backend/app/model/principalUser.js
Normal file
28
backend/app/model/principalUser.js
Normal file
@ -0,0 +1,28 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 主体用户关联模型,对应 principal_users 表
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} principalUser model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize;
|
||||
|
||||
const PrincipalUser = app.model.define('principal_user', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '主体ID' },
|
||||
user_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '用户ID' },
|
||||
role: { type: STRING(50), comment: '该主体下的角色标识' },
|
||||
is_default: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '是否默认主体:1是 0否' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
});
|
||||
|
||||
PrincipalUser.associate = () => {
|
||||
app.model.PrincipalUser.belongsTo(app.model.User, { foreignKey: 'user_id', as: 'user' });
|
||||
app.model.PrincipalUser.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
};
|
||||
|
||||
return PrincipalUser;
|
||||
};
|
||||
34
backend/app/model/product.js
Normal file
34
backend/app/model/product.js
Normal file
@ -0,0 +1,34 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 商品模型,对应 products 表
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} product model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, DECIMAL, DATE } = app.Sequelize;
|
||||
|
||||
const Product = app.model.define('product', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
|
||||
code: { type: STRING(50), allowNull: false, comment: '商品编码' },
|
||||
name: { type: STRING(100), allowNull: false, comment: '商品名称' },
|
||||
type: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '商品类型' },
|
||||
category: { type: STRING(50), comment: '分类' },
|
||||
spec: { type: STRING(100), comment: '规格' },
|
||||
unit: { type: STRING(20), comment: '单位' },
|
||||
price: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '销售价' },
|
||||
cost_price: { type: DECIMAL(12, 2), comment: '成本价' },
|
||||
image: { type: STRING(255), comment: '图片' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1上架 0下架' },
|
||||
remark: { type: STRING(255), comment: '备注' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
});
|
||||
|
||||
Product.associate = () => {
|
||||
app.model.Product.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
};
|
||||
|
||||
return Product;
|
||||
};
|
||||
27
backend/app/model/requestLog.js
Normal file
27
backend/app/model/requestLog.js
Normal file
@ -0,0 +1,27 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 请求日志模型,对应 request_logs 表
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} requestLog model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, INTEGER, TEXT, DATE } = app.Sequelize;
|
||||
|
||||
const RequestLog = app.model.define('request_log', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
method: { type: STRING(10), allowNull: false, comment: '请求方法' },
|
||||
url: { type: STRING(500), allowNull: false, comment: '请求地址(含 query)' },
|
||||
headers: { type: TEXT, comment: '请求头(敏感字段已脱敏)' },
|
||||
request_body: { type: TEXT, comment: '请求报文(敏感字段已脱敏)' },
|
||||
response_body: { type: TEXT, comment: '响应报文' },
|
||||
status: { type: INTEGER, comment: 'HTTP 状态码' },
|
||||
user_id: { type: BIGINT.UNSIGNED, comment: '解析到的用户ID,未登录为空' },
|
||||
ip: { type: STRING(45), comment: '请求方IP' },
|
||||
duration: { type: INTEGER, comment: '耗时(毫秒)' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
});
|
||||
|
||||
return RequestLog;
|
||||
};
|
||||
37
backend/app/model/user.js
Normal file
37
backend/app/model/user.js
Normal file
@ -0,0 +1,37 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 用户模型,对应 users 表(密码使用 password + salt 加盐存储)
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} user model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize;
|
||||
|
||||
const User = app.model.define('user', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
username: { type: STRING(50), allowNull: false, comment: '登录账号' },
|
||||
password: { type: STRING(255), allowNull: false, comment: '加盐哈希后的密码' },
|
||||
salt: { type: STRING(32), allowNull: false, comment: '密码盐值' },
|
||||
nickname: { type: STRING(50), comment: '昵称' },
|
||||
avatar: { type: STRING(255), comment: '头像' },
|
||||
email: { type: STRING(100), comment: '邮箱' },
|
||||
phone: { type: STRING(20), comment: '手机号' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
|
||||
last_login_at: { type: DATE, comment: '最后登录时间' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
});
|
||||
|
||||
User.associate = () => {
|
||||
// 用户与主体:多对多,通过主体用户关联表
|
||||
app.model.User.belongsToMany(app.model.Principal, {
|
||||
through: app.model.PrincipalUser,
|
||||
foreignKey: 'user_id',
|
||||
otherKey: 'principal_id',
|
||||
as: 'principals',
|
||||
});
|
||||
};
|
||||
|
||||
return User;
|
||||
};
|
||||
38
backend/app/router.js
Normal file
38
backend/app/router.js
Normal file
@ -0,0 +1,38 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* @param {Egg.Application} app - egg application
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { router, controller } = app;
|
||||
const jwtAuth = app.middleware.jwtAuth();
|
||||
const principalCheck = app.middleware.principalCheck;
|
||||
|
||||
router.get('/', controller.home.index);
|
||||
|
||||
// 注册、登录、邮箱验证码接口无需鉴权
|
||||
router.post('/api/auth/email-code', controller.auth.sendEmailCode);
|
||||
router.post('/api/auth/register', controller.auth.register);
|
||||
router.post('/api/auth/login', controller.auth.login);
|
||||
// 以下接口需要登录:请求头 Authorization: Bearer <token>
|
||||
router.get('/api/auth/profile', jwtAuth, controller.auth.profile);
|
||||
|
||||
// 菜单树需在 /api/menus/:id 之前注册,避免 tree 被当作 id 匹配
|
||||
router.get('/api/menus/tree', jwtAuth, controller.menu.tree);
|
||||
// 订单状态/外部 WMS 状态回写:按订单所属主体做跨主体隔离
|
||||
router.put('/api/orders/:id/status', jwtAuth, principalCheck({ model: 'Order' }), controller.order.updateStatus);
|
||||
router.put('/api/orders/:id/wms-status', jwtAuth, principalCheck({ model: 'Order' }), controller.order.updateWmsStatus);
|
||||
router.put('/api/users/:id/password', jwtAuth, controller.user.resetPassword);
|
||||
|
||||
// RESTful 资源路由:index / show / create / update / destroy(均需鉴权)
|
||||
router.resources('users', '/api/users', jwtAuth, controller.user);
|
||||
router.resources('principals', '/api/principals', jwtAuth, controller.principal);
|
||||
// 主体用户关联:需校验主体绑定关系
|
||||
router.resources('principalUsers', '/api/principal-users', jwtAuth, principalCheck({ model: 'PrincipalUser' }), controller.principalUser);
|
||||
// 以下资源均归属某个主体,需做主体校验与数据隔离,防止跨主体操作
|
||||
router.resources('products', '/api/products', jwtAuth, principalCheck({ model: 'Product' }), controller.product);
|
||||
router.resources('comboProducts', '/api/combo-products', jwtAuth, principalCheck({ model: 'ComboProduct' }), controller.comboProduct);
|
||||
router.resources('menus', '/api/menus', jwtAuth, controller.menu);
|
||||
router.resources('principalExternalApis', '/api/principal-external-apis', jwtAuth, principalCheck({ model: 'PrincipalExternalApi' }), controller.principalExternalApi);
|
||||
router.resources('orders', '/api/orders', jwtAuth, principalCheck({ model: 'Order' }), controller.order);
|
||||
};
|
||||
32
backend/app/schedule/clear_request_logs.js
Normal file
32
backend/app/schedule/clear_request_logs.js
Normal file
@ -0,0 +1,32 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 定时清理请求日志:每日凌晨 1 点执行,删除超过保留天数(默认 60 天)的记录
|
||||
*/
|
||||
module.exports = {
|
||||
schedule: {
|
||||
cron: '0 0 1 * * *',
|
||||
type: 'worker',
|
||||
disable: false,
|
||||
},
|
||||
|
||||
/**
|
||||
* 执行清理
|
||||
* @param {Egg.Context} ctx egg context(定时任务上下文)
|
||||
* @return {Promise<Number>} 删除的记录数
|
||||
*/
|
||||
async task(ctx) {
|
||||
const { keepDays } = ctx.app.config.requestLog;
|
||||
const Op = ctx.app.Sequelize.Op;
|
||||
const threshold = new Date(Date.now() - keepDays * 24 * 60 * 60 * 1000);
|
||||
|
||||
const count = await ctx.model.RequestLog.destroy({
|
||||
where: {
|
||||
created_at: { [Op.lt]: threshold },
|
||||
},
|
||||
});
|
||||
|
||||
ctx.logger.info(`[request-log] 已清理 ${keepDays} 天前的请求日志,共删除 ${count} 条`);
|
||||
return count;
|
||||
},
|
||||
};
|
||||
118
backend/config/config.default.js
Normal file
118
backend/config/config.default.js
Normal file
@ -0,0 +1,118 @@
|
||||
'use strict';
|
||||
|
||||
// 加载项目根目录 .env(敏感配置不入库);文件不存在时自动忽略
|
||||
require('dotenv').config();
|
||||
|
||||
const db = require('../database/config').development;
|
||||
|
||||
/**
|
||||
* @param {Egg.EggAppInfo} appInfo app info
|
||||
*/
|
||||
module.exports = appInfo => {
|
||||
/**
|
||||
* built-in config
|
||||
* @type {Egg.EggAppConfig}
|
||||
**/
|
||||
const config = exports = {};
|
||||
|
||||
// use for cookie sign key, should change to your own and keep security
|
||||
config.keys = appInfo.name + '_1720000000000_1234';
|
||||
|
||||
// 全局中间件:requestLog 记录请求日志(洋葱模型,在响应阶段读取用户信息)
|
||||
config.middleware = [ 'requestLog' ];
|
||||
|
||||
// 请求日志配置
|
||||
config.requestLog = {
|
||||
keepDays: Number(process.env.REQUEST_LOG_KEEP_DAYS || 60),
|
||||
maxBodyLength: Number(process.env.REQUEST_LOG_MAX_BODY || 2000),
|
||||
// 不记录的路径前缀(Swagger 静态资源等)
|
||||
excludePaths: [ '/swagger' ],
|
||||
};
|
||||
|
||||
// close csrf for easy debugging, please enable it in production if needed
|
||||
config.security = {
|
||||
csrf: {
|
||||
enable: false,
|
||||
},
|
||||
};
|
||||
|
||||
// sequelize / mysql config,与 sequelize-cli 迁移共用 database/config.js
|
||||
config.sequelize = {
|
||||
...db,
|
||||
define: {
|
||||
underscored: true,
|
||||
charset: 'utf8mb4',
|
||||
dialectOptions: {
|
||||
collate: 'utf8mb4_unicode_ci',
|
||||
},
|
||||
},
|
||||
pool: {
|
||||
max: 10,
|
||||
min: 0,
|
||||
idle: 10000,
|
||||
},
|
||||
};
|
||||
|
||||
// 邮件发送(SMTP)配置:未配置 SMTP_HOST 时验证码仅输出到日志,便于本地调试
|
||||
config.mailer = {
|
||||
host: process.env.SMTP_HOST || '',
|
||||
port: Number(process.env.SMTP_PORT || 465),
|
||||
secure: process.env.SMTP_SECURE !== 'false',
|
||||
auth: {
|
||||
user: process.env.SMTP_USER || '',
|
||||
pass: process.env.SMTP_PASS || '',
|
||||
},
|
||||
from: process.env.SMTP_FROM || 'noreply@oms.local',
|
||||
};
|
||||
|
||||
// Redis 配置:缓存邮箱验证码等数据,敏感信息建议用环境变量覆盖
|
||||
config.redis = {
|
||||
client: {
|
||||
host: process.env.REDIS_HOST || '127.0.0.1',
|
||||
port: Number(process.env.REDIS_PORT || 6379),
|
||||
password: process.env.REDIS_PASSWORD || 'qwe2019',
|
||||
db: 0,
|
||||
},
|
||||
};
|
||||
|
||||
// 邮箱验证码限流:同一邮箱发送间隔(秒)与每日发送上限
|
||||
config.emailCode = {
|
||||
interval: Number(process.env.EMAIL_CODE_INTERVAL || 60),
|
||||
dailyLimit: Number(process.env.EMAIL_CODE_DAILY_LIMIT || 10),
|
||||
};
|
||||
|
||||
// JWT 配置:secret 必须通过环境变量 JWT_SECRET 覆盖,切勿使用默认值上生产
|
||||
config.jwt = {
|
||||
secret: process.env.JWT_SECRET || 'oms-dev-jwt-secret-change-me',
|
||||
expiresIn: process.env.JWT_EXPIRES_IN || '2h',
|
||||
};
|
||||
|
||||
// swagger 文档:UI 访问 /swagger-ui.html,JSON 访问 /swagger-doc
|
||||
config.swaggerdoc = {
|
||||
dirScanner: './app/controller',
|
||||
basePath: '/',
|
||||
apiInfo: {
|
||||
title: 'OMS API',
|
||||
description: 'OMS 后端接口文档',
|
||||
version: '1.0.0',
|
||||
},
|
||||
schemes: [ 'http', 'https' ],
|
||||
consumes: [ 'application/json' ],
|
||||
produces: [ 'application/json' ],
|
||||
securityDefinitions: {
|
||||
apikey: {
|
||||
type: 'apiKey',
|
||||
name: 'Authorization',
|
||||
in: 'header',
|
||||
},
|
||||
},
|
||||
enableSecurity: true,
|
||||
routerMap: false,
|
||||
// 生产环境关闭文档
|
||||
enable: appInfo.env !== 'prod',
|
||||
};
|
||||
|
||||
return {
|
||||
...config,
|
||||
};
|
||||
};
|
||||
@ -9,6 +9,14 @@ const db = require('../database/config').development;
|
||||
module.exports = () => {
|
||||
const config = {};
|
||||
|
||||
// 开发环境监听端口,可通过 EGG_PORT 覆盖
|
||||
config.cluster = {
|
||||
listen: {
|
||||
port: Number(process.env.EGG_PORT || 6090),
|
||||
hostname: '127.0.0.1',
|
||||
},
|
||||
};
|
||||
|
||||
config.sequelize = {
|
||||
...db,
|
||||
define: {
|
||||
13
backend/config/config.unittest.js
Normal file
13
backend/config/config.unittest.js
Normal file
@ -0,0 +1,13 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 单元测试环境配置(npm run test-local 生效)
|
||||
*/
|
||||
module.exports = () => {
|
||||
return {
|
||||
// 测试环境不真实发送邮件,验证码仅输出到日志,避免依赖外部 SMTP
|
||||
mailer: {
|
||||
host: '',
|
||||
},
|
||||
};
|
||||
};
|
||||
@ -18,4 +18,8 @@ module.exports = {
|
||||
enable: true,
|
||||
package: 'egg-swagger-doc',
|
||||
},
|
||||
jwt: {
|
||||
enable: true,
|
||||
package: 'egg-jwt',
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,16 @@
|
||||
'use strict';
|
||||
|
||||
/** 为 users.email 增加唯一索引(MySQL 唯一索引允许多个 NULL,历史空邮箱数据不受影响) */
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.addIndex('users', {
|
||||
fields: [ 'email' ],
|
||||
unique: true,
|
||||
name: 'uk_users_email',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.removeIndex('users', 'uk_users_email');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,44 @@
|
||||
'use strict';
|
||||
|
||||
/** 邮件发送日志表:记录收件邮箱、正文、关联账号(注册场景为空)、IP 与发送结果 */
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable(
|
||||
'email_logs',
|
||||
{
|
||||
id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
autoIncrement: true,
|
||||
primaryKey: true,
|
||||
},
|
||||
scene: { type: Sequelize.STRING(30), allowNull: false, defaultValue: 'register', comment: '业务场景:register 等' },
|
||||
to_email: { type: Sequelize.STRING(100), allowNull: false, comment: '收件邮箱' },
|
||||
subject: { type: Sequelize.STRING(200), allowNull: true, comment: '邮件标题' },
|
||||
content: { type: Sequelize.TEXT, allowNull: true, comment: '邮件正文' },
|
||||
user_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: '关联用户ID,注册场景为空' },
|
||||
ip: { type: Sequelize.STRING(45), allowNull: true, comment: '请求方IP' },
|
||||
status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 0, comment: '发送状态:1成功 0失败' },
|
||||
error_msg: { type: Sequelize.STRING(500), allowNull: true, comment: '失败原因' },
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
},
|
||||
},
|
||||
{ charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '邮件发送日志表' }
|
||||
);
|
||||
|
||||
await queryInterface.addIndex('email_logs', { fields: [ 'to_email' ], name: 'idx_email_logs_to_email' });
|
||||
await queryInterface.addIndex('email_logs', { fields: [ 'created_at' ], name: 'idx_email_logs_created_at' });
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable('email_logs');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
|
||||
/** 请求日志表:记录请求地址、请求头、请求/响应报文、耗时、解析到的用户等 */
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable(
|
||||
'request_logs',
|
||||
{
|
||||
id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
autoIncrement: true,
|
||||
primaryKey: true,
|
||||
},
|
||||
method: { type: Sequelize.STRING(10), allowNull: false, comment: '请求方法' },
|
||||
url: { type: Sequelize.STRING(500), allowNull: false, comment: '请求地址(含 query)' },
|
||||
headers: { type: Sequelize.TEXT, allowNull: true, comment: '请求头(敏感字段已脱敏)' },
|
||||
request_body: { type: Sequelize.TEXT, allowNull: true, comment: '请求报文(敏感字段已脱敏)' },
|
||||
response_body: { type: Sequelize.TEXT, allowNull: true, comment: '响应报文' },
|
||||
status: { type: Sequelize.INTEGER, allowNull: true, comment: 'HTTP 状态码' },
|
||||
user_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: '解析到的用户ID,未登录为空' },
|
||||
ip: { type: Sequelize.STRING(45), allowNull: true, comment: '请求方IP' },
|
||||
duration: { type: Sequelize.INTEGER, allowNull: true, comment: '耗时(毫秒)' },
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
},
|
||||
},
|
||||
{ charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '请求日志表' }
|
||||
);
|
||||
|
||||
// 定时清理任务按创建时间删除
|
||||
await queryInterface.addIndex('request_logs', { fields: [ 'created_at' ], name: 'idx_request_logs_created_at' });
|
||||
await queryInterface.addIndex('request_logs', { fields: [ 'user_id' ], name: 'idx_request_logs_user_id' });
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable('request_logs');
|
||||
},
|
||||
};
|
||||
30
backend/database/seeders/20260909000200-init-admin-user.js
Normal file
30
backend/database/seeders/20260909000200-init-admin-user.js
Normal file
@ -0,0 +1,30 @@
|
||||
'use strict';
|
||||
|
||||
const { generateSalt, hashPassword } = require('../../app/lib/password');
|
||||
|
||||
const USERNAME = 'admin';
|
||||
const DEFAULT_PASSWORD = 'admin123';
|
||||
|
||||
/** 初始化超级管理员账号,登录后请及时修改密码 */
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const salt = generateSalt();
|
||||
const now = new Date();
|
||||
|
||||
await queryInterface.bulkInsert('users', [
|
||||
{
|
||||
username: USERNAME,
|
||||
password: hashPassword(DEFAULT_PASSWORD, salt),
|
||||
salt,
|
||||
nickname: '超级管理员',
|
||||
status: 1,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
},
|
||||
], {});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.bulkDelete('users', { username: USERNAME }, {});
|
||||
},
|
||||
};
|
||||
169
package-lock.json → backend/package-lock.json
generated
169
package-lock.json → backend/package-lock.json
generated
@ -8,12 +8,15 @@
|
||||
"name": "oms",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"dotenv": "^17.4.2",
|
||||
"egg": "^3.34.0",
|
||||
"egg-jwt": "^3.1.7",
|
||||
"egg-redis": "^2.6.1",
|
||||
"egg-scripts": "^3.1.0",
|
||||
"egg-sequelize": "^6.0.0",
|
||||
"egg-swagger-doc": "^2.3.2",
|
||||
"mysql2": "^3.24.4"
|
||||
"mysql2": "^3.24.4",
|
||||
"nodemailer": "^10.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"egg-bin": "^6.13.0",
|
||||
@ -2164,6 +2167,12 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/async": {
|
||||
"version": "1.5.2",
|
||||
"resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz",
|
||||
"integrity": "sha512-nSVgobk4rv61R9PUSDtYt7mPVB2olxNR5RWJcAsH676/ef11bUZwvu7+RGYrYauVdDPcO519v68wRhXQtxsV9w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/async-function": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/async-function/-/async-function-1.0.0.tgz",
|
||||
@ -2350,6 +2359,12 @@
|
||||
"ieee754": "^1.1.13"
|
||||
}
|
||||
},
|
||||
"node_modules/buffer-equal-constant-time": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
|
||||
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/buffer-from": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
|
||||
@ -3841,6 +3856,18 @@
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/dotenv": {
|
||||
"version": "17.4.2",
|
||||
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz",
|
||||
"integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==",
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://dotenvx.com"
|
||||
}
|
||||
},
|
||||
"node_modules/dottie": {
|
||||
"version": "2.0.7",
|
||||
"resolved": "https://registry.npmjs.org/dottie/-/dottie-2.0.7.tgz",
|
||||
@ -3923,6 +3950,15 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/ecdsa-sig-formatter": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
|
||||
"integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/editorconfig": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/editorconfig/-/editorconfig-1.0.7.tgz",
|
||||
@ -4301,6 +4337,19 @@
|
||||
"isstream": "~0.1.2"
|
||||
}
|
||||
},
|
||||
"node_modules/egg-jwt": {
|
||||
"version": "3.1.7",
|
||||
"resolved": "https://registry.npmjs.org/egg-jwt/-/egg-jwt-3.1.7.tgz",
|
||||
"integrity": "sha512-N3An6zn8f2AgbmRXAeJEL2sKhMDul3Sv1vPXr84FTBZDQUIvnhyRDBEoMz6X064aWlKVTIAApwK2OqyIoZGpvw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jsonwebtoken": "^8.3.0",
|
||||
"koa-jwt2": "^1.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/egg-logger": {
|
||||
"version": "3.6.1",
|
||||
"resolved": "https://registry.npmjs.org/egg-logger/-/egg-logger-3.6.1.tgz",
|
||||
@ -8042,6 +8091,49 @@
|
||||
"node": ">= 0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/jsonwebtoken": {
|
||||
"version": "8.5.1",
|
||||
"resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz",
|
||||
"integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jws": "^3.2.2",
|
||||
"lodash.includes": "^4.3.0",
|
||||
"lodash.isboolean": "^3.0.3",
|
||||
"lodash.isinteger": "^4.0.4",
|
||||
"lodash.isnumber": "^3.0.3",
|
||||
"lodash.isplainobject": "^4.0.6",
|
||||
"lodash.isstring": "^4.0.1",
|
||||
"lodash.once": "^4.0.0",
|
||||
"ms": "^2.1.1",
|
||||
"semver": "^5.6.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4",
|
||||
"npm": ">=1.4.28"
|
||||
}
|
||||
},
|
||||
"node_modules/jwa": {
|
||||
"version": "1.4.2",
|
||||
"resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.2.tgz",
|
||||
"integrity": "sha512-eeH5JO+21J78qMvTIDdBXidBd6nG2kZjg5Ohz/1fpa28Z4CcsWUzJ1ZZyFq/3z3N17aZy+ZuBoHljASbL1WfOw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"buffer-equal-constant-time": "^1.0.1",
|
||||
"ecdsa-sig-formatter": "1.0.11",
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/jws": {
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmjs.org/jws/-/jws-3.2.3.tgz",
|
||||
"integrity": "sha512-byiJ0FLRdLdSVSReO/U4E7RoEyOCKnEnEPMjq3HxWtvzLsV08/i5RQKsFVNkCldrCaPr2vDNAOMsfs8T/Hze7g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jwa": "^1.4.2",
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/keygrip": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/keygrip/-/keygrip-1.1.0.tgz",
|
||||
@ -8155,6 +8247,22 @@
|
||||
"integrity": "sha512-+97CtHAlWDx0ndt0J8y3P12EWLwTLMXIfMnYDev3wOTwH/RpBGMlfn4bDXlMEg1u73K6XRE9BbUp+5ZAYoRYWw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/koa-jwt2": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/koa-jwt2/-/koa-jwt2-1.0.3.tgz",
|
||||
"integrity": "sha512-ACW/sQ21vlkR/HBXnGvJfM2yDkKnv1GZe6/1nro+Mt4+bWhJq007esu2h9oZcj2+nce47PXcan2rXVaKmX295w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"async": "^1.5.0",
|
||||
"jsonwebtoken": "^8.1.0",
|
||||
"koa-unless": "^1.0.7",
|
||||
"lodash.isfunction": "^3.0.9",
|
||||
"lodash.set": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/koa-locales": {
|
||||
"version": "1.12.0",
|
||||
"resolved": "https://registry.npmjs.org/koa-locales/-/koa-locales-1.12.0.tgz",
|
||||
@ -8281,6 +8389,12 @@
|
||||
"node": ">= 7.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/koa-unless": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/koa-unless/-/koa-unless-1.0.7.tgz",
|
||||
"integrity": "sha512-NKiz+nk4KxSJFskiJMuJvxeA41Lcnx3d8Zy+8QETgifm4ab4aOeGD3RgR6bIz0FGNWwo3Fz0DtnK77mEIqHWxA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/koa/node_modules/debug": {
|
||||
"version": "4.4.3",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
|
||||
@ -8368,12 +8482,24 @@
|
||||
"integrity": "sha512-C5N2Z3DgnnKr0LOpv/hKCgKdb7ZZwafIrsesve6lmzvZIRZRGaZ/l6Q8+2W7NaT+ZwO3fFlSCzCzrDCFdJfZ4g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.includes": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
|
||||
"integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isarguments": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz",
|
||||
"integrity": "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isboolean": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
|
||||
"integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isempty": {
|
||||
"version": "4.4.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isempty/-/lodash.isempty-4.4.0.tgz",
|
||||
@ -8385,7 +8511,18 @@
|
||||
"version": "3.0.9",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isfunction/-/lodash.isfunction-3.0.9.tgz",
|
||||
"integrity": "sha512-AirXNj15uRIMMPihnkInB4i3NHeb4iBtNg9WRWuK2o31S+ePwwNmDPaTL3o7dTJ+VXNZim7rFs4rxN4YU1oUJw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isinteger": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
|
||||
"integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isnumber": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
|
||||
"integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isobject": {
|
||||
@ -8395,11 +8532,16 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isplainobject": {
|
||||
"version": "4.0.6",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
|
||||
"integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isstring": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
|
||||
"integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.merge": {
|
||||
@ -8409,6 +8551,18 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.once": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
|
||||
"integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.set": {
|
||||
"version": "4.3.2",
|
||||
"resolved": "https://registry.npmjs.org/lodash.set/-/lodash.set-4.3.2.tgz",
|
||||
"integrity": "sha512-4hNPN5jlm/N/HLMCO43v8BXKq9Z7QdAGc/VGrRD61w8gN9g/6jF9A4L1pbUgBLCffi0w9VsXfTOij5x8iTyFvg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/log-symbols": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz",
|
||||
@ -9554,6 +9708,15 @@
|
||||
"node": ">=4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/nodemailer": {
|
||||
"version": "10.0.1",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.0.1.tgz",
|
||||
"integrity": "sha512-c+gU9cL9HLDax3vjxL88kW+6NOgdtEUWaZ+AUtxdJR6LLhf0kGdCLExof7yiKW7zdO9EfXCSIgmhGyFmUM0mYQ==",
|
||||
"license": "MIT-0",
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/nopt": {
|
||||
"version": "7.2.1",
|
||||
"resolved": "https://registry.npmjs.org/nopt/-/nopt-7.2.1.tgz",
|
||||
@ -4,7 +4,7 @@
|
||||
"description": "OMS 后端服务(Egg.js)",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "egg-bin dev",
|
||||
"dev": "egg-bin dev --port 6090",
|
||||
"start": "egg-scripts start --daemon --title=egg-server-oms",
|
||||
"stop": "egg-scripts stop --title=egg-server-oms",
|
||||
"test": "npm run lint -- --fix && npm run test-local",
|
||||
@ -19,12 +19,15 @@
|
||||
"swagger:export": "node scripts/export-swagger.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"dotenv": "^17.4.2",
|
||||
"egg": "^3.34.0",
|
||||
"egg-jwt": "^3.1.7",
|
||||
"egg-redis": "^2.6.1",
|
||||
"egg-scripts": "^3.1.0",
|
||||
"egg-sequelize": "^6.0.0",
|
||||
"egg-swagger-doc": "^2.3.2",
|
||||
"mysql2": "^3.24.4"
|
||||
"mysql2": "^3.24.4",
|
||||
"nodemailer": "^10.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"egg-bin": "^6.13.0",
|
||||
201
backend/test/app/auth.test.js
Normal file
201
backend/test/app/auth.test.js
Normal file
@ -0,0 +1,201 @@
|
||||
'use strict';
|
||||
|
||||
const { app, assert } = require('egg-mock/bootstrap');
|
||||
const { generateSalt, hashPassword } = require('../../app/lib/password');
|
||||
const { codeKey, dailyKey, intervalKey } = require('../../app/lib/emailCode');
|
||||
|
||||
const USERNAME = 'auth_test_user';
|
||||
const PASSWORD = 'test123456';
|
||||
const REGISTER_USERNAME = 'auth_register_user';
|
||||
const REGISTER_EMAIL = 'auth_register_user@oms.test';
|
||||
|
||||
describe('test/app/auth.test.js', () => {
|
||||
let userId;
|
||||
|
||||
before(async () => {
|
||||
// 清理注册用例相关的 Redis 状态,避免限流影响重复执行
|
||||
await app.redis.del(codeKey(REGISTER_EMAIL));
|
||||
await app.redis.del(intervalKey(REGISTER_EMAIL));
|
||||
await app.redis.del(dailyKey(REGISTER_EMAIL));
|
||||
|
||||
const salt = generateSalt();
|
||||
const user = await app.model.User.create({
|
||||
username: USERNAME,
|
||||
password: hashPassword(PASSWORD, salt),
|
||||
salt,
|
||||
status: 1,
|
||||
});
|
||||
userId = user.id;
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await app.model.User.destroy({ where: { username: USERNAME } });
|
||||
await app.model.User.destroy({ where: { username: REGISTER_USERNAME } });
|
||||
});
|
||||
|
||||
it('should 401 when request without token', async () => {
|
||||
await app.httpRequest()
|
||||
.get('/api/users')
|
||||
.expect(401);
|
||||
});
|
||||
|
||||
it('should 401 when password is wrong', async () => {
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/auth/login')
|
||||
.send({ account: USERNAME, password: 'wrong-password' })
|
||||
.expect(401);
|
||||
|
||||
assert(res.body.code === 401);
|
||||
});
|
||||
|
||||
it('should login success and token only contains user_id', async () => {
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/auth/login')
|
||||
.send({ account: USERNAME, password: PASSWORD });
|
||||
assert(res.status === 200, `login failed: ${res.status} ${JSON.stringify(res.body)}`);
|
||||
|
||||
const { token, user_id: tokenUserId } = res.body.data;
|
||||
assert(token);
|
||||
assert(tokenUserId === userId);
|
||||
|
||||
// 校验载荷:仅包含 user_id(jwt 自带 iat/exp),不含任何敏感信息
|
||||
const decoded = app.jwt.verify(token, app.config.jwt.secret);
|
||||
assert(decoded.user_id === userId);
|
||||
assert(!decoded.password);
|
||||
assert(!decoded.salt);
|
||||
assert(!decoded.username);
|
||||
|
||||
// 携带 token 可正常访问受保护接口
|
||||
await app.httpRequest()
|
||||
.get('/api/users')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(200);
|
||||
|
||||
await app.httpRequest()
|
||||
.get('/api/auth/profile')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(200);
|
||||
});
|
||||
|
||||
it('should 400 when register without email code', async () => {
|
||||
await app.httpRequest()
|
||||
.post('/api/auth/register')
|
||||
.send({ username: 'no_code_user', password: PASSWORD, email: 'no_code@oms.test' })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('should send email code and register success', async () => {
|
||||
// 1. 发送邮箱验证码
|
||||
const sendRes = await app.httpRequest()
|
||||
.post('/api/auth/email-code')
|
||||
.send({ email: REGISTER_EMAIL })
|
||||
.expect(200);
|
||||
assert(sendRes.body.code === 0);
|
||||
|
||||
// 2. 从 Redis 取出验证码(SMTP 未配置时不会真实发信)
|
||||
const code = await app.redis.get(codeKey(REGISTER_EMAIL));
|
||||
assert(code && code.length === 6);
|
||||
|
||||
// 3. 携带验证码注册
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/auth/register')
|
||||
.send({ username: REGISTER_USERNAME, password: PASSWORD, email: REGISTER_EMAIL, code, nickname: '注册测试' });
|
||||
assert(res.status === 200, `register failed: ${res.status} ${JSON.stringify(res.body)}`);
|
||||
|
||||
const { token, user_id: newUserId } = res.body.data;
|
||||
assert(token);
|
||||
assert(newUserId > 0);
|
||||
|
||||
// 注册返回的 token 可直接访问受保护接口
|
||||
await app.httpRequest()
|
||||
.get('/api/auth/profile')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(200);
|
||||
|
||||
// 密码应为加盐哈希,不可明文反解
|
||||
const created = await app.model.User.findOne({ where: { username: REGISTER_USERNAME } });
|
||||
assert(created.password !== PASSWORD);
|
||||
assert(created.salt);
|
||||
});
|
||||
|
||||
it('should 400 when register email already exists', async () => {
|
||||
// 邮箱已被注册:发送验证码阶段即拦截
|
||||
const sendRes = await app.httpRequest()
|
||||
.post('/api/auth/email-code')
|
||||
.send({ email: REGISTER_EMAIL })
|
||||
.expect(400);
|
||||
|
||||
assert(sendRes.body.code === 400);
|
||||
|
||||
// 注册阶段同样拦截
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/auth/register')
|
||||
.send({ username: 'another_user', password: PASSWORD, email: REGISTER_EMAIL, code: '000000' })
|
||||
.expect(400);
|
||||
|
||||
assert(res.body.code === 400);
|
||||
});
|
||||
|
||||
it('should 400 when email code is wrong', async () => {
|
||||
await app.httpRequest()
|
||||
.post('/api/auth/email-code')
|
||||
.send({ email: 'wrong_code@oms.test' })
|
||||
.expect(200);
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/auth/register')
|
||||
.send({ username: 'wrong_code_user', password: PASSWORD, email: 'wrong_code@oms.test', code: '000000' })
|
||||
.expect(400);
|
||||
|
||||
assert(res.body.code === 400);
|
||||
});
|
||||
|
||||
it('should 400 when register params invalid', async () => {
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/auth/register')
|
||||
.send({ username: 'short_pwd_user', password: '123', email: 'bad-email', code: '123456' })
|
||||
.expect(400);
|
||||
|
||||
assert(res.body.code === 400);
|
||||
});
|
||||
|
||||
it('should 429 when send code too frequently', async () => {
|
||||
const email = 'freq_limit@oms.test';
|
||||
await app.redis.del(intervalKey(email), dailyKey(email), codeKey(email));
|
||||
|
||||
await app.httpRequest()
|
||||
.post('/api/auth/email-code')
|
||||
.send({ email })
|
||||
.expect(200);
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/auth/email-code')
|
||||
.send({ email })
|
||||
.expect(429);
|
||||
|
||||
assert(res.body.code === 429);
|
||||
await app.redis.del(intervalKey(email), dailyKey(email), codeKey(email));
|
||||
});
|
||||
|
||||
it('should 429 when daily limit reached', async () => {
|
||||
const email = 'daily_limit@oms.test';
|
||||
await app.redis.del(intervalKey(email), codeKey(email));
|
||||
// 直接把当日计数置为上限
|
||||
await app.redis.set(dailyKey(email), app.config.emailCode.dailyLimit);
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/auth/email-code')
|
||||
.send({ email })
|
||||
.expect(429);
|
||||
|
||||
assert(res.body.code === 429);
|
||||
await app.redis.del(dailyKey(email));
|
||||
});
|
||||
|
||||
it('should 401 when token is invalid', async () => {
|
||||
await app.httpRequest()
|
||||
.get('/api/users')
|
||||
.set('Authorization', 'Bearer invalid.token.value')
|
||||
.expect(401);
|
||||
});
|
||||
});
|
||||
84
backend/test/app/request_log.test.js
Normal file
84
backend/test/app/request_log.test.js
Normal file
@ -0,0 +1,84 @@
|
||||
'use strict';
|
||||
|
||||
const { app, assert } = require('egg-mock/bootstrap');
|
||||
|
||||
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
|
||||
describe('test/app/request_log.test.js', () => {
|
||||
it('should write request log after request', async () => {
|
||||
await app.httpRequest()
|
||||
.get('/')
|
||||
.expect(200);
|
||||
|
||||
// 等待后台异步写入
|
||||
await wait(600);
|
||||
|
||||
const log = await app.model.RequestLog.findOne({
|
||||
where: { url: '/' },
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
assert(log);
|
||||
assert(log.method === 'GET');
|
||||
assert(log.status === 200);
|
||||
assert(typeof log.duration === 'number');
|
||||
});
|
||||
|
||||
it('should mask sensitive headers and body', async () => {
|
||||
await app.httpRequest()
|
||||
.post('/api/auth/login')
|
||||
.set('Authorization', 'Bearer some-token-value')
|
||||
.send({ account: 'mask_test_user', password: 'secret-password' });
|
||||
|
||||
await wait(600);
|
||||
|
||||
const log = await app.model.RequestLog.findOne({
|
||||
where: { url: '/api/auth/login', method: 'POST' },
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
assert(log);
|
||||
// 请求头中的 token 已脱敏
|
||||
assert(log.headers.includes('***'));
|
||||
assert(!log.headers.includes('some-token-value'));
|
||||
// 请求报文中的密码已脱敏
|
||||
assert(log.request_body.includes('***'));
|
||||
assert(!log.request_body.includes('secret-password'));
|
||||
});
|
||||
|
||||
it('should mask token in response but keep business code', async () => {
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/auth/login')
|
||||
.send({ account: 'liufumingren', password: 'mingming1234' });
|
||||
|
||||
await wait(600);
|
||||
|
||||
const log = await app.model.RequestLog.findOne({
|
||||
where: { url: '/api/auth/login', method: 'POST' },
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
assert(log);
|
||||
// 登录响应中的 token 必须脱敏
|
||||
assert(log.response_body.includes('***'));
|
||||
if (res.body.data && res.body.data.token) {
|
||||
assert(!log.response_body.includes(res.body.data.token));
|
||||
}
|
||||
// 业务状态码 code 需保留,不被脱敏
|
||||
assert(log.response_body.includes('"code":0'));
|
||||
});
|
||||
|
||||
it('should delete logs older than keepDays', async () => {
|
||||
const { keepDays } = app.config.requestLog;
|
||||
const old = new Date(Date.now() - (keepDays + 1) * 24 * 60 * 60 * 1000);
|
||||
|
||||
const row = await app.model.RequestLog.create({ method: 'GET', url: '/expired-log' });
|
||||
await row.update({ created_at: old });
|
||||
|
||||
const deleted = await app.runSchedule('clear_request_logs');
|
||||
assert(deleted >= 1);
|
||||
|
||||
const exists = await app.model.RequestLog.findOne({ where: { url: '/expired-log' } });
|
||||
assert(!exists);
|
||||
});
|
||||
});
|
||||
@ -1,73 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const db = require('../database/config').development;
|
||||
|
||||
/**
|
||||
* @param {Egg.EggAppInfo} appInfo app info
|
||||
*/
|
||||
module.exports = appInfo => {
|
||||
/**
|
||||
* built-in config
|
||||
* @type {Egg.EggAppConfig}
|
||||
**/
|
||||
const config = exports = {};
|
||||
|
||||
// use for cookie sign key, should change to your own and keep security
|
||||
config.keys = appInfo.name + '_1720000000000_1234';
|
||||
|
||||
// add your middleware config here
|
||||
config.middleware = [];
|
||||
|
||||
// close csrf for easy debugging, please enable it in production if needed
|
||||
config.security = {
|
||||
csrf: {
|
||||
enable: false,
|
||||
},
|
||||
};
|
||||
|
||||
// sequelize / mysql config,与 sequelize-cli 迁移共用 database/config.js
|
||||
config.sequelize = {
|
||||
...db,
|
||||
define: {
|
||||
underscored: true,
|
||||
charset: 'utf8mb4',
|
||||
dialectOptions: {
|
||||
collate: 'utf8mb4_unicode_ci',
|
||||
},
|
||||
},
|
||||
pool: {
|
||||
max: 10,
|
||||
min: 0,
|
||||
idle: 10000,
|
||||
},
|
||||
};
|
||||
|
||||
// swagger 文档:UI 访问 /swagger-ui.html,JSON 访问 /swagger-doc
|
||||
config.swaggerdoc = {
|
||||
dirScanner: './app/controller',
|
||||
basePath: '/',
|
||||
apiInfo: {
|
||||
title: 'OMS API',
|
||||
description: 'OMS 后端接口文档',
|
||||
version: '1.0.0',
|
||||
},
|
||||
schemes: [ 'http', 'https' ],
|
||||
consumes: [ 'application/json' ],
|
||||
produces: [ 'application/json' ],
|
||||
securityDefinitions: {
|
||||
apikey: {
|
||||
type: 'apiKey',
|
||||
name: 'Authorization',
|
||||
in: 'header',
|
||||
},
|
||||
},
|
||||
enableSecurity: false,
|
||||
routerMap: false,
|
||||
// 生产环境关闭文档
|
||||
enable: appInfo.env !== 'prod',
|
||||
};
|
||||
|
||||
return {
|
||||
...config,
|
||||
};
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user