Skip to content

Instantly share code, notes, and snippets.

@Mantish
Forked from theangryangel/AuthController.js
Last active December 21, 2015 21:09
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save Mantish/6366642 to your computer and use it in GitHub Desktop.
Save Mantish/6366642 to your computer and use it in GitHub Desktop.
Sails.js (v0.9.3) authentication using Passportmiddleware
// api/controllers/AuthController.js
var passport = require('passport');
var AuthController = {
login: function (req,res)
{
res.view();
},
process: function(req, res)
{
passport.authenticate('local', function(err, user, info)
{
if ((err) || (!user))
{
res.redirect('/login');
return;
}
req.logIn(user, function(err)
{
if (err)
{
res.view();
return;
}
res.redirect('/');
return;
});
})(req, res);
},
logout: function (req,res)
{
req.logout();
res.redirect('/');
}
};
module.exports = AuthController;
// api/policies/authenticated.js
// We use passport to determine if we're authenticated
module.exports = function(req, res, next)
{
if (req.isAuthenticated())
return next();
res.redirect('/auth/login');
}
// config/bootstrap.js
module.exports.bootstrap = function (cb) {
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing.
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findOne(id).done(function (err, user) {
done(err, user);
});
});
// Use the LocalStrategy within Passport.
// Strategies in passport require a `verify` function, which accept
// credentials (in this case, a username and password), and invoke a callback
// with a user object. In the real world, this would query a database;
// however, in this example we are using a baked-in set of users.
passport.use(new LocalStrategy(
function(username, password, done) {
// Find the user by username. If there is no user with the given
// username, or the password is not correct, set the user to `false` to
// indicate failure and set a flash message. Otherwise, return the
// authenticated `user`.
findByUsername(username, function(err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
return done(null, user);
});
}
));
// It's very important to trigger this callack method when you are finished
// with the bootstrap! (otherwise your server will never lift, since it's waiting on the bootstrap)
cb();
};
// config/express.js
var passport = require('passport');
module.exports.express = {
customMiddleware: function (app) {
app.use(passport.initialize());
app.use(passport.session());
}
};
// views/auth/login.ejs
<form action="/login" method="post">
<div>
<label>Username:</label>
<input type="text" name="username"/>
</div>
<div>
<label>Password:</label>
<input type="password" name="password"/>
</div>
<div>
<input type="submit" value="Submit"/>
</div>
</form>
// config/policies.js
/**
* Policy defines middleware that is run before each controller/controller.
* Any policy dropped into the /middleware directory is made globally available through sails.middleware
* Below, use the string name of the middleware
*/
module.exports.policies = {
// default require authentication
// see api/policies/authenticated.js
'*': 'authenticated',
// whitelist the auth controller
'auth':
{
'*': true
}
};
// views/auth/signup.ejs
<form action="/user/create" method="post">
<p>
<label for="username">Username:</label>
<input id="username" type="text" name="username"/>
</p>
<p>
<label for="password">Password:</label>
<input id="password" type="password" name="password"/>
</p>
<p>
<input type="submit" value="Sign Up"/>
</p>
</form>
@mikebolivar
Copy link

Hello @Mantish in Sails V0.9.4, where is express.js file??? Thank you.

@jrmlstf
Copy link

jrmlstf commented Sep 22, 2013

You have to create it. I guess that @Mantish called it express.js because it configures the Express app on which Sails is built.

@codeboyim
Copy link

@jrmlstf a side question from a node/sailsjs newbie: anything in the config folder will be loaded at some stage ( I guess when app initialisation), so the name of the file is not a matter, right?

@Nek-
Copy link

Nek- commented Nov 26, 2013

@mikebolivar express.js is in your config folder ;-)

Thank you @Mantish for your piece of code !

One more little precision... Do not use '*': false if you want to access your page ! See https://github.com/balderdashy/sails-docs/blob/0.9/policies.md#how-do-i-protect-my-controllers-with-policies

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment