Skip to content

Instantly share code, notes, and snippets.

@anhnt
Created January 7, 2014 10:02
Show Gist options
  • Save anhnt/8297229 to your computer and use it in GitHub Desktop.
Save anhnt/8297229 to your computer and use it in GitHub Desktop.
Passport authenticate with SailsJS (v0.98)
// api/models/Account.js
module.exports = {
attributes: {
acct_id: {
type: 'int',
primaryKey: true
},
loginName: {
type: 'string',
required: true
},
email: {
type:'string',
required: true
},
phone: 'string',
fullName: {
type: 'string'
},
password: {
type: 'string',
required: true
},
posts: {
collection: 'Post'
}
}
}
// 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.redirect('/login');
return;
}
res.redirect('/');
return;
});
})(req, res);
},
logout: function (req,res)
{
req.logout();
res.redirect('/');
}
};
module.exports = AuthController;
// config/express.js
var passport = require('passport');
module.exports.express = {
customMiddleware: function (app) {
app.use(passport.initialize());
app.use(passport.session());
}
};
// api/policies/isAuthenticated.js
module.exports = function(req, res, next)
{
if (req.isAuthenticated())
return next();
else return res.redirect('/login')
}
<!-- views/auth/login.ejs -->
<form action="/login" method="post">
<div>
<label>Username:</label>
<input type="text" name="username"/><br/>
</div>
<div>
<label>Password:</label>
<input type="password" name="password"/>
</div>
<div>
<input type="submit" value="Submit"/>
</div>
</form>
// config/passport.js
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;
passport.serializeUser(function(account, done) {
done(null, account.acct_id);
});
passport.deserializeUser(function(id, done) {
Account.findOne({acct_id: id}).done(function (err, account) {
done(err, account);
});
});
passport.use(new LocalStrategy(
function(username, password, done) {
Account.findOne({ loginName: username}).done(function(err, account) {
if (err) { return done(err); }
if (!account) { return done(null, false, { message: 'Unknown user ' + username }); }
if (account.password != password) { return done(null, false, { message: 'Invalid password' }); }
return done(null, account);
});
}
));
// config/policies.js
module.exports.policies = {
'*': 'isAuthenticated',
'auth': {
'*': true
}
}
// config/routes.js
module.exports.routes = {
'/': {
controller: 'post',
action: 'index'
},
'get /login':{
controller: 'auth',
action: 'login'
},
'post /login':{
controller: 'auth',
action: 'process'
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment