Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Google authentication to Firebase Real Time Database

I'm using the Firebase Real Time Database and I need to add user authentication to it. Users can only login with Google as a provider.

Current database mode:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

New mode should be like this:

// These rules grant access to a node matching the authenticated
// user's ID from the Firebase auth token
{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}

What should I use to authenticate in my case? userID, Google providerID or a token like described here?

This is the function without authentication to store data:

 createMeetup ({commit, getters}, payload) {
      console.log('index.js -> createMeetup')
      const meetup = {
        title: payload.title,
      }
      let imageUrl
      let key
      firebase.database().ref('meetups').push(meetup)
        .then((data) => {
          key = data.key
          return key
        })
        .then(() => {
          commit('createMeetup', {
            ...meetup,
            imageUrl: imageUrl,
            id: key
          })
        })
        .catch((error) => {
          console.log(error)
        })
    },
like image 744
Tom Avatar asked Dec 03 '18 19:12

Tom


1 Answers

For your use case it seems like you need to sort out a few steps. I'm guessing your application can already connect/use Firebase, but these are essentially it:

Step 1 - Connecting

Connect to Firebase using your API key/config as per usual, should look something like the following.

firebase.initializeApp(config)

See also: https://firebase.google.com/docs/web/setup

You probably already have this somewhere. This does not change, but if you would apply the rules as described your users would not be able to use Firebase after just connecting.

Step 2 - Authenticating

This is basically telling Firebase who is connected. This must be done with a token/method Firebase can verify. Using a Google ID is the most common method.

With an existing Google ID / user login

// Initialize a generate OAuth provider with a `google.com` providerId.
var provider = new firebase.auth.OAuthProvider('google.com');
var credential = provider.credential(googleUser.getAuthResponse().id_token);
firebase.auth().signInWithCredential(credential)

See also: https://firebase.google.com/docs/reference/js/firebase.auth.OAuthProvider#credential

Or make Firebase SDK do the login flow

var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
  // This gives you a Google Access Token. You can use it to access the Google API.
  var token = result.credential.accessToken;
  // The signed-in user info.
  var user = result.user;
  // ...
})

See also: https://firebase.google.com/docs/auth/web/google-signin

This last option is preferred / suggested by the documentation you referenced.

If, as you described, users can already login with Google to your app for other functionalities then you should already have a login flow somewhere. Depending on your situation it might be advisable to let the Firebase SDK / library take over this process for simplicity in your application.

Step 3 - Using the database

Lastly, after authenticating users and applying the rules you suggested you will need to also make sure the paths you write to are within those accessible by the current user. You can put this in a simple function to make it easier.

const getUserRef = (ref) => {
  const user = firebase.auth().currentUser;
  return firebase.database().ref(`/users/${user.uid}/${ref}/`);
}

You should of course not be retrieving the current user every time you want to get a database reference, but I think this clearly illustrates the steps that need to be taken.

like image 175
sg3s Avatar answered Oct 10 '22 16:10

sg3s