Source: middleware/authenticator.js

  1. const admin = require("firebase-admin");
  2. const express = require("express");
  3. /**
  4. * Middleware that verifies Firebase user and gets their uid using email.
  5. * NOTE: This is only meant for dev purposes. Never use this in production code.
  6. * @param {*} req
  7. * @param {string} req.body.email The email of the user
  8. * @param {*} res
  9. * @param {callback} next - Next function to call
  10. */
  11. const devGetUser = async(req, res, next) => {
  12. if (req.body.email) {
  13. admin.auth().getUserByEmail(req.body.email)
  14. .then(function(userRecord) {
  15. // See the UserRecord reference doc for the contents of userRecord.
  16. res.locals.uid = userRecord.uid;
  17. next();
  18. })
  19. .catch(function(error) {
  20. res.status(401).send('Unauthorized');
  21. });
  22. } else {
  23. res.status(401).send('Unauthorized');
  24. }
  25. }
  26. /**
  27. * Middleware that verifies Firebase user and gets their uid using their authentication token in the header.
  28. * @param {*} req
  29. * @param {string} req.headers.authorization The authorization ID token
  30. * @param {*} res
  31. * @param {callback} next - Next function to call
  32. */
  33. const checkAuth = async (req, res, next) => {
  34. if (req.headers.authorization) {
  35. admin.auth().verifyIdToken(req.headers.authorization)
  36. .then((decodedToken) => {
  37. res.locals.uid = decodedToken.uid;
  38. res.locals.email = decodedToken.email;
  39. next();
  40. }).catch(function(error) {
  41. res.status(401).send('Unauthorized');
  42. });
  43. } else {
  44. res.status(401).send('Unauthorized');
  45. }
  46. }
  47. module.exports = {email: devGetUser, token: checkAuth};