Source: middleware/authenticator.js

const admin = require("firebase-admin");
const express = require("express");

/**
 * Middleware that verifies Firebase user and gets their uid using email.
 * NOTE: This is only meant for dev purposes. Never use this in production code.
 * @param {*} req 
 * @param {string} req.body.email The email of the user
 * @param {*} res 
 * @param {callback} next - Next function to call
 */
const devGetUser = async(req, res, next) => {
  if (req.body.email) {
    admin.auth().getUserByEmail(req.body.email)
    .then(function(userRecord) {
      // See the UserRecord reference doc for the contents of userRecord.
      res.locals.uid = userRecord.uid;
      next();
    })
    .catch(function(error) {
      res.status(401).send('Unauthorized');
    });
  } else {
    res.status(401).send('Unauthorized');
  }
}

/**
 * Middleware that verifies Firebase user and gets their uid using their authentication token in the header.
 * @param {*} req
 * @param {string} req.headers.authorization The authorization ID token
 * @param {*} res 
 * @param {callback} next - Next function to call
 */
const checkAuth = async (req, res, next) => {
  if (req.headers.authorization) {
    admin.auth().verifyIdToken(req.headers.authorization)
      .then((decodedToken) => {
        res.locals.uid = decodedToken.uid;
        res.locals.email = decodedToken.email;
        next();
      }).catch(function(error) {
        res.status(401).send('Unauthorized');
      });
  } else {
    res.status(401).send('Unauthorized');
  }
}

module.exports = {email: devGetUser, token: checkAuth};