灏天阁

Node/Koa2[32]: 注册-密码加密

· Yin灏

目录结构

└─src
    ├─conf
    │  └─secretKeys.js
    ├─controller
    │  └─user.js
    └─utils
        └─cryp.js

统一处理加密 KEY

src/conf/secretKeys.js

module.exports = {
  CRYPTO_SECRET_KEY: "自定义",
  SESSION_SECRET_KEY: "自定义",
};

加密

src/utils/cryp.js

const crypto = require("crypto");
const { CRYPTO_SECRET_KEY } = require("../conf/secretKeys");

function _md5(content) {
  const md5 = crypto.createHash("md5");
  return md5.update(content).digest("hex");
}

function doCrypto(cntent) {
  const str = `password=${content}&key=${CRYPTO_SECRET_KEY}`;
  return _md5(str);
}

module.exports = doCrypto;

使用加密函数

src/controller/user.js

//...
const doCrypto = reuqire("../utils/cryp");
//...

async function register({ userName, password, gender }) {
  const userInfo = await getUserInfo(userName);
  if (userInfo) {
    // 用户名已存在
    return new ErrorModel(registerUserNameExistInfo);
  }
  // services
  try {
    await createUser({
      userName,
      // 密码加密
      password: doCrypto(password),
      gender,
    });
    return new SuccessModel();
  } catch (ex) {
    console.log(ex.message, ex.stack);
    return new ErrorModel(registerFailInfo);
  }
}

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

- Book Lists -