Role-based authentication with Ionic & Firebase

First Published: 24 April 2019
Updated on: 24 April 2019

Today you’ll learn a bit about role-based authentication, and how to show/hide different part of your apps to different kind of users.

We’ll work through an example, you have a button on your page that should only be visible to admin users.

If an admin user logs in they should see two buttons in the home page like shown in the picture below.

Firebase Dashboard

And if a regular user logs in they should only see one of the buttons, like shown in the picture below.

Firebase Dashboard Hide

If you prefer the video version you can watch it right here.

First, there’s something we need to understand when working with Firebase. Authentication and the Firestore database aren’t really “connected”.

They’re both Firebase products that can work with each other, but if you want to have an ‘admin’ user you’ll need to store some sort of identifier in the database yourself.

Firestore Database

Hiding the content

Once we understand that, we’re going to be focusing on the content we want to hide, to hide it, we’ll use the *ngIf directive and bind it to a public isAdmin variable. (For this example imagine we’re working on the home.page module)

Open home.page.ts and add the directive.

<ion-button *ngif="isAdmin" routerlink="/event-create">
  Create a new Event
</ion-button>

After we do that, we need to go into our class and give that isAdmin variable some logic.

The first thing we want to do is go to home.page.ts and import Firebase (In this example we’re using the JS SDK but you can accomplish the same using AngularFire)

import * as firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';

Once that’s imported, we’re going to go to our ngOnInit() function and do the following:

ngOnInit() {
  firebase.auth().onAuthStateChanged(user => {
    if (user) {
      firebase
        .firestore()
        .doc(`/userProfile/${user.uid}`)
        .get()
        .then(userProfileSnapshot => {
          this.isAdmin = userProfileSnapshot.data().isAdmin;
        });
    }
  });
}
  • The onAuthStateChanged() function is returning the currently logged in user.
  • If there’s a user, we’re creating a reference to that user’s Firestore document.
  • Once we get the document we’re assigning the value of the isAdmin property from the database to our isAdmin public variable.

And that’s it, it will read the logged in user, detect if it’s an admin, and based on that decide whether to show or hide the button.