Firebase part V: authentication and middleware

1st Oct 19
person sketching out plan on white board

I will add authentication to certain routes facilitated by setting up middleware.

In Express you can pass a second argument that is a callback, which acts as a middleware that intercepts the request.  Middleware allows me to make changes to the request and response objects or end the request-response cycle.  Within my middleware I check whether the route has an authorisation header and if so I assign the token to a variable.  If not I will halt the request, preventing the user from accessing the route as unauthorised.   

const FBAuth = (req, res, next) => {
let idToken;
if(req.headers.authorization && req.headers.authorization.startsWith('Bearer ')){
    idToken = req.headers.authorization.split('Bearer ')[1];
}else{
    console.error('No token found');
    return res.status(403).json({error: 'Unauthorised'});   
}

Firebase admin has an inbuilt verifyIdToken method that can check verify and decode the token.  The decoded token is assigned the the request user object and as there is additional data that should be included in the user object like username and admin, I assign it in the next 'then' block (which returns the document from the collection).

The next function is called when the users token has been successfully verified and calls the next function in the stack (the request / response).

 admin.auth().verifyIdToken(idToken)
            .then(decodedToken => {
                req.user = decodedToken;
                db.collection('users')
                    .where('userId', '==', req.user.uid)
                    .limit(1)
                    .get()
            })
            .then(data => {
                req.user.handle = data.docs[0].data().handle; 
                req.user.admin = data.docs[0].data().admin; 
                return next();
            })
            .catch(err => {
                console.error('Error while verifying token');
                return res.status(403).json(err);
            });

 

I add the middleware to the post 'bonsai' route.  

app.post('/bonsai', FBAuth, (req, res) => {

 

I have recently completed my apprenticeship.  I am currently building the API to a React JS site using Firebase.