【问题标题】:How to link Firebase's Authentication to Realtime Database?如何将 Firebase 身份验证链接到实时数据库?
【发布时间】:2023-03-20 15:36:01
【问题描述】:

正如标题所说。 我需要将经过身份验证的用户链接到数据库。 这样不同的用户只能看到他们的数据。

我已经成功实现了 Firebase 的 Authentication 功能。 但是记录没有保存到实时数据库,我不知道该怎么做。

谁能教我怎么做这样的功能? 我尝试了数据库,我大致知道它使用(推送)创建一个唯一 ID 来区分用户。但我仍然不知道如何将其与身份验证功能结合起来。

以下代码是我的Login()和Register()函数

login (){

    const validate = this.refs.formId.getValue();
    if (validate) {
        firebase.auth().signInWithEmailAndPassword(validate.email, validate.password)
        .then(() => {
        })
        .catch((error) => {
            const errorCode = error.code;
            const errorMessage = error.message;
            if (errorCode === 'auth/wrong-password') {

            Toast.show({ text: `${Strings.ST30}`, position: 'bottom', buttonText: `${Strings.ST33}` })

            }
            else if (errorCode === 'auth/user-not-found') {

            Toast.show({ text: `${Strings.ST31}`, position: 'bottom', buttonText: `${Strings.ST33}` })

            }
            else{
            Toast.show({ text: `${Strings.ST32}`, position: 'bottom', buttonText: `${Strings.ST33}` })
            }

        });
    }

}
    register () {

    const validate = this.refs.form.getValue();
    if(this.validate) {
        const errorHandler = ((e)=>{
        console.log(e);
        if(e.code == 'auth/email-already-in-use'){
            Toast.show({ text: `${Strings.ST36}`, position: 'bottom', buttonText: `${Strings.ST33}` })

        } else {
            Toast.show({ text: `${Strings.ST32}`, position: 'bottom', buttonText: `${Strings.ST33}` })
        }

    })
    firebase.auth().createUserWithEmailAndPassword(validate.email,validate.password).then((response) => {
        firebase.auth().currentUser.updateProfile({
            displayName : validate.name,
        }).then(()=>{
        }).catch(errorHandler);

    }).catch(errorHandler)
}}

非常感谢您的时间和帮助。非常感谢!

编辑 2:

        firebase.auth()
    .createUserWithEmailAndPassword(validate.email,validate.password)
    .then((response) => {
        firebase.auth().currentUser.updateProfile({
            displayName : validate.name,
        }).then(()=>{
            firebase.database()
            .ref('users/' + firebase.auth().currentUser.uid + "/profile")
            .set({
                Username: validate.name,
                UserEmail: validate.email,
                CreationDate: d1.getFullYear() + "/" + (d1.getMonth() + 1) + "/" + d1.getDate()
            })
        }).catch(errorHandler);
    }).catch(errorHandler)
}}

我已成功链接到 Firebase 实时数据库。

但我无法从我的数据库中写入和读取其他函数。 这是我对 Firebase 数据库的规则。我可以知道我应该改变哪个部分吗?

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

}

编辑 3:(ExampleSendData.js)

构造函数(道具){ 超级(道具)
这个.state = { 信息: '', 消息:[] }

this.addItem = this.addItem.bind(this); }

    componentDidMount() {
        firebase
        .database()
        .ref()
        .child("messages")
        .once("value", snapshot => {
            const data = snapshot.val()
            if (snapshot.val()) {
            const initMessages = [];
            Object
                .keys(data)
                .forEach(message => initMessages.push(data[message]));
            this.setState({
                messages: initMessages
            })
            }
        });

        firebase
        .database()
        .ref()
        .child("messages")
        .on("child_added", snapshot => {
            const data = snapshot.val();
            if (data) {
            this.setState(prevState => ({
                messages: [data, ...prevState.messages]
            }))
            }
        })

    }

    addItem () {
        if (!this.state.message) return;

        const newMessage = firebase.database().ref()
                            .child("messages")
                            .push();
        newMessage.set(this.state.message, () => this.setState({message: ''}))
    }

    render() {
        return (
        <View style={styles.container}>
            <View style={styles.msgBox}>
            <TextInput placeholder='Enter your message'
                value={this.state.message}
                onChangeText={(text) => this.setState({message: text})}
                style={styles.txtInput}/>
            <Button title='Send' onPress={this.addItem}/>
            </View>
            <FlatList data={this.state.messages}
            renderItem={
                ({item}) => 
                <View style={styles.listItemContainer}>
                <Text style={styles.listItem}> {item}
                </Text>
                </View>
            }

            />
        </View>
        );
    }
    }

【问题讨论】:

标签: firebase react-native firebase-realtime-database firebase-authentication react-native-android


【解决方案1】:

从您正在编写的代码中,我希望您使用的是 react-native-firebase?如果没有 - 你应该使用它:-)

react-native-firebase 的解决方案:

一旦您注册或登录,您就可以使用 firebase.auth().currentUser 对象。此对象包含一个 uid (currentUser.uid)。然后,您可以使用 firebase.database().ref('users/' + firebase.auth().currentUser.uid + "/profile").set() 将一些数据推送到 uid 下的数据库; 例如在你的寄存器中是这样的:

    register () {
        const validate = this.refs.form.getValue();
        if(this.validate) {
            const errorHandler = ((e)=>{
            console.log(e);
            if(e.code == 'auth/email-already-in-use'){
                Toast.show({ text: `${Strings.ST36}`, position: 'bottom', buttonText: `${Strings.ST33}` })
            } else {
                Toast.show({ text: `${Strings.ST32}`, position: 'bottom', buttonText: `${Strings.ST33}` })
            }
        })
        firebase.auth().createUserWithEmailAndPassword(validate.email,validate.password).then((response) => {
            firebase.auth().currentUser.updateProfile({
                displayName : validate.name,
            }).then(()=>{
                firebase.database().ref('users/' + firebase.auth().currentUser.uid + "/profile").set(firebase.auth().currentUser);
            }).catch(errorHandler);
        }).catch(errorHandler)
    }}

安全性:

我不建议在您的数据库中设置整个用户数据,因为您不需要它。使用数据库来保存用户进度或类似的东西。

安全 2:

您应该设置数据库的安全规则,只有用户可以在他的数据库节点中读取和写入。使用类似的东西:

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

编辑 1: 请尝试删除推送,因为它会生成一个唯一的密钥,这与用户无关。很难再次找到您的用户数据。 并且不要使用 set 两次,因为它不起作用。

编辑 2: 您必须像这样将您想要可读/可写的节点设置为 true:

{
    "rules": {
        ".read": false,
        ".write": false,
        "users":
        {
            "$userId":
            {
                ".read": "auth.uid === $userId",
                ".write": "auth.uid === $userId"
            }
        },
        // readable node
        "messages":
        {
            ".read": true
        },
        // readable and writable node
        "messages":
        {
            ".read": true,
            ".write": true
        }
    }
}

【讨论】:

  • 您好,感谢您的帮助。我将 Register() 的代码更改为您的代码,我注册了一个新帐户,数据库仍然没有记录最新创建的用户。是的,我也会根据您的建议更改规则。
  • 您可以在更新配置文件后登录您的用户,例如 firebase.auth().createUserWithEmailAndPassword(validate.email,validate.password).then((response) => { firebase.auth().currentUser .updateProfile({ displayName : validate.name, }).then(()=>{ console.log(firebase.auth().currentUser); }).catch(errorHandler); }).catch(errorHandler)跨度>
  • 也有可能 firebase.auth().currentUser 无法完全写入 db。您是否尝试过编写自己的对象,例如 firebase.database().ref('users/' + firebase.auth().currentUser.uid + "/profile").set({name: validate.name});
  • 抱歉@Alexander 回复晚了,我用我的代码截图编辑了我的帖子。希望你能帮助我。我仍然停留在数据库链接上。
  • 嗨,亚历克斯,请下次复制您的代码,因为这样编辑起来会更舒服:-) 我还用屏幕截图编辑了我的答案 - 如果可行,请尝试。如果没有,您能否检查一下是否达到了 Firebase 数据库调用以及您的 auth().currentUser.uid 是否已设置?只需在调用之前放置一个 console.log(firebase.auth().currentUser) 并检查 uid 是否在其中......
【解决方案2】:

您需要在使用firebase.auth.getcurrentuser() 登录后获取当前用户,然后将信息写入数据库firebase.database().ref('users/' + firebase.auth().currentUser.uidcurrentuser.email,如果您想将电子邮件写入数据库,还要检查是否设置了安全规则。

【讨论】:

  • 如果没记错的话,Firebase 实时数据库不允许添加电子邮件作为密钥。如果我错了,请纠正我。
猜你喜欢
  • 1970-01-01
  • 2019-01-28
  • 1970-01-01
  • 2017-12-26
  • 2019-05-05
  • 1970-01-01
  • 2019-06-28
  • 2021-01-22
  • 1970-01-01
相关资源
最近更新 更多