Pages

Friday, January 13, 2017

Building a Shared Calendar [Part 9]: Add validation to the express.js router

In the last post I described how to create an event using Google's Calendar API. One thing that was left pending was to protect the route so that only authenticated users sending valid data can make use of it.

To validate that a user is authenticated we can attach a behavior to the router so that it inspects all requests and returns a 403 for unauthenticated requests:
var express = require('express');
var router = express.Router();

router.use(function(req, res, next) {
    if (!req.user) {
        res.status(403).send('Unauthorized');
    } else {
        next();
    }
});

Now, for validating the request parameters I used the express-validator npm package. Once installed and attached to the pipeline it adds helper methods to the request object that can be used to check each parameter using a fluent API:
router.post('/addEvent', function(req, res, next) {
    req.checkBody('summary', 'Summary is required.').notEmpty();
    req.checkBody('startTime', 'Start time is required.').notEmpty().isNumeric();
    req.checkBody('endTime', 'End time is required.').notEmpty().isNumeric();

    var errors = req.validationErrors();

    if (errors) {
        res.status(400).send(errors[0].msg);
    }

    ...
});

As can be seen, if any of the checks fail the error message is returned to the client with a 400 response.

This will be the last post of this series, even though the site was never published it was a good experiment and learning experience of consuming one of Google APIs. The source code is available at bitbucket or you can play with the live test site.


Federico

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.