const jwt = require("jsonwebtoken"); const { createAccount, getAccountInfo } = require("../service/account.service"); const Response = require("../utils/response"); const { JWT_SECRET } = require("../config/config.default"); const { accountRegisterError, userLoginError, } = require("../constant/err.type"); class AccountController { async register(ctx, next) { const { username, password, role } = ctx.request.body; try { const res = await createAccount( username, password, role == "1" ? role : "0" ); ctx.body = Response(0, "用户注册成功", { id: res.id, username: res.username, }); } catch (error) { ctx.app.emit("error", accountRegisterError, ctx); } } async login(ctx, next) { const { username } = ctx.request.body; try { // 从返回结果对象中剔除password属性, 将剩下的属性放到res对象 const { password, ...res } = await getAccountInfo({ username }); ctx.body = Response(0, "用户登录成功", { token: jwt.sign(res, JWT_SECRET, { expiresIn: "1d" }), }); } catch (err) { ctx.app.emit("error", userLoginError, ctx); } } } module.exports = new AccountController();