buzzfeed-openlab / buzzbot

🤖 Beep Boop Bop – I am BuzzBot; a facebook messenger bot for newsrooms
https://www.buzzfeed.com/westleyargentum/under-the-hood-of-buzzbot
MIT License
70 stars 9 forks source link

how to add authentication to the api and amin dashboard? #49

Closed WestleyArgentum closed 8 years ago

WestleyArgentum commented 8 years ago

There have been some questions about how to add auth to the api and admin dashboard, so here's a quick run down:

Initially there was basic auth in buzzbot itself, but it was stripped out because internally we have an nginx instance that sits in front of buzzbot, handles authentication using our login system, and forwards everything to buzzbot.

If you have an internal auth system that you can put buzzbot behind, that proved to be the easiest and most secure for us. But if not, there are basically 2 places where you need to introduce basic auth.

1) For the http endpoints and for serving the static admin interface files, you need to write a little piece of express middleware and make sure it is used for all the routes. It will look something like:

function auth(req, res, next) {
    function unauthorized(res, user) {
        console.log('WARNING, unauthorized attempt by user:', user, 'to access route:', req.originalUrl);
        res.set('WWW-Authenticate', 'Basic');
        return res.sendStatus(401);
    }

    var user = basicAuth(req);

    if (!user || !user.name || !user.pass) {
        return unauthorized(res, user);
    }

    if (user.name === config.auth.user && user.pass === config.auth.password) {
        return next();
    } else {
        return unauthorized(res, user);
    }
};

2) For websockets, you need to write a little piece of middleware for socket.io (which ends up being simple but is not well documented):

if (config.env != 'development') {
    io.use((socket, next) => {
        var user = basicAuth(socket.request);
        if (!user || user.name !== config.auth.user || user.pass !== config.auth.password) {
            return console.log('WARNING, unauthorized websocket connection attempt:', user);
        }
        next && next();
    });
}

You can actually see all the auth changes being stripped out here: https://github.com/buzzfeed-openlab/buzzbot/commit/c3678099a39e4cb73c9c490214aea61d6abb0a26 So if you want you can fork and add those back in.