'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 }; } /** * 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;