How to determine if a user in Firebase has admin role

This article is divided in two parts:

  1. User's side authentication (React)
  2. Server's side verification (Firebase Cloud Functions)

User's side

First, we need to create a form to authenticate the user.

If you use React, you can do it by creating a button that executes a login() function on click.

This function will send the user's token to the server and wait for the response (determining whether the user is an admin or not).

jsx
import React, { useState, useEffect } from 'react';
import firebase, {auth, provider}     from './Firebase.js';

const Admin = () => {
    
    const [admin, setAdmin] = useState(false);
    
    const login = async () => {
        
        // Wait for Google pop-up and sign in
        let user = await auth.signInWithPopup(provider);
        
        // Getting user's token
        let idToken = await firebase.auth().currentUser.getIdToken(true);
        
        // URL to fetch
        let url = 'FIREBASE_CLOUD_FUNCTION_URL';
        
        // Waiting for response
        let response = await fetch(url, {
            "method":  "POST",
            "headers": { "Content-Type": "application/json" },
            "body":    JSON.stringify({ "idToken": idToken })
        });
        
        // If response ok, set as admin
        if(response.ok){
            
            // Waiting for the json response
            let json    = await response.json();
            
            // Is admin?
            let isAdmin = json.isAdmin;
            
            // Setting new state
            setAdmin(isAdmin);
            
        }
      
    }
    
    return (
    
        <div className = 'Admin'>
            <div className = 'Login'>
                <h2>Hi</h2>
                <button onClick = {() => login()}>Login</button>
            </div>
        </div>
        
    );
    
}

export default Admin;

Server's side

Before to proceed, install Firebase Cloud Functions. Then, you need to install firebase-admin and cors packages as well.

After the whole installation, get the user's admin UID: go to the Firebase Console, check the Authentication tab and look for the admin's UID.

Set the adminId in the command console:

terminal
firebase functions:config:set admin.id="ADMIN_ID"

Finally, open the functions/index.js and create the isAdmin() function.

jsx
const functions  = require('firebase-functions');
const admin      = require('firebase-admin');
const cors       = require('cors')({origin: true});
const adminId    = functions.config().admin.id; 

// Verifies if the user is an admin
exports.isAdmin = functions.https.onRequest((request, response) => {
    
    // Enable CORS using the `cors` express middleware.
    return cors(request, response, async () => {
    
        // Getting token
        let token = request.body.idToken;

        // Creating charge
        let decodedToken = await admin.auth().verifyIdToken(token);

        // Checking if user is admin
        let isAdmin = (decodedToken.uid === adminId);

        // Sending response
        response.status(200).json({isAdmin: isAdmin});
        
    });
    
});

After deploying, you will get the URL of the function (you will need to paste it on FIREBASE_CLOUD_FUNCTION_URL on the user's side file).

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.