Friday, October 9, 2015

Passport.js for Sails.js

So, you start your new Webapp project and you decide to build it using the great MVC framework Sails.js. You have also decided to use the other great security framework Passport.js to handle authentication.

You look around and you found that Sails.js site has a dedicated page on the integration of the two frameworks. The page presents two promising Sails.js extensions sails-auth and sails-pemissions that will make you life easy. However, your current need doesn't justify using these two extensions and, rather, you decided to take a simple path.

This article will present the simplest way to get Sails.js and Passport.js up and running. It will tell the short story for people that doesn't want to dig into details. In another article, I will go through the full story in addition of listing enhancements to make the integration enterprise-grade.

1) Start development of your Webapp
$ npm install -g sails
$ mkdir ~/sails-experiments
$ cd ~/sails-experiments
$ sails new webapp
$ cd webapp
$ npm install --save passport passport-local

2) Create the controller api/controllers/AuthController.js
var passport = require('passport');

module.exports = {
    login: function (req, res) {
        passport.authenticate('local', function(err, user, info) {
            if ((err) || (!user)) {
                return res.send({message: 'login failed'});
            }          

            req.logIn(user, function(err) {
                if (err) return res.send(err);

                return res.send({message: 'login successful'});
            });        
        })(req, res);
    }, 
    logout: function (req,res){
        req.logout();
        res.send('logout successful');
    }  
};
3) Create the service api/services/passport.js
var passport        = require('passport');
var LocalStrategy    = require('passport-local').Strategy;

var __users__ = [
    { id: 1, username: 'u1', password: 'p1',},
    { id: 2, username: 'u2', password: 'p2',},
    { id: 3, username: 'u3', password: 'p3',},
    { id: 4, username: 'u4', password: 'p4',},
    { id: 5, username: 'u5', password: 'p5',},
];

function findById(id, fn) {
    var user = null;
    for ( var index = 0; index < __users__.length; index++ ) {
        if ( __users__[index].id === id ) {
            user = __users__[index];
            break;
        }
    }
    return fn(null, user);
}

function findByUsername(username, fn) {
    var user = null;
    for ( var index = 0; index < __users__.length; index++ ) {
        if ( __users__[index].username === username ) {
            user = __users__[index];
            break;
        }
    }
    return fn(null, user);
}

passport.serializeUser(function (user, done) {
    done(null, user.id);
});

passport.deserializeUser(function (id, done) {
    findById(id, function (err, user) {
        done(err, user);
    });
});

passport.use(new LocalStrategy(
    function (username, password, done) {
        findByUsername(username, function (err, user) {
            if (err                                    ) return done(null, err);
            if (!user || user.password !== password    ) return done(null, false, {message: 'Invalid username or password'});
            return done(null, user, {message: 'Logged In Successfully'});
        });
    }
));
4) Configure the HTTP middleware config/http.js
module.exports.http = {
    middleware: {
        passportInit    : require('passport').initialize(),
        passportSession : require('passport').session(),

        order: [
            'startRequestTimer',
            'cookieParser',
            'session',
            'passportInit',
            'passportSession',
            'myRequestLogger',
            'bodyParser',
            'handleBodyParserError',
            'compress',
            'methodOverride',
            'poweredBy',
            '$custom',
            'router',
            'www',
            'favicon',
            '404',
            '500',
        ],
    },
};
5) Test your Webapp
$ sails lift&
$ curl http://localhost:1337/auth/login?username=u1\&password=p1
login successful.
$ curl http://localhost:1337/auth/login?username=u1\&password=p2
login failed.
$ curl http://localhost:1337/auth/login?username=u6\&password=p6
login failed.

No comments:

Post a Comment