You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic项目中Firebase认证与实时数据库用户信息关联方法问询

关联Firebase认证与实时数据库用户信息

核心逻辑

利用Firebase认证生成的用户UID作为实时数据库中用户数据的节点键,实现认证用户与个人资料的一一绑定,替代原代码中push()生成随机键的方式,确保数据关联准确。


1. 注册时初始化用户数据(可选)

用户注册成功后,直接用当前用户的UID在数据库创建专属节点,可先写入邮箱等基础信息,后续引导用户完善其他资料:

signUp(email: string, password: string) {
  this.angularFireAuth.createUserWithEmailAndPassword(email, password).then((userCredential) => {
    // 获取注册用户的UID
    const userId = userCredential.user.uid;
    // 在数据库创建以UID为键的用户节点
    firebase.database().ref(`users/${userId}`).set({
      email: email,
      gebruikersnaam: '', // 留空待用户完善
      voornaam: '',
      achternaam: ''
    }).then(() => {
      this.showToast('Account gemaakt, graag je emailadres verifieren.');
      this.sendVerificationMail();
    }).catch(dbError => {
      this.presentAlert('数据库初始化失败:' + dbError.message);
    });
  })
  .catch(error => {
    const errorCode = error.code;
    let errorMessage;
    switch (errorCode) {
      case 'auth/email-already-in-use':
        errorMessage = 'Dit emailadres bestaat al.';
        break;
      case 'auth/invalid-email':
        errorMessage = 'Dit emailadres is onjuist.';
        break;
      default:
        errorMessage = '注册失败,请重试';
    }
    this.presentAlert(errorMessage);
  });
}

2. 完善个人资料时关联当前用户

修改资料页的update方法,获取当前登录用户的UID,更新对应节点的数据,避免生成无关的随机键:

// 确保导入AngularFireAuth
import { AngularFireAuth } from '@angular/fire/compat/auth';

// 组件构造函数注入
constructor(private afAuth: AngularFireAuth) {}

update() {
  this.afAuth.currentUser.then(user => {
    if (user) {
      const userId = user.uid;
      // 更新当前用户的数据库节点
      firebase.database().ref(`users/${userId}`).update({
        gebruikersnaam: this.profileform.value.gebruikersnaam,
        voornaam: this.profileform.value.voornaam,
        achternaam: this.profileform.value.achternaam,
      }).then(() => {
        this.showToast('资料更新成功');
      }).catch(dbError => {
        this.presentAlert('资料更新失败:' + dbError.message);
      });
    } else {
      this.presentAlert('请先登录');
    }
  });
}

3. 登录后拉取关联的用户资料

登录成功且邮箱验证通过后,根据用户UID从数据库获取个人资料,可存储到服务或本地供全局使用:

signIn(email: string, password: string) {
  this.angularFireAuth.signInWithEmailAndPassword(email, password).then(res => {
    if (res.user.emailVerified) {
      const userId = res.user.uid;
      // 读取当前用户的数据库资料
      firebase.database().ref(`users/${userId}`).once('value').then(snapshot => {
        const userData = snapshot.val();
        // 可将userData存入全局服务或localStorage
        console.log('用户资料:', userData);
      });
    } else {
      this.showToast('email is niet geverifieerd.');
    }
  })
  .catch(error => {
    const errorCode = error.code;
    let errorMessage;
    switch (errorCode) {
      case 'auth/user-not-found':
        errorMessage = 'Dit emailadres komt niet bekend voor.';
        break;
      case 'auth/user-disabled':
        errorMessage = 'Dit emailadres is geblokkeerd.';
        break;
      case 'auth/wrong-password':
        errorMessage = 'Het wachtwoord is onjuist.';
        break;
      default:
        errorMessage = '登录失败,请重试';
    }
    this.presentAlert(errorMessage);
  });
}

4. 配置数据库安全规则

为防止非法访问,在Firebase控制台的实时数据库规则中设置,确保每个用户仅能读写自己的资料:

{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}

内容的提问来源于stack exchange,提问作者Samir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 02:50:22