I am attempting to authenticate a user in a Node app using Sequelize and Passport. I am able to hit my database but can't seem to get a positive result. Basically, I have a simple frontend form that accepts a username and password (using the respective names "username" and "password") and then the following Passport definition:
passport.use(new localStrategy(
{usernameField: 'email'},
function(req, email, password, done) {
models.TeacherX.findOne({ email: email }, 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);
});
}
));
Then I call it with:
router.post('/login',
passport.authenticate('local', { failureRedirect: '/login?msg=failure'}),
function(req, res) {
res.redirect("/?msg=positive");
});
Since you are passing the request to the verify callback, you need to set the property passReqToCallback to true or remove the req param from the verify callback. Try this:
passport.use(new localStrategy(
{passReqToCallback: true ,
usernameField: 'email'},
function(req, email, password, done) {
models.TeacherX.findOne({ email: email }, 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);
});
}
));
Related
I'm using express-session and passport to authenticate.
Here's my module :
(updated)
passport.use(new LocalStrategy(
function(username, password, done) {
LamAdmin.findOne({ email: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: 'Incorrect username' }); }
if (!comparePassword(user.password, password)) { return done(null, false, { message: 'Incorrect password' }); }
return done(null, user);
});
}
));
router.post('/login', passport.authenticate('local',{
successRedirect: '/p/dashboard',
failureRedirect: '/p',
failureFlash: true
}));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
LamAdmin.findById(id, function (err, user) {
done(err, user);
});
});
function checkAuth(req,res,next) {
if (req.isAuthenticated()) {
next();
} else {
res.redirect('/p');
}
}
// //DOES NOT WORK WITH CHECKAUTH MIDDLEWARE
// router.get('/dashboard',(req,res,next)=> {
// res.render('dashboard');
// });
router.get('/dashboard',checkAuth,(req,res,next)=> {
res.render('dashboard');
});
checkAuth is my middleware and idk why it always returns false.
This is passport and session configs in app.js :
//sessions
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true,
cookie: { secure: false } // Remember to set this
}));
//passport
app.use(passport.initialize());
app.use(passport.session());
Is there anything wrong with my checkAuth middleware ?
Or my redirect to Dashboard view?
Thanks in advance!
When you call passport.authenticate() method, it uses a strategy to authenticate the user. If you have the user information stored in a local DB, then you can use the Local Strategy that will use username and password to authenticate. So in your app.js add the following:
const LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function(username, password, done) {
/* Change this to fetch user info from your db
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!comparePasswords(user.password, password)) { return done(null, false); }
return done(null, user);
});
*/
}
));
When the user is authenticated, serializeUser() method is called with the user object returned from the above method passed as an argument and express appends the value returned to the current user session in req.session.passport.user
passport.serializeUser(function(user, done) {
done(null, user.id);
});
On each subsequent request, when isAuthenticated() method is called, passport checks if some value is present in req.session.passport.user. If user information is present, it calls the deserializeUser() method which appends the user information to the request and can be accessed via req.user
passport.deserializeUser(function(id, done) {
// Replace it with your db
User.findById(id, function (err, user) {
done(err, user);
});
});
I am implementing the Facebook login and register functions to my application, and can reach facebook for the user to enter their information, but can't make the callback work. I have input the code below into passport.js (obviously x'ing out our information):
passport.use(new FacebookStrategy({
clientID: "xxxxxxxxxxxxxx",
clientSecret: "xxxxxxxxxxxxxxxxxxx",
callbackURL: "https://xxxxxxxxxxxxxxxx/auth/facebook/callback/",
enableProof: false,
profileFields: ['id', 'displayName', 'photos']
},
function (accessToken, refreshToken, profile, done) {
process.nextTick(function () {
User.findOne({facebookId: profile.id}, function (err, user) {
if (err) {
return done(err);
}
if (user) {
return done(null, user);
} else {
var data = {
facebookId: profile.id,
f_name: profile.first_name,
l_name: profile.last_name,
username: profile.email
};
if (profile.emails && profile.emails[0] && profile.emails[0].value) {
data.username = profile.emails[0].value;
}
User.create(data, function (err, user) {
return done(err, user);
});
}
});
});
}));
passport.serializeUser(function(user, callback) {
callback(null, user._id);
});
passport.deserializeUser(function(id, done) {
User.findById({
_id: id
}, function(err, user) {
callback(err, user);
});
});
passport.use(new LocalStrategy(
function (username, password, done) {
console.log(username);
console.log(password);
User.findOne({ 'username': username }, function (err, user) {
// if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect email.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));
The following callback URL has been included in index.js:
router.get('/auth/facebook', passport.authenticate('facebook', {
scope: 'email' }));
router.get('/auth/facebook/callback',
passport.authenticate('facebook', {
successRedirect : '/user/#/home',
failureRedirect : '/'
}));
I am able to make the application direct to the Facebook login page onClick, but once the user enters their email and password into facebook, the application is unable to reload on redirect and get the person to our homepage. The redirect begins to happen, but hits an error once it tries to load our application. Could we be utilizing one of the redirect fields incorrectly? As a side note, what should we set as a valid OAuth Redirect URI on the facebook developer application page?
I am using passport-local and passport-facebook strategies for authentication in sails.js. Authentication with email is working fine. But when user authenticates using facebook, I am getting this error message [Error: Failed to serialize user into session].
Then I tested serializeUser method and it turns out user param is empty in case of facebook. While I also tried to see if verifyHandler is called or not and it is not being called.
Here is my code for the facebook authentication action:
facebook: function (req, res) {
passport.authenticate('facebook', {failureRedirect: '/login', scope: ['email']}, function (err, user) {
if ((err) || (!user)) {
req.session.flash = {
errMsg: 'Email or password mismatch.'
}
return res.redirect('/login');
}
req.logIn(user, function (err) {
if (err) {
console.log(err);
res.view('500');
return;
}
res.redirect('/');
return;
});
})(req, res);
}
And this is the code of passport.js service (api/services/passport.js)
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
FacebookStrategy = require('passport-facebook').Strategy,
bcrypt = require('bcrypt');
var verifyHandler = function (token, tokenSecret, profile, done) {
console.log('in verifyHandler'); // this line is not being executed.
console.log(profile);
process.nextTick(function () {
User.findOne({uid: profile.id}, function (err, user) {
if (err) {
return done(err);
}
if (user) {
return done(null, user);
} else {
var data = {
provider: profile.provider,
uid: profile.id,
name: profile.displayName
};
if (profile.emails && profile.emails[0] && profile.emails[0].value) {
data.email = profile.emails[0].value;
}
User.create(data, function (err, user) {
return done(err, user);
});
}
});
});
};
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function (email, password, done) {
User.findOne({email: email}).exec(function (err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, {message: 'Unknown user ' + email});
}
bcrypt.compare(password, user.password, function (err, res) {
if (!res) return done(null, false, {message: 'Invalid Password'});
return done(null, user);
});
});
}
));
passport.use(new FacebookStrategy({
clientID: sails.config.facebook.clientID,
clientSecret: sails.config.facebook.clientSecret,
callbackURL: sails.config.facebook.callbackURL
}, verifyHandler));
And finally (config/passport.js)
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
FacebookStrategy = require('passport-facebook').Strategy;
module.exports = {
http: {
customMiddleware: function (app) {
app.use(passport.initialize());
app.use(passport.session());
}
}
};
Any thoughts?
Check if user.id is defined and it is string but not ObjectId().
in
passport.serializeUser(function (user, done) {
done(null, user.id);
});
I'm new to node express and passport so I'm not sure what I'm missing. I'm trying to use a custom callback as all I want is a json response from my registration strategy. Currently I keep getting the following error "Missing credentials". I've been at it for a while now and I'm stuck.
Here is my controller:
app.post('/services/authentication/registration', function(req, res, next) {
console.log('before authentication')
passport.authenticate('local-registration', function(err, user, info) {
console.log('authentication callback');
if (err) { return res.send({'status':'err','message':err.message});}
if (!user) { return res.send({'status':'err','message':info.message});}
if (user!=false) { return res.send({'message':'registration successful'});}
})(req, res, next);
},
function(err, req, res, next) {
return res.send({'status':'err','message':err.message});
});
And my passport strategy:
passport.use('local-registration', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) {
console.log('credentials passed to passport' + email + '' + password)
// asynchronous
// User.findOne wont fire unless data is sent back
process.nextTick(function() {
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error
if (err)
return done(err);
// check to see if theres already a user with that email
if (user) {
return done(null, false, {message: 'User already exists'});
} else {
// if there is no user with that email
// create the user
var newUser = new User();
// set the user's local credentials
newUser.local.email = email;
newUser.local.password = newUser.generateHash(password);
// save the user
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}));
I dont think you should send "req" as a parameter to the authentication function. take a look at this example from the passport docs:
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: 'Incorrect username.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));
I have a simple users collection in my MongoDB. I user mongo-native driver.
{
"email": "johndow#example.com",
"password": "123456",
"_id": {
"$oid": "50658c835b821298d3000001"
}
}
As I user auth via pair email:pass, I re-wrote default passport-local function findByUsername to this:
function findByEmail(email, fn) {
db.collection("users", function(err, collection) {
collection.find({}, {}, function(err, users) {
users.each(function(err, user) {
if (user.email === email) {
return fn(null, user);
}
});
return fn(null, null);
});
});
}
Just get all of the users form DB, and checking - if user.email == provided email, then return user object.
I use _id parameter of MongoDB as id for users, that's why I've modifies these two functions:
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
findById(id, function(err, user) {
done(err, user);
});
});
And this is my code for passport local strategy:
passport.use(new LocalStrategy( function(email, password, done) {
process.nextTick(function() {
console.log('initialize findByEmail() for "',email,'"');
findByEmail(email, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
console.log('Unknown user ' + email)
return done(null, false, {
message: 'Unknown user ' + email
});
}
if (user.password != password) {
console.log('Invalid password')
return done(null, false, {
message: 'Invalid password'
});
}
//сonsole.log('ALL VERIFIATION PASSED');
return done(null, user);
})
});
}));
I post data from login page:
app.post('/login', passport.authenticate('local', {
failureRedirect: '/',
failureFlash: true
}), function(req, res) {
res.redirect('/desk');
});
And I get
Error: Can't set headers after they are sent.
and after this I get
TypeError: Cannot read property 'email' of null
The last error is really strange 'cause findByEmail has console.log(user) line (removed from this listing) and it list all the user's data.
What am I doing wrong?
It's not well documented, but cursor.each provides a null value to the second parameter of its callback to indicate that the cursor has no more documents available. It's only mentioned in the example of the documentation.
So in your case you should be checking for user !== null in your users.each callback.
However, it would be more efficient to have mongo do the searching for you by changing your find call to:
collection.findOne({email: email}, {}, function(err, user) {
if (user) {
// email was found case
...
}
...
}