Js Mobile Dev About Courses Articles Youtube Services Contact

Role-based authentication with Ionic & Firebase

Libraries and Versions

Backend: Firebase v8.0.1
Frontend: @ionic/angular v5.0.0

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

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

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 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) {
        .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.

Become a Mobile Developer using JavaScript

Leave your email below and you'll get one or two emails a month sharing articles, videos, or courses that will help you jump-start your development with Ionic, Firebase, and Angular 🚀.

    I don't do the spam thing, you can one-click unsubscribe at any time