1

First of all, I am using nodejs for the backend. I use firebase hosting and firebase functions to deploy an express() app.

What I am trying to achieve is to make an admin website, which is connected to Firebase. so I have a route /admin/ like this:

adminApp.get("/", (request, response) => {
    return response.redirect("/admin/login");
});

Here I basically want to check if a current user is logged in - or not. I know firebase supports client side authentication using:

firebase.auth().onAuthStateChanged(user => {
   if (user) {

    } else {

    }
});

And using

function login() {
   var userEmail = document.getElementById("email").value;
   var userPass = document.getElementById("password").value;

   firebase.auth().signInWithEmailAndPassword(userEmail, userPass).catch(function(error) {
     var errorCode = error.code;
     var errorMessage = error.message;
     if (error) {
       document.getElementById('loginError').innerHTML = `Error signing in to firebase`;
     }
   });
}

However image this case:

Someone (not an admin) is visiting /admin/some_secret_website/ which he obviously does not have access to. If I rely on client side authentication, it first loads the entire website and the scripts and then notices - hey I am not authenticated, let me redirect to /login. By then however anyone knows the source code of an admin page.

I'd rather have something like:

adminApp.get("/admin/some_secret_website", (request, response) => {
    if (request.user) {
       // user is authenticated we can check if the user is an admin and give access to the admin page
    }
});

I know that you can get the user's token and validate that token using the AdminSDK, but the token must be send by the client code, meaning the website was already loaded.

I came across Authorized HTTPS Endpoint by firebase, but it only allows a middleware when using a bearer token.

Does anybody know how I can maintain a server side user object to not even return admin html to the browser but only allow access to admins?

Janosch Hübner
  • 1,584
  • 25
  • 44
  • The middleware you're referring to in the example can be very easily rewritten as inline code to be invoked directly in a function that should be protected. – Doug Stevenson Aug 12 '18 at 00:12

1 Answers1

1

Like Doug indicated, the way your admin website/webapp would function with Firebase Cloud Functions (which is effectively a Nodejs server) is that you get the request, then use the headers token to authenticate them against Firebase Auth. See this answer for a code snippet on this.

In your case, I'm thinking you would create a custom claim for an "administrator" group and use that to determine whether to send a pug templated page as a response upon authentication. As far as Authorization, your db rules will determine what said user can CRUD.

Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91