Taro + node.js 注册 仿照java 中的加盐算法

1.需求

为了让用户的密码更加保密

我们在md5 之前 在加一个随机数 用java 的说法 叫做 加盐算法

2.代码

复制代码
 //H5注册
  async H5Register(register) {
    if (
      !register.phone ||
      !register.password ||
      !register.confirmPassword ||
      !register.yzmCode ||
      !register.registerCode
    ) {
      throw new CoolCommException('参数不能为空~');
    }

    const phoneRegex = /^1[3-9]\d{9}$/; // 手机号码的正则表达式

    if (!phoneRegex.test(register.phone)) {
      throw new CoolCommException('手机号码格式不正确~');
    }
    if (register.password !== register.confirmPassword) {
      throw new CoolCommException('两次密码不一致');
    }
    const inviteCode = await this.businessUserEntity.findOneBy({
      inviteCode: register.registerCode,
    });
    if (!inviteCode) {
      throw new CoolCommException('导师不存在~');
    }
    const checkV = await this.captchaCheckByH5(register.yzmCode);
    if (checkV) {
      const user = await this.businessStudentEntity.findOneBy({
        phone: register?.phone,
      });
      if (user) {
        throw new CoolCommException('账户已存在~');
      }
      const salt = this.generatePasswordCode();
      await this.businessStudentEntity.save({
        phone: register.phone,
        password: md5(register.password + salt).toUpperCase(),
        membershipLevel: 0,
        balance: 0,
        userId: inviteCode.id,
        randomStr: salt,
      });
      return 1;
    } else {
      throw new CoolCommException('验证码不正确~');
    }
  }

 //生成加盐密码
  public generatePasswordCode() {
    // const hmac = crypto.createHmac('sha256', '1234567890');
    // hmac.update(password.toString());
    // const hash = hmac.digest('hex');
    // const code = hash.substring(0, 6).toUpperCase();
    // return code;

    let chars = 'ABCDEFGHJKMNPQRSTWXYZ1234567890';
    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    let maxPos = chars.length;
    var code = '';
    for (let i = 0; i < 6; i++) {
      code += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return code.toString();
  }

3 登录验证

为了适配之前的纯md5 方式

复制代码
  // H5 登录
  async H5Login(login) {
    if (!login.password || !login.phone) {
      throw new CoolCommException('账户或者密码不能为空~');
    }
    let user;
    // 尝试使用直接MD5加密的密码进行验证
    const userByDirectMd5 = await this.businessStudentEntity.findOneBy({
      phone: login.phone,
      password: md5(login.password),
    });

    // 如果没有找到,尝试使用带有随机字符串的加密方式
    if (!userByDirectMd5) {
      const userInfo = await this.businessStudentEntity.findOneBy({
        phone: login.phone,
      });

      if (!userInfo) {
        // 手机号不存在,直接返回错误
        throw new CoolCommException('账户不存在或密码不正确~');
      }

      const userByRandomStrMd5 = await this.businessStudentEntity.findOneBy({
        phone: login.phone,
        password: md5(login.password + userInfo.randomStr).toUpperCase(),
      });

      if (!userByRandomStrMd5) {
        // 密码不正确
        throw new CoolCommException('账户不存在或密码不正确~');
      }

      // 这里可以设置 user 为使用随机字符串加密方式找到的用户
      user = userByRandomStrMd5;
    } else {
      // 这里设置 user 为使用直接MD5加密方式找到的用户
      user = userByDirectMd5;
    }

    // 检查账户是否启用
    if (user.isEnabled == 0) {
      throw new CoolCommException('账户无权限,请联系客服开通~');
    }

    // 生成和缓存JWT令牌
    const { expire, refreshExpire } = this.coolConfig.jwt.token;
    const result = {
      expire,
      token: await this.generateTokenClient(user, expire),
      refreshExpire,
      refreshToken: await this.generateTokenClient(user, refreshExpire, true),
    };

    // 缓存令牌
    await this.cacheManager.set(
      `business:client:token:${user.id}`,
      result.token,
      { ttl: expire }
    );
    await this.cacheManager.set(
      `business:client:token:refresh:${user.id}`,
      result.refreshToken,
      { ttl: refreshExpire }
    );

    return result;
  }
相关推荐
霪霖笙箫1 分钟前
「JS全栈AI学习」十一、Multi-Agent 系统设计:可观测性与生产实践
前端·面试·全栈
不会敲代码12 分钟前
从零开始读懂 MCP:大模型如何通过标准化协议“调用”你的工具?
javascript·cursor·trae
ZC跨境爬虫4 分钟前
3D 地球卫星轨道可视化平台开发 Day12(解决初始相位拥挤问题,实现卫星均匀散开渲染)
前端·javascript·算法·3d·json
踩着两条虫7 分钟前
VTJ.PRO 企业级应用开发实战指南
前端·人工智能·低代码·重构·架构
用户5757303346248 分钟前
🚀 别再让浏览器“负重跑”了!手把手教你用 IntersectionObserver 实现图片懒加载
前端
好雨知时节t10 分钟前
告别“刷新”:一文搞懂 WebSocket、SSE 与轮询机制
javascript·ai编程
Ruihong14 分钟前
Vue 转 React:揭秘 scoped 样式是如何被 VuReact 编译的?
vue.js·react.js·面试
胖纳特16 分钟前
从零到一:OnlyOffice中国版企业级完整落地指南
前端·后端
MiNG MENS20 分钟前
Spring Boot + Vue 全栈开发实战指南
vue.js·spring boot·后端
Ruihong20 分钟前
Vue 组件样式 <style> 转 React:VuReact 怎么处理?
vue.js·react.js·面试