DZone
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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Data Engineering
  3. Data
  4. 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 · Tutorial
Like (5)
Save
Tweet
Share
8.90K 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

  • Custom Validators in Quarkus
  • DevOps vs Agile: Which Approach Will Win the Battle for Efficiency?
  • What Is API-First?
  • Tracking Software Architecture Decisions

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • 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: