灏天阁

Node/Koa2[42]: 修改密码

· Yin灏

src/routes/api/user.js

//...
const { changePassword } = require("../../controller/user");
//...
const { loginCheck } = require("../../middlewares/loginChecks");
const userValidate = require("../../validator/user");
const { genValidator } = require("../../middlewares/validator");
// patch 更新数据
router.patch(
  "/changePassword",
  loginCheck,
  // 验证密码信息中间件
  genValidator(userValidate),
  async (ctx, next) => {
    const { password, newPassword } = ctx.request.body;
    const { userName } = ctx.session.userInfo;
    // controller 层
    ctx.body = await changePassword(userName, password, newPassword);
  }
);
//...

controller 层处理

src/controller/user.js

//..
const { SuccessModel, ErrorModel } = require("../model/ResModel");
const { changePasswordFailInfo } = require("../model/ErrorInfo");
const { updateUser } = require("../services/user");
//...
async function changePassword(userName, password, newPassword) {
  const result = await updateUser(
    {
      newPassword: doCrypto(newPassword),
    },
    {
      userName,
      password: doCrypto(password),
    }
  );
  if (result) {
    return new SuccessModel();
  }
  return new ErrorModel(changePasswordFailInfo);
}

module.exports = {
  //...
  changePassword,
};

- Book Lists -