DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > Effortless Passport.js for Sails.js

Effortless Passport.js for Sails.js

There are several extensions for using Passport.js with Sails.js, but this post has an easier, simpler method.

Younes Ouadi user avatar by
Younes Ouadi
·
Oct. 12, 15 · Web Dev Zone · Tutorial
Like (5)
Save
Tweet
8.67K Views

Join the DZone community and get the full member experience.

Join For Free

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

You look around and you found that Sails.js Doc has a dedicated page on the integration of the two frameworks. The page presents two promizing Sails.js extensions sails-auth and sails-pemissions that will make your life easy. However, your current need doesn't justify using these two extensions and you decide 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 don't want to dig into details. In another article, I will go through the full story in addition to listing enhancements that make the integration enterprise-grade.

1) Start the 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 application

$ 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.
Framework Integration app Web Service application Dig (command) Testing Data Types security Build (game engine)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • What Is Edge Compute? It’s Kind of Like Knitting Dog Hats
  • Handling Multiple Browser Windows and Tabs in Selenium PHP
  • RestTemplate vs. WebClient
  • Demystifying Cloud-Native Data Management: Layers of Operation

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo