joël joël - 6 months ago 14
Node.js Question

How to use http-auth with Sails

I have deployed my Sails app to a PaaS, and I'd like to have simple password protect so that no one can access my staging server.

What's the simplest way to do that?

Looks like http-auth, the doc explains how to implement for ExpressJS, but with SailsJS I don't find

app.use()


what I have tried



In my
policies.js
file

module.exports.policies = {

// '*': true,
'*': require('http-auth').basic({
realm: 'admin area'
}, function customAuthMethod (username, password, onwards) {
return onwards(username === "Tina" && password === "Bullock");
}),


which leads to

info: Starting app...

error: Cannot map invalid policy: { realm: 'admin area',
msg401: '401 Unauthorized',
msg407: '407 Proxy authentication required',
contentType: 'text/plain',
users: [] }


also it looks like Policies can't apply to views, but to actions only hm...

Answer

The way I did it was using config/http.js file. Creating custom middleware there...

This is my http.js file:

var basicAuth = require('basic-auth'),
    auth = function (req, res, next) {
        var user = basicAuth(req);
        if (user && user.name === "username" && user.pass === "password") return next();
        res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
        return res.send(401);
    };

module.exports.http = {

    customMiddleware: function (app) {
        app.use('/protected', auth);
    },

    middleware: {

        order: [
            'startRequestTimer',
            'cookieParser',
            'session',
            // 'requestLogger',
            'bodyParser',
            'handleBodyParserError',
            'compress',
            'methodOverride',
            'poweredBy',
            '$custom',
            'router',
            'www',
            'favicon',
            '404',
            '500'
        ],

        requestLogger: function (req, res, next) {
            console.log("Requested :: ", req.method, req.url);
            console.log('=====================================');
            return next();
        }

    }
};
Comments