如何将 Firebase 的身份验证链接到实时数据库?

Ale*_*ong 11 firebase react-native firebase-authentication firebase-realtime-database react-native-android

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

我已经成功实现了 Firebase 的身份验证功能。但是记录没有保存到实时数据库,我不知道如何做到这一点。

谁能教我如何做这样的功能?我尝试了数据库,我大致知道它使用(推送)来创建一个唯一的 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)
}}
Run Code Online (Sandbox Code Playgroud)

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

在此处输入图片说明 在此处输入图片说明 在此处输入图片说明 在此处输入图片说明 在此处输入图片说明

编辑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)
}}
Run Code Online (Sandbox Code Playgroud)

我已成功链接到 Firebase 实时数据库。 在此处输入图片说明

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

{
"rules": {
    ".read": false,
    ".write": false,
    "users":
    {
        "$userId":
        {
            ".read": "auth.uid === $userId",
            ".write": "auth.uid === $userId"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

}

编辑 3: (ExampleSendData.js)

构造函数(道具){ 超级(道具)
this.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>
        );
    }
    }
Run Code Online (Sandbox Code Playgroud)

Ale*_*tig 7

从您编写的代码中,我希望您使用的是 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)
    }}
Run Code Online (Sandbox Code Playgroud)

安全:

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

安全2:

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

{
    "rules": {
        ".read": false,
        ".write": false,
        "users":
        {
            "$userId":
            {
                ".read": "auth.uid === $userId",
                ".write": "auth.uid === $userId"
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)