sing both Aurelia and firebase together is exceptionally convenient for my workflow. When it comes to authentication, I have certain routes I want to protect.
The best way to add in authentication checks for routes in Aurelia is to create a router pipeline step. Specifically, an authorise pipeline step.
Because of the way Firebase uses a promise based callback for its auth state change event, we need a way to wait for Firebase to resolve its callback before checking.
It might not be immediately obvious if you read the document, but the
run method in a pipeline step can return a
Promise object and it will wait for it to resolve or reject before proceeding.
I am going to assume you already have Firebase installed and configured in your Aurelia application.
Inside of your
src/app.js file, add the following right at the bottom:
This is our authorise step which waits for Firebase to tell us the current auth state and check the current route to see if it has an
auth attribute set to true.
We use the observable
onAuthStateChanged method because the user might log out or their session expires between page loads. Also, you’ll experience race collisions with the timing of routes and the state not being fully resolved if you do it any other way.
You’ll notice if the user is not logged in, then we are redirecting them to the homepage. Specify any URL you want here. Don’t forget to import
Redirect from the
aurelia-router package as well.
Inside of your app file, inside of the
configureRouter method, you want to now supply the auth step so our routes are checked.
At the bottom of the
configureRouter method add the following:
That’s it. Not much code to implement Firebase auth into your routes.