Search code examples
node.jstypescriptexpressfirebase-authenticationfirebase-admin

Using Firebase as an Authenticating Middleware in Express.js


I am currently in the process of creating an auth middleware to ensure there is a valid firebase token in the request header. The code is as follows:

auth.ts

import * as firebase from 'firebase-admin';
import { NextFunction, Request, Response } from 'express';

const getAuthToken = (req: Request, res: Response, next: NextFunction) => {
  if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
    req.authToken = req.headers.authorization.split(' ')[1];
  } else {
    req.authToken = null;
  }
  next();
};

export const checkIfAuthenticated = (req: Request, res: Response, next: NextFunction) => {
  getAuthToken(req, res, async () => {
    try {
      const { authToken } = req;
      const userInfo = await firebase.auth().verifyIdToken(authToken);
      req.authId = userInfo.uid;
      return next();
    } catch (e) {
      return res.status(401).send({ error: 'You are not authorized to make this request' });
    }
  });
};

export const checkIfAdmin = (req: Request, res: Response, next: NextFunction) => {
  getAuthToken(req, res, async () => {
    try {
      const authToken = req;
      const userInfo = await firebase.auth().verifyIdToken(authToken);
      if (userInfo.admin === true) {
        req.authId = userInfo.uid;
        return next();
      }
    } catch (e) {
      return res.status(401).send({ error: 'You are not authorized to make this request' });
    }
  });
};

app.ts

app.get('/api/users', checkIfAuthenticated, (req, res) => {
  executeQuery('SELECT * from user')
    .then(function (results: unknown) {
      res.send(results);
    })
    .catch(function (err: unknown) {
      res.status(400).send(err);
    });
});

However, in auth.ts I keep getting the following errors, how do I fix them:

1. In getAuthToken

Error:(6, 9) TS2339: Property 'authToken' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.

Error:(8, 9) TS2339: Property 'authToken' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.

2. In checkIfAuthenticated

Error:(16, 15) TS2339: Property 'authToken' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.

Error:(18, 11) TS2339: Property 'authId' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.

3. In checkIfAdmin

Error:(30, 60) TS2345: Argument of type 'Request<ParamsDictionary, any, any, ParsedQs>' is not assignable to parameter of type 'string'.

Error:(32, 13) TS2339: Property 'authId' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.


Solution

  • Fixed it as follows:

    import * as firebase from 'firebase-admin';
    import { NextFunction, Request, Response } from 'express';
    
    export interface IGetAuthTokenRequest extends Request {
      authToken: string;
      authId: string;
    }
    
    const getAuthToken = (req: IGetAuthTokenRequest, res: Response, next: NextFunction) => {
      if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
        req.authToken = req.headers.authorization.split(' ')[1];
      } else {
        req.authToken = null;
      }
      next();
    };
    
    export const checkIfAuthenticated = (
      req: IGetAuthTokenRequest,
      res: Response,
      next: NextFunction
    ) => {
      getAuthToken(req, res, async () => {
        try {
          const { authToken } = req;
          const userInfo = await firebase.auth().verifyIdToken(authToken);
          req.authId = userInfo.uid;
          return next();
        } catch (e) {
          return res.status(401).send({ error: 'You are not authorized to make this request' });
        }
      });
    };
    
    export const checkIfAdmin = (req: IGetAuthTokenRequest, res: Response, next: NextFunction) => {
      getAuthToken(req, res, async () => {
        try {
          const userInfo = await firebase.auth().verifyIdToken(req.authToken);
          if (userInfo.admin === true) {
            req.authId = userInfo.uid;
            return next();
          }
        } catch (e) {
          return res.status(401).send({ error: 'You are not authorized to make this request' });
        }
      });