in passport js, basic strategy, the following code sample provides a function for verifying the identity of a user.
passport.use(new BasicStrategy(
function(userid, password, done) {
User.findOne({ username: userid }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!user.verifyPassword(password)) { return done(null, false); }
return done(null, user);
});
}
));
Question is where (which file) in a Sails application should this code be placed? I suppose same applies for a custom verification function?
create AuthController under controllers directory
then write code to make passport handle login process
login: function(req, res) {
passport.authenticate('local', function(err, user, info) {
if ((err) || (!user)) {
return res.send({
message: info.message,
user: user
});
}
req.logIn(user, function(err) {
if (err) res.send(err);
return res.send({
message: info.message,
user: user
});
});
})(req, res);
this line passport.authenticate('local' will read configuration from passport.js inside config.js which will be like this :-
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function(email, password, done) {
User.findOne({ email: email }, function (err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect email.' });
}
bcrypt.compare(password, user.password, function (err, res) {
if (!res)
return done(null, false, {
message: 'Invalid Password'
});
var returnUser = {
email: user.email,
createdAt: user.createdAt,
id: user.id
};
return done(null, returnUser, {
message: 'Logged In Successfully'
});
});
});
add these line into route.js :- 'post /login': 'AuthController.login'
Related
I'm trying to secure an API endpoint on a node.js express app that uses passport.
This is my route:
router.post('/api/devices', authController.isAuthorized, catchErrors(deviceController.getDevicesAPI));
This is my authorization method:
exports.isAuthorized = (req, res, next) => {
passport.authenticate('local', {session: false}, (err, user, info) => {
if (err || !user) {
return res.json({ message: 'Something is not right ', err, info });
}
req.login(user, {session: false}, (err) => {
if (err) {
res.send(err);
}
next();
});
})(req, res);
};
From Postman or a separate local server, I get the response:
{
"message": "Something is not right ",
"err": null,
"info": {
"message": "Missing credentials"
}
}
This is the Postman configuration:
What am I missing?
How is your local strategy configured? It seems like a database query problem
As the sample in http://www.passportjs.org/docs/username-password/, please see my comments below
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function(username, password, done) { //<--- Here is where you pass the UN&PASS
User.findOne({ username: username }, function(err, user) { //<--- Here is the sample code that should find you a user
if (err) { return done(err); } //<--- Here could be where the response is coming from
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user); //<--- Here is the sample code that should let you return that user
});
}
));
I finally dug it out from here. User.authenticate() is the method I was looking for.
exports.isAuthorized = async (req, res, next) => {
const username = req.body.username;
const password = req.body.password;
const user = await User.findOne({ email: username });
if (!user) {
res.sendStatus(403);
return;
}
user.authenticate(password, function(err, result) {
if (result) {
next();
return;
}
res.sendStatus(403);
});
};
I have this problem in the time i am in admin routes and i try to add a new article or a new image in my database , the same things happen even when i want to update something ....
this is my codes ?
exports.isAdmin = (req, res, next) => {
if (req.isAuthenticated() && res.locals.user.admin == 1) {
next();
} else {
req.flash("danger", "please log in as admin");
res.redirect("/users/login");
}
}
var LocalStrategy = require("passport-local").Strategy;
var User = require("../models/user");
var bcrypt = require("bcryptjs");
module.exports = function (passport) {
passport.use(new LocalStrategy(function (username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err)
console.log(err);
if (!user) {
return done(null, false, { message: "No user found" });
}
bcrypt.compare(password, user.password, function (err, isMatch) {
if (err) console.log(err);
if (isMatch) {
return done(null, user);
} else {
return done(null, false, { message: "Wrong password" });
}
})
});
}));
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
}
Anyone one can help the problem is i think in res.locals.user.admin but in other admin routes works ok but only when i want to add a new and edit a think happen this problem
I'm still a noob to node and webdev, but trying hard!
I get this error : can't set headers after they are sent
with the following while using passport.js and bcryptjs compare method for password validation on a mean stack
routes/login.js
var express = require('express')
var router = express.Router()
var mongoose = require('mongoose')
var User = mongoose.model('User')
var passport = require('passport')
router.post('/', function (req, res, next){
passport.authenticate('local', function(err, user, info){
if(err){ return next(err); }
if(user){
return res.json({token: user.generateJWT()});
} else {
return res.status(401).send(info)
}
})(req, res, next);
});
module.exports = router
authenticate/local.js
var passport = require('passport')
var LocalStrategy = require('passport-local').Strategy
var mongoose = require('mongoose')
var User = mongoose.model('User')
var bcrypt = require('bcryptjs')
passport.use(new LocalStrategy(function(username, password, done) {
User.findOne({
username: username
}, function(err, user) {
if (err) {
return done(err)
}
if (!user) {
return done(null, false, {
message: {
username: 'Incorrect username.'
}
})
}
bcrypt.compare(password, user.password, function(err, isMatch) {
if (err) {
return done(err)
}
if (!isMatch) {
return done(null, false, {
message: {
password: 'Incorrect password'
}
})
}
});
return done(null, user);
});
}));
This validates correctly for a valid username and password, and logs in.
For an invalid username, it correctly rejects the login attempt.
But for an invalid password, it logs in and then crashes the app with the Can't set headers error.
However if i change the bcrypt.compare to bcrypt.compareSync, then all validations are correct.
if (!bcrypt.compareSync(password, user.password)) {
return done(null, false, {
message: {
password: 'Incorrect password'
}
});
}
I would rather not depend on the sync methods, so help me please understand where I am going wrong!
bcrypt.compare() is async but you're calling done(null, user) immediately. Move it inside the callback and it should be fine:
bcrypt.compare(password, user.password, function(err, isMatch) {
if (err) { return done(err) }
if (!isMatch) {
return done(null, false, { message: { password: 'Incorrect password' } })
}
done(null, user)
})
I'm making a form login by passportJs and it always return failureRedirect. I have search in stack overflow for this issue, but still not have the correct answer. Here is my code:
Form making form jade:
form(method='post', action='/users/login', enctype='multipart/form-data')
.form-group
label Username
input.form-control(name='username', type='text' placeholder='Enter Username')
.form-group
label Password
input.form-control(name='password', type='password' placeholder='Enter password')
input.btn.btn-default(name='submit', type='submit', value='Login')
Router Hanlde is using express framework form Nodejs and passport middleware:
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
},
function(username, password, done) {
User.getUserByUsername(username, function(err, user) {
if (err) throw err;
if (!user) {
console.log('Unknown User');
return done(null, false, {
message: 'Unknown User'
});
}
User.comparePassword(password, user.password, function(err, isMatch) {
if (err) throw err;
if (isMatch) {
return done(null, user);
} else {
console.log('Invalid Password');
return done(null, false, {
message: 'Invalid Password'
});
}
});
});
}
));
router.post('/login', passport.authenticate('local', {
failureRedirect: '/users/login',
failureFlash: 'Invalid username or password'
}), function(req, res) {
console.log('Authentication Successful');
req.flash('success', 'You are logged in ');
res.redirect('/');
});
Looking at getUserByUsername function you shared in comments, it looks like you are not making call to callback function of getUserByUsername in correct way and therefore it is not getting user object resulting into failure redirect. The function you shared was:
module.exports.getUserByUsername = function(username, callback){
var query = {username: username};
User.findOne(query, callback);
}
Changing it to following should fix your issue:
module.exports.getUserByUsername = function(username, callback){
var query = {username: username};
User.findOne(query, function(err, user) {
callback(err, user);
});
}
I need to write commonplace code to check a Current User Password value submitted via form to see if it matches the existing password in the database, and if so, update the password to a New Password value that was submitted via the same form.
Yet, I can't find any good examples of how to do this using Passport.js. Can anyone advise as to how I can do this in my Users controller down below, if there are any helper functions provided by passport that I should use for this, and how I do this with hashed and salted passwords?
Here is my code:
// Form Submitted
req.body = {
_id: '5294198b7b35ad2794000001',
email: 'testusera1#abc.net',
name: 'John Smith',
provider: 'local',
username: 'ab123',
current_password: 'currentpassword',
new_password: 'newpassword'
}
// Route
app.put('/users/me', users.update);
// Controller
var mongoose = require('mongoose'),
User = mongoose.model('User'),
_ = require('underscore'),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;
exports.update = function(req, res) {
var user = req.user
user = _.extend(user, req.body);
user.save(function(err) {
if(err) { console.log(err) };
res.jsonp(user);
});
};
// Passport Config File
module.exports = function(passport) {
//Serialize sessions
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findOne({
_id: id
}, function(err, user) {
done(err, user);
});
});
//Use local strategy
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function(email, password, done) {
User.findOne({
email: email
}, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, {
message: 'Unknown user'
});
}
if (!user.authenticate(password)) {
return done(null, false, {
message: 'Invalid password'
});
}
return done(null, user);
});
}
));
};
hashed and salted password
full example on github
// Bcrypt middleware
userSchema.pre('save', function(next) {
var user = this;
if(!user.isModified('password')) return next();
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if(err) return next(err);
bcrypt.hash(user.password, salt, function(err, hash) {
if(err) return next(err);
user.password = hash;
next();
});
});
});
// Password verification
userSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if(err) return cb(err);
cb(null, isMatch);
});
};