Skip to content

Files

Latest commit

d1bd908 · May 4, 2020

History

History

4-firebase-authentication

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
May 4, 2020
May 4, 2020

Firebase Authentication

  1. React Native Firebase'in projeye eklenmesi
npm install --save @react-native-firebase/app

Diğer konfigürasyonlar için bakınız.

  1. Authentication modülünün eklenmesi
npm install --save @react-native-firebase/auth
cd ios && pod install
  1. Authentication implementasyonu (HomeScreen.js)
import auth from '@react-native-firebase/auth';
    state = {
        loading: false
    };
renderLogin() {
    return <View style={{ flex: 1, padding: 30, alignItems: 'center', justifyContent: 'center' }}>
        <Input style={{ marginBottom: 10 }} placeholder="User Name" />
        <Button buttonStyle={{ backgroundColor: '#8BC34A' }} title="Login" disabled={this.state.loading} onPress={() => this.login()} />
    </View>
}

login(){
    this.setState({ loading: true });

    auth()
        .signInAnonymously()
        .then(() => {
            console.log('User signed in anonymously');
            this.setState({ loading: false, isAuthenticated: true });
        })
        .catch(error => {
            if (error.code === 'auth/operation-not-allowed') {
                console.log('Enable anonymous in your firebase console.');
            }

            console.error(error);
            this.setState({ loading: false });
        });
}
  1. Kullanıcı giriş yapmış ise kullanıcı listesine yönlendirme (HomeScreen.js)
state = {
    loading: true
};
componentDidMount() {
    if (auth().currentUser != null) {
        this.setState({ isAuthenticated: true });
    }

    this.setState({ loading: false });
}
  1. Çıkış yapma (App.js)
import { Text, TouchableOpacity } from 'react-native';
componentDidMount() {
    ...
    this.renderLogoutButton(); // Add this line
}
renderLogoutButton() {
    this.props.navigation.setOptions({
        headerRight: () => {
            return this.state.isAuthenticated ?
                <TouchableOpacity
                    style={{ padding: 5, marginRight: 5 }}
                    onPress={() => {
                        auth()
                            .signOut()
                            .then(() => {
                                this.setState({ isAuthenticated: false }, () => { this.renderLogoutButton(); });
                            })
                    }}>
                    <Text>Log out</Text>
                </TouchableOpacity>
                :
                null
        }
    });
}
login() {
    ...
    auth()
        .signInAnonymously()
        .then(() => {
            console.log('User signed in anonymously');
            this.setState({ loading: false, isAuthenticated: true }, () => { this.renderLogoutButton(); }); // Update this line
        })
        .catch(error => {
            ... 
        });
}