liufumingren e49c25cd19 feat: 主体停用后下拉置灰不可切换、数据只读、定时任务跳过
- principalCheck 中间件加载主体状态:停用主体只放行读请求(GET/HEAD/OPTIONS)与导出任务提交,
  其余写操作(新建/编辑/推送/删除)一律 403「主体已停用,仅可查看与导出」
- 可选主体列表包含停用主体并按「启用优先」排序;/api/auth/profile 返回 status/disabled
- 顶栏主体下拉显示「xxx(已停用)」且不可选择;当前主体停用时在顶栏下方显示只读提示条
- 定时任务跳过停用主体:自动拉单、订单推送 WMS、发货推送、出库推送、发货结果回传平台、一键拉单任务
- 主体自身的 GET/PUT 未加主体状态校验,运维仍可通过接口重新启用

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-05 23:31:45 +08:00

539 lines
16 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'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() });
// 登录时间变更,失效用户缓存,下次请求重新加载
await ctx.service.cache.invalidateUser(user.id);
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, 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,
// 注册不再填写昵称:账号显示名称改到主体账号关联表(principal_users.name)维护
nickname: null,
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;
// JWT 中间件已从缓存加载用户,这里不再查库
const user = ctx.user || await ctx.service.cache.getUser(ctx.userId);
if (!user) {
ctx.status = 404;
ctx.body = { code: 404, message: '用户不存在' };
return;
}
// 返回用户所属主体列表,供前端判断是否已创建主体(多租户隔离);走缓存的可选主体列表
// 同时带出当前账号在每个主体下的名称/头像(principal_users.name / avatar),供右上角展示
const options = await ctx.service.cache.getUserPrincipalOptions(ctx.userId);
const relations = await ctx.model.PrincipalUser.findAll({
where: { user_id: ctx.userId },
attributes: [ 'principal_id', 'name', 'avatar' ],
});
const relationMap = new Map(relations.map(r => [ Number(r.principal_id), r ]));
const principals = options.map(item => {
const relation = relationMap.get(Number(item.id));
return {
id: item.id,
name: item.name,
// 主体停用时前端置灰不可选,并提示只能查看
status: item.status,
disabled: Number(item.status) !== 1,
account_name: (relation && relation.name) || null,
account_avatar: (relation && relation.avatar) || null,
};
});
ctx.body = { code: 0, message: 'success', data: { ...user, principals } };
}
/**
* @summary 发送邮箱登录验证码
* @description 公开接口,无需登录:邮箱必须已注册,发送 6 位数字验证码(10 分钟有效);
* 受频率限制:同一邮箱 60 秒一次、每日上限 10 次,超限返回 429
* @router post /api/auth/email-login/code
* @request body sendLoginCodeRequest *body
* @response 200 baseResponse success
*/
async sendLoginCode() {
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 user = await ctx.model.User.findOne({ where: { email } });
if (!user) {
ctx.status = 400;
ctx.body = { code: 400, message: '该邮箱未注册,请先注册账号' };
return;
}
const result = await sendCode(app, email, {
userId: user.id,
ip: ctx.ip,
scene: 'login',
length: 6,
subject: 'OMS 邮箱登录验证码',
});
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 公开接口,无需登录:校验 6 位验证码(通过后立即失效),
* 校验通过后直接签发 JWT;账号被禁用时返回 403
* @router post /api/auth/email-login
* @request body emailLoginRequest *body
* @response 200 loginResponse success
*/
async loginByEmailCode() {
const { ctx, app } = this;
const { email, code } = ctx.request.body;
if (!email || !EMAIL_REGEX.test(email)) {
ctx.status = 400;
ctx.body = { code: 400, message: '请填写正确的邮箱地址' };
return;
}
if (!code) {
ctx.status = 400;
ctx.body = { code: 400, message: 'email 与 code 为必填项' };
return;
}
const user = await ctx.model.User.findOne({ where: { email } });
if (!user) {
ctx.status = 400;
ctx.body = { code: 400, message: '该邮箱未注册,请先注册账号' };
return;
}
if (Number(user.status) !== 1) {
ctx.status = 403;
ctx.body = { code: 403, message: '账号已禁用' };
return;
}
const verified = await verifyCode(app, email, code, 'login');
if (!verified) {
ctx.status = 400;
ctx.body = { code: 400, 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 公开接口,无需登录:邮箱必须已注册,发送 4 位数字验证码(10 分钟有效);
* 受频率限制:同一邮箱 60 秒一次、每日上限 10 次,超限返回 429
* @router post /api/auth/reset-password/code
* @request body sendResetCodeRequest *body
* @response 200 baseResponse success
*/
async sendResetCode() {
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 user = await ctx.model.User.findOne({ where: { email } });
if (!user) {
ctx.status = 400;
ctx.body = { code: 400, message: '该邮箱未注册' };
return;
}
const result = await sendCode(app, email, {
userId: user.id,
ip: ctx.ip,
scene: 'reset-password',
length: 4,
subject: 'OMS 密码重置验证码',
});
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 公开接口,无需登录:校验 4 位验证码(通过后立即失效),
* 然后重新生成盐值并更新加盐哈希密码;新密码不少于 6 位
* @router post /api/auth/reset-password
* @request body resetPasswordByCodeRequest *body
* @response 200 baseResponse success
*/
async resetPasswordByCode() {
const { ctx, app } = this;
const { email, code, password } = ctx.request.body;
if (!email || !EMAIL_REGEX.test(email)) {
ctx.status = 400;
ctx.body = { code: 400, message: '请填写正确的邮箱地址' };
return;
}
if (!code || !password) {
ctx.status = 400;
ctx.body = { code: 400, message: '验证码与新密码均为必填项' };
return;
}
if (String(password).length < 6) {
ctx.status = 400;
ctx.body = { code: 400, message: '新密码长度不能少于 6 位' };
return;
}
const user = await ctx.model.User.findOne({ where: { email } });
if (!user) {
ctx.status = 400;
ctx.body = { code: 400, message: '该邮箱未注册' };
return;
}
const verified = await verifyCode(app, email, code, 'reset-password');
if (!verified) {
ctx.status = 400;
ctx.body = { code: 400, message: '验证码错误或已过期' };
return;
}
const salt = generateSalt();
await user.update({ salt, password: hashPassword(password, salt) });
await ctx.service.cache.invalidateUser(user.id);
ctx.body = { code: 0, message: 'success', data: { id: user.id } };
}
/**
* @summary 修改当前登录用户资料
* @description 自助服务:仅可修改邮箱与手机号,不涉及密码、账号与状态;
* 昵称/头像已改到「账号(主体账号关联)」处按主体维护(principal_users.name / avatar),
* 本接口不再接受 nickname / avatar
* @router put /api/auth/profile
* @apikey
* @request body updateProfileRequest *body
* @response 200 baseResponse success
*/
async updateProfile() {
const { ctx } = this;
const user = await ctx.model.User.findByPk(ctx.userId);
if (!user) {
ctx.status = 404;
ctx.body = { code: 404, message: '用户不存在' };
return;
}
const { email, phone } = ctx.request.body;
if (email && !EMAIL_REGEX.test(email)) {
ctx.status = 400;
ctx.body = { code: 400, message: '邮箱格式不正确' };
return;
}
if (email) {
const exist = await ctx.model.User.findOne({ where: { email } });
if (exist && Number(exist.id) !== Number(user.id)) {
ctx.status = 400;
ctx.body = { code: 400, message: '该邮箱已被使用' };
return;
}
}
// 昵称/头像不再通过「我的」维护(改到账号处按主体设置),此处忽略传入值
const patch = {};
if (email !== undefined) patch.email = email;
if (phone !== undefined) patch.phone = phone;
await user.update(patch);
await ctx.service.cache.invalidateUser(user.id);
const updated = await ctx.model.User.findByPk(user.id, {
attributes: { exclude: [ 'password', 'salt' ] },
});
ctx.body = { code: 0, message: 'success', data: updated };
}
/**
* @summary 修改当前登录用户密码
* @description 自助服务:需校验原密码,通过后重新生成盐值并更新加盐哈希密码;新密码不少于 6 位且不能与原密码相同
* @router put /api/auth/password
* @apikey
* @request body changePasswordRequest *body
* @response 200 baseResponse success
*/
async changePassword() {
const { ctx } = this;
const { old_password: oldPassword, password } = ctx.request.body;
if (!oldPassword || !password) {
ctx.status = 400;
ctx.body = { code: 400, message: '原密码与新密码均为必填项' };
return;
}
if (String(password).length < 6) {
ctx.status = 400;
ctx.body = { code: 400, message: '新密码长度不少于 6 位' };
return;
}
const user = await ctx.model.User.findByPk(ctx.userId);
if (!user) {
ctx.status = 404;
ctx.body = { code: 404, message: '用户不存在' };
return;
}
if (hashPassword(oldPassword, user.salt) !== user.password) {
ctx.status = 400;
ctx.body = { code: 400, message: '原密码不正确' };
return;
}
if (oldPassword === password) {
ctx.status = 400;
ctx.body = { code: 400, message: '新密码不能与原密码相同' };
return;
}
const salt = generateSalt();
await user.update({ salt, password: hashPassword(password, salt) });
await ctx.service.cache.invalidateUser(user.id);
ctx.body = { code: 0, message: 'success', data: { id: user.id } };
}
/**
* 将有效期配置转换为秒数(如 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;