liufumingren bde5dc7bad feat(backend): 图片上传接入腾讯云 COS,新增存储管理与未引用清理
- 头像 / 文档图片改由后端校验并转发到 COS,密钥只留在服务端
- 新增 file_records 登记表(迁移 20261123170000),记录对象键、大小、上传者等
- 引用关系实时计算(用户头像 / 文档正文),改删业务数据后状态自动同步
- 新增平台管理「存储管理」页:引用状态与明细、单删、两步清理未引用
- 新增接口 GET /api/web/admin/files、POST /api/web/admin/files/cleanup、
  DELETE /api/web/admin/files/:id(仍被引用默认 409,force 才删)
- COS 目录前缀(COS_DIR_AVATAR / COS_DIR_DOC)、大小上限、清理保护期改为可配置

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-23 16:39:47 +08:00

76 lines
2.7 KiB
JavaScript
Raw 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 EDITABLE = [ 'nickname', 'avatar', 'phone', 'gender', 'email' ];
/**
* web 用户端:当前用户自己的资料(`/api/web/me`)
*
* 鉴权:`middleware.apiAuth()` —— header 里的 user JWT;**用户 ID 一律取自令牌**,
* 不接受前端传 id(不然就成越权改别人资料了)。
*/
class WebProfileController extends Controller {
/** GET /api/web/me —— 当前登录用户 */
async show() {
const { ctx } = this;
ctx.body = { ok: true, data: ctx.state.user };
}
/**
* PUT /api/web/me —— 改自己的资料
* body: `{ nickname?, avatar?, phone?, gender?, email? }`
*/
async update() {
const { ctx } = this;
const body = ctx.request.body || {};
const fields = {};
for (const key of EDITABLE) {
if (body[key] !== undefined) fields[key] = body[key];
}
if (!Object.keys(fields).length) ctx.throw(422, '没有可更新的字段');
if (fields.email !== undefined) {
fields.email = String(fields.email || '').trim().toLowerCase() || null;
}
if (fields.nickname !== undefined && !String(fields.nickname).trim()) {
ctx.throw(422, '昵称不能为空');
}
const user = await ctx.service.user.update(ctx.state.user.id, fields);
// 用户详情接口用的是同一份缓存,顺手失效
await ctx.service.cache.del(`user:${ctx.state.user.id}`);
ctx.logger.info('[web] 用户 %s 更新了资料', ctx.state.user.id);
ctx.body = { ok: true, data: user };
}
/** POST /api/web/me/avatar —— 上传当前用户头像到 COS */
async uploadAvatar() {
const { ctx } = this;
const image = await ctx.service.imageUpload.upload(await ctx.getFileStream(), {
category: 'avatar',
dir: `${this.config.cos.dirs.avatar}/${ctx.state.user.id}`,
});
ctx.body = { ok: true, data: image };
}
/**
* PUT /api/web/me/password —— 修改密码
* body: `{ oldPassword, newPassword }`
*/
async changePassword() {
const { ctx } = this;
const { oldPassword, newPassword } = ctx.request.body || {};
if (!oldPassword || !newPassword) ctx.throw(422, '请填写原密码与新密码');
if (String(newPassword).length < 6) ctx.throw(422, '新密码至少 6 位');
const changed = await ctx.service.auth.changePassword(ctx.state.user.id, oldPassword, newPassword);
if (!changed) ctx.throw(422, '原密码不正确');
ctx.logger.info('[web] 用户 %s 修改了密码', ctx.state.user.id);
ctx.body = { ok: true, data: { id: ctx.state.user.id } };
}
}
module.exports = WebProfileController;