Role-based authentication with Ionic & Firebase
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.
And if a regular user logs in they should only see one of the buttons, like shown in the picture below.
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.
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 the firestore packages/methods we
need:
import { Auth, authState } from '@angular/fire/auth';
import { doc, Firestore, setDoc } from '@angular/fire/firestore';
constructor(
private readonly auth: Auth,
private readonly firestore: Firestore,
) {}
Once that’s imported, we’re going to go to our ngOnInit()
function and do the following:
ngOnInit() {
authState(user => {
if (user) {
const userReference = doc(
this.firestore,
`users/${user.uid}`
);
docData(userReference).subscribe(userObject => {
this.isAdmin = userObject.isAdmin;
})
}
});
}
- The
authState()
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 ourisAdmin
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.