Skip to main content

React Native and Firebase: Authentication

 

React Native and Firebase: Authentication

How to set up your React Native app to work with Firebase

Authenticate a User in React with Firebase

https://next.egghead.io/lessons/react-authenticate-a-user-in-react-with-firebase

Photo by Google...

Hi! I’m Sanjay. Here’s a quick guide that will get us up and running with Firebase’s Authentication in React Native!

Firebase provides a lot of great products that allow us to develop mobile apps quickly; Realtime Database, Authentication, Cloud Firestore, Cloud Functions, Crashlytics…Just to name a few.

We’re going to be building a simple authentication flow using an email and password.

All we need is a way to use the Firebase SDK with a React Native app…and thanks to the lovely people at Invertase, who created react-native-firebase, we have just that! It’s an awesome open-source project for linking React Native apps with Firebase.

Setting Up Our App

Since we’re starting from scratch, we can go ahead and use the basic starter kit provided by react-native-firebase.

(If you already have an existing application, you can head over to React Native Firebase and follow the manual installation instructions.)

Go ahead and follow their instructions (they’re great) to get our app up and running, and then come back when you’re ready.

Enable Email and Password Authentication in Firebase

After following the instructions linked above, you should be ready to get started.

Here’s a diagram of what we’re going to be building:

A flow diagram of what we’re building

To allow users to use an email and password combo, we need to enable this provider in our Firebase console.

To do this, head on over to your Firebase Project → Authentication → Sign-in Method. Click on Email/Password and set to enabled and save. Your dashboard should look like this:

Enabling email and password authentication

Creating the Screens

If we take a look at our diagram, you can see that we have four screens: Loading, SignUp, Login, and Main.

A Loading screen that displays until we determine the auth state of a user, a SignUp screen where the user can create an account, a Login screen where an existing user can log in, and a Main screen of our application that we only show to an authenticated user.

We’re going to be using react-navigation for our app’s navigation, so let’s set up our navigator and create our screens.

yarn add react-navigation

Let’s create our screens.

Loading.js

// Loading.js
import React from 'react'
import { View, Text, ActivityIndicator, StyleSheet } from 'react-native'
export default class Loading extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>Loading</Text>
        <ActivityIndicator size="large" />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  }
})

SignUp.js



// SignUp.js
import React from 'react'
import { StyleSheet, Text, TextInput, View, Button } from 'react-native'
export default class SignUp extends React.Component {
  state = { email: '', password: '', errorMessage: null }
handleSignUp = () => {
  // TODO: Firebase stuff...
  console.log('handleSignUp')
}
render() {
    return (
      <View style={styles.container}>
        <Text>Sign Up</Text>
        {this.state.errorMessage &&
          <Text style={{ color: 'red' }}>
            {this.state.errorMessage}
          </Text>}
        <TextInput
          placeholder="Email"
          autoCapitalize="none"
          style={styles.textInput}
          onChangeText={email => this.setState({ email })}
          value={this.state.email}
        />
        <TextInput
          secureTextEntry
          placeholder="Password"
          autoCapitalize="none"
          style={styles.textInput}
          onChangeText={password => this.setState({ password })}
          value={this.state.password}
        />
        <Button title="Sign Up" onPress={this.handleSignUp} />
        <Button
          title="Already have an account? Login"
          onPress={() => this.props.navigation.navigate('Login')}
        />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  textInput: {
    height: 40,
    width: '90%',
    borderColor: 'gray',
    borderWidth: 1,
    marginTop: 8
  }
})

Login.js

// Login.js
import React from 'react'
import { StyleSheet, Text, TextInput, View, Button } from 'react-native'
export default class Login extends React.Component {
  state = { email: '', password: '', errorMessage: null }
  handleLogin = () => {
    // TODO: Firebase stuff...
    console.log('handleLogin')
  }
  render() {
    return (
      <View style={styles.container}>
        <Text>Login</Text>
        {this.state.errorMessage &&
          <Text style={{ color: 'red' }}>
            {this.state.errorMessage}
          </Text>}
        <TextInput
          style={styles.textInput}
          autoCapitalize="none"
          placeholder="Email"
          onChangeText={email => this.setState({ email })}
          value={this.state.email}
        />
        <TextInput
          secureTextEntry
          style={styles.textInput}
          autoCapitalize="none"
          placeholder="Password"
          onChangeText={password => this.setState({ password })}
          value={this.state.password}
        />
        <Button title="Login" onPress={this.handleLogin} />
        <Button
          title="Don't have an account? Sign Up"
          onPress={() => this.props.navigation.navigate('SignUp')}
        />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  textInput: {
    height: 40,
    width: '90%',
    borderColor: 'gray',
    borderWidth: 1,
    marginTop: 8
  }
})

Main.js

// Main.js
import React from 'react'
import { StyleSheet, Platform, Image, Text, View } from 'react-native'
export default class Main extends React.Component {
  state = { currentUser: null }
render() {
    const { currentUser } = this.state
return (
      <View style={styles.container}>
        <Text>
          Hi {currentUser && currentUser.email}!
        </Text>
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  }
})

Now that we have all our screens created, let’s wire up our navigation inside our App.js file.

App.js



import React from 'react'
import { StyleSheet, Platform, Image, Text, View } from 'react-native'
import { SwitchNavigator } from 'react-navigation'
// import the different screens
import Loading from './Loading'
import SignUp from './SignUp'
import Login from './Login'
import Main from './Main'
// create our app's navigation stack
const App = SwitchNavigator(
  {
    Loading,
    SignUp,
    Login,
    Main
  },
  {
    initialRouteName: 'Loading'
  }
)
export default App
If we start up our app, you should see our Loading screen with the ActivityIndicator spinning forever. This is what we expected, because we need to determine if the user is authenticated or not to determine where to route them.

If the user is authenticated, route them to the Main screen. Otherwise, send them to the SignUp screen.

Determining if a User Is Authenticated

We can use Firebase to determine the authentication state of a user. Let’s add a check on our Loading screen that determines if a user is logged in or not.


// Loading.js
// Omitted other imports...
import firebase from 'react-native-firebase'
export default class Loading extends React.Component {
  componentDidMount() {
    firebase.auth().onAuthStateChanged(user => {
      this.props.navigation.navigate(user ? 'Main' : 'SignUp')
    })
  }
// Omitted the rest of the file...
We are using Firebase’s onAuthStateChanged listener to get the current auth state of the user. If they are authenticated, we route them to the Main screen. Otherwise, we send them to the SignUp screen.

Now, since we’re not logged in, you should see the Loading screen for a brief moment, and then be routed to the SignUp screen.

Signing a User Up

We need to create a new user, so we can log them in! Let’s head on over to the SignUp screen and wire up our handleSignUp method.


// SignUp.js
// Omitted other imports...
import firebase from 'react-native-firebase'
export default class SignUp extends React.Component {
  state = { email: '', password: '', errorMessage: null }
  handleSignUp = () => {
    firebase
      .auth()
      .createUserWithEmailAndPassword(this.state.email, this.state.password)
      .then(() => this.props.navigation.navigate('Main'))
      .catch(error => this.setState({ errorMessage: error.message }))
  }
// Omitted the rest of the file...
When a user submits the form, we createUserWithEmailAndPassword and then navigate them to the Main screen. If there is an error we catch it and display it.

Displaying the Current User on the Main Screen

With our current implementation, we will only see the Main screen if a user is logged in. We need to grab the currentUser from Firebase so that we can display their email. Let’s update our Main screen do handle this.

// Main.js
// Omitted other imports...
import firebase from 'react-native-firebase'
export default class Main extends React.Component {
  state = { currentUser: null }
  componentDidMount() {
    const { currentUser } = firebase.auth()
    this.setState({ currentUser })
}
// Omitted the rest of the file...


Now, when we see the Main screen, we should see the user’s email address. If we refresh the app, we should be automatically routed to the Main screen because are already authenticated.

The last step is that we should be able to log in a user after we have already created an account!

Logging an Already Existing User In

Homestretch! Let’s update our Login screen so that we can log in with an existing account.


// Login.js
// Omitted other imports...
import firebase from 'react-native-firebase'
export default class Login extends React.Component {
  state = { email: '', password: '', errorMessage: null }
  handleLogin = () => {
    const { email, pasword } = this.state
    firebase
      .auth()
      .signInWithEmailAndPassword(email, password)
      .then(() => this.props.navigation.navigate('Main'))
      .catch(error => this.setState({ errorMessage: error.message }))
  }
// Omitted the rest of the file...

We now have a simple authentication flow set up with React Native and Firebase. If you would like access to the entire source code, I’ve uploaded it to GitHub.

Thanks for reading!

Comments

Popular Posts

React Native: How To Open App Settings Page

  React Native: How To Open App Settings Page React Native has a Linking module to manage the interaction with other applications in the device. In this article, I will explain how you can open “Application Setting Page” of the device using. Sample Case Before I explain how to do this, I’ll talk about an example case where we might need this: You need to get location permission within the application from a user using an iOS operating system and you asked for permission. But user did not agree to grant this permission the first time. In this case, you cannot ask your user for location permission the second time. In this case, the only thing to do is to direct the user to the settings page of our application and make it manually allow it. Now that we have explained our example situation, we can move on to how we can redirect our user to the “settings page of our application”. Open App Settings Page iOS If our user is using an iOS operating system, we can handle the whole process wit...

Integrate the FaceID or TouchID Authentication in iOS Apps - Swift

FaceID or TouchID Authentication Dear Folks, today I am going to explain the proper way to integrate the Face ID or Touch ID in iOS App. Face ID and Touch ID are secure, familiar authentication methods that people trust. Follow below steps: Step 1: Add NSFaceIDUsageDescription Key in info.plist file <key>NSFaceIDUsageDescription</key> <string>This app requires Face ID permission to authenticate using Face recognition.</string> Step 2: Create a swift file with any name but it would be better to related to its functionality, Like BioMetrixFile.swift Step 3: In BioMetrixFile write below codes and follow instructions. But before proceeding further import LocalAuthentication class in BioMetrixFile. Now, create typealias for success or failure blocks to well manage Authentication Success or Failure. public typealias AuthenticationSuccess = (() -> ()) public typealias AuthenticationFailure = ((AuthenticationError) -> ()) Now written all s...

Add Custom Checkbox on UITableViewCell or UITableView in Swift 4

Add Custom Checkbox Introduction to how to add custom checkbox on UITableViewCell or UITableView in swift 4 In this tutorial, we are going to learn about how can we create or add custom checkbox on UITableViewCell or UITableView in swift and perform IBAction on our custom checkbox placed on UITableViewCell or UITableView in swift 4. We will place UIButton on UITableViewCell that will act as checkbox for our UITableViewCell in UITableView using swift 4. In the end of this tutorial, we will have output as shown in below picture Learn how to create checkbox in swift from  HERE Steps to create or add custom checkbox on UITableViewCell or UITableView Step 1 :  Create a new Xcode project and select  "Single View App"  template. Name  project as  "addCheckBoxonTable-Tutorial" . Step 2:  Open  "Main.storyboard"  file and drag UITableView object on to the view. Then we will add constraints to UITableView so that it fits...