I'm having some trouble with using Passport for authentication.
I've defined my signup strategy as follows:
passport.use('local_signup', new localStrategy({
usernameField: 'username',
passwordField:'password',
passReqToCallback: true
},function(req,username, password,done){
User.findOne({username: username},function(err,user){
if(err){
console.log(err);
} else{
if(user){
console.log("user exists.")
}
else{
const newUser = new User();
newUser.email = req.body.email;
newUser.password =req.body.password;
newUser.username = req.body.user_name;
newUser.first_name = req.body.first_name;
newUser.last_name = req.body.last_name;
newUser.save(function(err){
if(err){
console.log(err);
}else{
console.log('success');
}
})
}
}
})
})
)
I've then called this strategy in my register route
app.post('/register', passport.authenticate('local_signup', {
successRedirect : '/drinks',
failureRedirect : '/register',
failureFlash : true
}));
If the authentication was successful it should trigger the drinks route
app.get('/drinks',function(req,res){
if(req.isAuthenticated()){
res.render('start');
} else {
res.redirect('/login')
}
})
successRedirect isn't redirecting to the desired page. It remains stuck on the register route. The populated users however are showing up on my database so at least my strategy is working. I don't know how to debug this. Any help would be appreciated. Thanks
You are not making use of done(). From what I understand, it is an exit point from the strategy code and letting the flow go to success or failure based on the params you pass in it. It is a param in your callback in your strategy implementation code. It is something internal to passport.
Call it like this in case of success:
return done(null, newUser);
Call it like this in case of error:
done(err);
Related
I've been taking courses and watching tutorials on NodeJS for awhile and decided to put them to good use in an app.
For this project I need users to signup and login in order to store their activity in a database. I used Passport to do this process, the code for this section of the project is this:
/****** Passport functions ******/
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
db.user.findOne( { where : { idUser : id } }).then(function (err, user) {
done(err, user);
});
});
//Facebook
passport.use(new FacebookStrategy({
//Information stored on config/auth.js
clientID: configAuth.facebookAuth.clientID,
clientSecret: configAuth.facebookAuth.clientSecret,
callbackURL: configAuth.facebookAuth.callbackURL,
profileFields: ['id', 'emails', 'displayName', 'name', 'gender']
}, function (accessToken, refreshToken, profile, done) {
//Using next tick to take advantage of async properties
process.nextTick(function () {
db.user.findOne( { where : { idUser : profile.id } }).then(function (err, user) {
if(err) {
return done(err);
}
if(user) {
return done(null, user);
} else {
db.user.create({
idUser : profile.id,
token : accessToken,
nameUser : profile.displayName,
email : profile.emails[0].value,
sex : profile.gender
});
return done(null);
}
});
});
}));
app.use(express.static(__dirname + '/public/'));
/* FACEBOOK STRATEGY */
// Redirect the user to Facebook for authentication. When complete,
// Facebook will redirect the user back to the application at
// /auth/facebook/callback//
app.get('/auth/facebook', passport.authenticate('facebook', { scope : ['email']}));
/* FACEBOOK STRATEGY */
// Facebook will redirect the user to this URL after approval. Finish the
// authentication process by attempting to obtain an access token. If
// access was granted, the user will be logged in. Otherwise,
// authentication has failed.
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { successRedirect: '/app',
failureRedirect: '/' }));
app.get('/', function (req, res) {
res.render('/');
});
app.get('/app', isLoggedIn, function (req, res) {
res.sendFile('app.html');
});
function isLoggedIn(req, res, next) {
if(req.isAuthenticated()) {
return next();
} else {
res.redirect('/');
}
}
The tutorial I followed on Facebook Auth using Passport used pretty much the same code, I changed the User model because the tutorial used Mongoose and I'm using Sequelize but this aspect is working great, when I click to signup with FB it registers me or logs me in, the queries do the work.
However, what isn't working is the redirection. When I register using facebook, it gets stuck and doesn't load anything (wheel keeps spinning on index.html (where the FB button is) and doesn't load anything). When I login using facebook, it only displays this on the screen:
[object SequelizeInstance:user]
On the tutorial, the instructor used EJS as a template language,however I already built 95% of the front end of the project using HTML, CSS and jQuery (yeah, should have used React or Angular but time is sensitive and was already learning Node). I believe this is one of the reasons this is happening but I'm not 100% sure on what is going on here and why I'm getting the error or how to get around.
Any help is appreciated, if more information / code is needed, let me know. Thank you
So after a good amount of time debugging and with some good help, I figured out what was causing my problem, there were actually three errors in there.
First of all, in the Facebook Strategy, this is how I should had built it:
passport.use(new FacebookStrategy({
//Information stored on config/auth.js
clientID: configAuth.facebookAuth.clientID,
clientSecret: configAuth.facebookAuth.clientSecret,
callbackURL: configAuth.facebookAuth.callbackURL,
profileFields: ['id', 'emails', 'displayName', 'name', 'gender']
}, function (accessToken, refreshToken, profile, done) {
//Using next tick to take advantage of async properties
process.nextTick(function () {
db.user.findOne( { where : { idUser : profile.id } }).then(function (user, err) {
if(err) {
return done(err);
}
if(user) {
return done(null, user);
} else {
//Create the user
db.user.create({
idUser : profile.id,
token : accessToken,
nameUser : profile.displayName,
email : profile.emails[0].value,
sex : profile.gender
});
//Find the user (therefore checking if it was indeed created) and return it
db.user.findOne( { where : { idUser : profile.id } }).then(function (user, err) {
if(user) {
return done(null, user);
} else {
return done(err);
}
});
}
});
});
}));
The callback after db.user.findOne had switched parameters, so it was giving me an error every time even though it didn't have one, so I switched those and also added a query to look for the user in the DB after creating it to be able to return it.
On the second facebook route, this is how I built it:
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { failureRedirect: '/' }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('../../app.html');
});
This allowed me to continue using HTML (I'll probably rewrite it to use a better view later on), and on testing, I was able to get the information from req.user.
Finally, I had a minor naming error on Passport's serializeUser:
passport.serializeUser(function (user, done) {
done(null, user.idUser);
});
Just changing from user.id to user.idUser to maintain the naming convention I used.
Hopefully this helps other people using Sequelize with Passport.
I have been looking at some passport.js tutorials online but haven't grasped a clear understanding of what is happening. Can someone help me clear my doubts below? Please read the paragraph at the bottom first.
So assuming I set up everything correctly, this is the login strategy:
passport.use('login', new LocalStrategy({
passReqToCallback : true
},
function(req, username, password, done) {
// check in mongo if a user with username exists or not
User.findOne({ 'username' : username },
function(err, user) {
// In case of any error, return using the done method
if (err)
return done(err);
// Username does not exist, log error & redirect back
if (!user){
console.log('User Not Found with username '+username);
return done(null, false,
req.flash('message', 'User Not found.'));
}
// User exists but wrong password, log the error
if (!isValidPassword(user, password)){
console.log('Invalid Password');
return done(null, false,
req.flash('message', 'Invalid Password'));
}
// User and password both match, return user from
// done method which will be treated like success
return done(null, user);
}
);
}));
Now in my app.js (server) I have this as one of my routes:
/* Handle Login POST */
router.post('/login', passport.authenticate('login', {
successRedirect: '/home',
failureRedirect: '/',
failureFlash : true
}));
Now in my AJS file:
app.controller('loginController', function($scope) {
var user = $resource('/login');
$scope.createUser = function() {
var User = new user();
User.username = $scope.usernameVar;
User.password = $scope.passwordVar;
User.save();
}
});
Please read this first (Instead of going through the code first):
So when the user clicks on the login button on the login page the createUser function above is run (in my AJS file). Then I create a resource object for the endpoint '/login' and when I call save on that it will run the route for that '/login' endpoint on my server (app.js). Then in my server it will passport.authenticate('login', ... which will run the passport middleware.
Now my question is:
In the passport.use('login'... strategy where the do values for the variables req, username, and password come from in the callback to that strategy. Do I have to explicitly pass the username and password the user enters in the textfield on my front end. Like I have a two way data binding for those two textfields in AJS view. If so how do I pass those username and password values?
Do these two lines in my AJS controller User.username = $scope.usernameVar; and User.password = $scope.passwordVar; attach the usernameVar and passwordVar values to the req object on my server for the route '/login'?
If you have a form with action to post to your path /login, and have input names labeled after your username and password, the submit button will pass the values along to your passport code.
Check out Form in the docs.
The below custom call back for passport.js doesn't seems to work, no mater what i do.
app.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, users, info) {
console.log(users);
if (user === false) {
console.log('Failed!');
} else {
res.redirect('/');
}
})(req, res, next);
});
The same if i change it to like below all works as expected.
app.post("/login"
,passport.authenticate('local',{
successRedirect : "/",
failureRedirect : "/login",
})
);
Also I've noticed when using custom callback even the passport.serializeUser and passport.deserializeUser also not getting invoked by passport.js.
Is this any sort of a bug or am i doing something wrong here ??
My Local-Strategy:
passport.use('local-sigin',new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) { // callback with email and password from our form
console.log('Passport Strategy Sign in:');
// 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({ 'email' : email }, function(err, user) {
// if there are any errors, return the error before anything else
if (err)
return done({status:'ERROR',message:'Something went wrong!'});
// if no user is found, return the message
if (!user)
return done({status:'ERROR',message:'No user found.'}, false);
// if the user is found but the password is wrong
if (!user.validPassword(password))
return done({status:'ERROR',message:'Oops! Wrong password.'}, false);
// all is well, return successful user
return done({status:'OK',message:'Login success.'}, user);
});
}));
I am guessing that by 'doesn't work' you mean to say that the user is never being logged in.
Firstly, your local strategy is named 'local-sigin' however on a POST to '/login' you are invoking the 'local' strategy, which presumably doesn't exist:
passport.use('local', new LocalStrategy({
Change the name of your strategy to be consistent (or vice versa!):
passport.authenticate('local'
Secondly, your 'local' authentication callback has a parameter users (plural) but you are trying to access user (singular) within its body, meaning user is undefined and user === false is false under strict equality:
app.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
// ^^^^
console.log(user);
if (!user) {
console.log('Failed!');
} else {
res.redirect('/');
}
})(req, res, next);
});
And finally, you are never logging the user in when authentication is successful. Creating a session for a user is not automatic, you must call req#login:
Passport exposes a login() function on req (also aliased as logIn()) that can be used to establish a login session.
Let's add that to your authentication callback:
app.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
console.log(user);
if (!user) {
console.log('Failed!');
} else {
req.login(user, function (err) {
if(err) {
console.log(err);
return;
}
res.redirect('/');
});
}
})(req, res, next);
});
Take a look at the Passport docs, they explain in a good amount of detail how these processes work and how to implement them.
this is probably some basic mistake but I am watching tutorial and even though I think I done everything exactly like I should after submitting login form I am redirected to the "failureRedirect" page. When I looked at source code in passport module I something.
After this:
Strategy.prototype.authenticate = function(req, options) {
options = options || {};
var username = lookup(req.body, this._usernameField) || lookup(req.query, this._usernameField);
var password = lookup(req.body, this._passwordField) || lookup(req.query, this._passwordField);
//I added:
console.log("U-> " + username);
console.log("P-> " + password);
console says
U-> null
P-> null
Then after this, rest is not executed.
if (!username || !password) {
return this.fail({ message: options.badRequestMessage || 'Missing credentials' }, 400);
}
I am not sure which parts of code should I post here. Maybe this can help
passport.use(new LocalStrategy(
function(username, password, done){
console.log("passport.use new LocalStrategy"); //never gets executed
//never gets executed
User.getUserByUsername(username, function(err, user){
if (err) throw err;
if(!user) {
console.log("Unknown user");
return done(null, false, {message: "Uknkown User"});
}
User.comparePassword(password, user.password, function(err, isMatch){
if (err) throw err;
if (isMatch) {
return done(null, user);
} else {
console.log("invalid Pass");
return done(null, false, {message: "Invalid Password"});
}
});
});
}));
router.post("/login", passport.authenticate("local", {failureRedirect:"/users/login/err", failureFlash:"invalid username or pass"}), function(req, res){
console.log("Authenticated OK");
req.flash("success", "You are logged in");
res.redirect("/xx");
});
I am not sure about the exact implementation that you are doing. Probably you are overriding the authenticate functionality using the prototype pattern.
However, Authentication using Passportjs is simple. I have done one recently in my side project. Please go through the below link with my own experience on implementing Passportjs
I have a well documented artcile that i wrote on my tech blog. Hope this helps you
// complete code for the exmaple node rest api authentication using passport
var express = require('express');
var passport = require('passport');
var passportHttp = require('passport-http');
var basicStrategy = passportHttp.BasicStrategy; // using the basic authentication
var app = express();
app.get('/',function(req,res){
res.send("There you go");
});
app.use(passport.initialize()); // initialize and use it in express
passport.use(new passportHttp.BasicStrategy(function(username,password,done) {
if(username === password){
done(null,username); //null means no error and return is the username
}
else{
return done(null,'there is no entry for you!'); // null means nothing to say,
//no error. 2nd is the custom statement business rule
}
}));
// this function hits first when there is an API call.
function ensureAuthenticated(req,res,next){
if(req.isAuthenticated()){
next();
// next redirects the user to the next api function waiting to be executed in the express framework
}else{
res.sendStatus(403); //forbidden || unauthorized
}
};
// this means all the API calls that hit via mydomain.com/api/ uses this authentication.
//session is false, because its a HTTP API call.
// setting this helps passport to skip the check if its an API call or a session web call
app.use('/api',passport.authenticate('basic',{session:false}));
// this is served the user once the authentication is a susccess
app.get('/api/data',ensureAuthenticated,function(req,res){
var somevalue = [{name: 'foo'},
{name: 'bar'},
{name: 'baz'}];
res.send(somevalue);
});
app.listen(3250);
console.log('listening to port on ' + 3250);
I'm using the standard passport local strategy (with express.js) for the signup form on my website. When the failureRedirect is invoked, it redirects back to my signup form correctly, but all the values of my form are wiped blank. I get why this is happening, because of the redirect, but ... This is incredibly annoying for the user if they've made a simple mistake like forgetting a checkbox or their username is already taken. (Also, I know the password should not be sent back to the view). Is there a way to persist the users entered values even after the redirect with passport?
//my route
.post('', passport.authenticate('local-signup', {
failureRedirect: '/account/signup', // redirect back to the signup page if there is an error
failureFlash: true // allow flash messages
}), function(req, res) {
...
});
passport code
passport.use('local-signup', new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true // allows us to pass back the entire request to the callback
}, function(req, username, password, done) {
process.nextTick(function() {
if(password != params.password2) {
return done(null, false, req.flash('error', 'Passwords do not match.'));
}
User.findOne({
'username': username
}, function(err, user) {
// if there are any errors, return the error
if (err)
return done(err);
if (user) {
return done(null, false, req.flash('error', 'That username is already taken.'));
} else {
... create a new user ...
}
});
});
}));
function(req, username, password, done) {
What if you wrap passport in your route logic. For example,
app.post('/login', function(req, res, next) {
// Do something here with the username & password, like
// checking if the username is available.
if (!username || !password) {
// Render the login form, and pass in the username and password.
res.render('/login', {username: username, password: password});
} else {
// If all is validated, attempt the login:
passport.authenticate('local-signup', {
failureRedirect: '/account/signup',
failureFlash: true
}), function(req, res) {
...handle response here...
}
}
});
I'm not sure if all of that is syntatically correct, but the idea is to do whatever application-specific validation you have to do before you attempt to authenticate with Passport.