wangrong
16 小时以前 0d90e20ec20f0aeee642756a7ebf9e8514174124
src/modules/user/service/login.ts
@@ -78,12 +78,85 @@
   * @param encryptedData
   * @param iv
   */
  async miniPhone(code, encryptedData, iv) {
  async miniPhone(code, encryptedData, iv, loginCode?) {
    const phone = await this.userWxService.miniPhone(code, encryptedData, iv);
    if (phone) {
      return await this.phone(phone);
    } else {
    if (!phone) {
      throw new CoolCommException('获得手机号失败,请检查配置');
    }
    const token = await this.phone(phone);
    await this.bindMiniOpenid(phone, loginCode);
    return {
      ...token,
      phone,
    };
  }
  /**
   * 小程序再次打开时,用 openid 静默登录
   */
  async miniAuto(code: string) {
    if (!code) {
      return null;
    }
    const session = await this.userWxService.miniSession(code);
    if (!session?.openid || session.errcode) {
      return null;
    }
    const wx = await this.userWxEntity.findOneBy({
      openid: Equal(session.openid),
    });
    if (!wx?.unionid) {
      return null;
    }
    const user = await this.userInfoEntity.findOneBy({
      unionid: Equal(wx.unionid),
    });
    if (!user?.phone || user.status === 2) {
      return null;
    }
    const token = await this.token({ id: user.unionid });
    return {
      ...token,
      phone: user.phone,
      nickName: user.nickName,
      avatarUrl: user.avatarUrl,
      unionid: user.unionid,
      id: user.id,
    };
  }
  /**
   * 把当前微信 openid 记到手机号账号上,供下次静默登录
   */
  async bindMiniOpenid(phone: string, loginCode?: string) {
    if (!loginCode) {
      return;
    }
    try {
      const session = await this.userWxService.miniSession(loginCode);
      if (!session?.openid || session.errcode) {
        return;
      }
      const user = await this.userInfoEntity.findOneBy({
        phone: Equal(phone),
      });
      if (!user) {
        return;
      }
      const unionid = user.unionid || session.unionid || phone;
      const exist = await this.userWxEntity.findOneBy({
        openid: Equal(session.openid),
      });
      await this.userWxEntity.save({
        id: exist?.id,
        openid: session.openid,
        unionid,
        nickName: user.nickName,
        avatarUrl: user.avatarUrl,
        type: 0,
      });
    } catch (err) {
      // 绑定 openid 失败不影响本次手机号登录
    }
  }
@@ -115,7 +188,8 @@
      user = {
        phone,
        unionid: phone,
        loginType: 2,
        loginType: 0,
        departmentId: 1,
        nickName: phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2'),
      };
      await this.userInfoEntity.insert(user);