Passport-facebook access req object from within callback function - node.js

On the callback from Facebook for nodejs passport authentication, how do you get the req object within the callback?
passport.use(new FacebookStrategy({
clientID: 123456789,
clientSecret: 'SECRET',
callbackURL: "http://example.com/login/facebook/callback"
},
function(accessToken, refreshToken, profile, done){
// Is there any way to get the req object in here?
}
));

Setting the passReqToCallback option, as so:
passport.use(new LocalStrategy({ passReqToCallback: true },
function(req, username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!user.verifyPassword(password)) {
req.flash('error', 'Your password is too long');
req.flash('error', 'Also, it is too short!!!');
return done(null, false);
}
return done(null, user);
});
}
));
req becomes the first argument to the verify callback
As per https://github.com/jaredhanson/passport/issues/39

I am answering it too late, but i think my solution is better and more conventional.
In the official documentation here. There is a section "Association in Verify Callback", in which it is mentioned that if we set the strategy's passReqToCallback option to true, this enables req and it will be passed as the first argument to the verify callback.
So my FacebookStrategy now looks like:
var User = require('../models/UserModel.js');
var FacebookStrategy = require('passport-facebook').Strategy;
exports.facebookStrategy = new FacebookStrategy({
clientID: 'REPLACE_IT_WITH_CLIENT_ID',
clientSecret: 'REPLACE_IT_WITH_CLIENT_SECRET',
callbackURL: 'http://localhost:3000/auth/facebook/callback',
passReqToCallback: true
},function(req,accessToken,refreshToken,profile,done){
User.findOne({
'facebook.id' : profile.id
},function(err,user){
if(err){
done(err);
}
if(user){
req.login(user,function(err){
if(err){
return next(err);
}
return done(null,user);
});
}else{
var newUser = new User();
newUser.facebook.id = profile.id;
newUser.facebook.name = profile.displayName;
newUser.facebook.token = profile.token;
newUser.save(function(err){
if(err){
throw(err);
}
req.login(newUser,function(err){
if(err){
return next(err);
}
return done(null,newUser);
});
});
}
});
}
);
In my code sample i have added some logic to save user info in DB and saving user details in session. I thought it might be helpful to people.
req.user gives the information of user stored in passport session.

Related

how to return an error after login failed in passport oauth

I have a node js server, as a login strategy I use passport with google OAuth.
this is my code
passport.use(new GoogleStrategy({
clientID: ...,
clientSecret: ...,
callbackURL: "http://localhost:3000/users/googleAuth/callback"
},
function(accessToken, refreshToken, profile, done) {
process.nextTick(function(){
UserDB.findOne({'google.id': profile.id}, function(err, user){
if(err)
return done(err);
if(user)
if(user.active)
return done(null, user);
else
return done("user was disabled");
else {
var newUser = new UserDB();
newUser.admin = false;
newUser.email = profile.emails[0].value;
newUser.google.id = profile.id;
newUser.google.token = accessToken;
newUser.google.name = profile.displayName;
newUser.google.email = profile.emails[0].value;
newUser.save(function(err){
if(err)
console.log(err);
else
return done(null, newUser);
});
console.log(profile);
}
});
});
}
));
and this is the callback
router.get('/googleAuth/callback',
passport.authenticate('google', {successRedirect:'/'}), function (req,res) {
if(!req.isAuthenticated())
res.redirect('/');
});
the user have an active property ,if it set to false the user can't log in (you can see this in the code) , when this happen I want to redirect the user to the main page with an error message, I tried to use res.redirect('/'), however it didn't work ,the user is just stack in the screen where you pick a google user ,I also tried to add failureRedirect property but with the same results.
How can I redirect the user? is it also possible to send a message?

How is the verify callback used in the API?

While going through the API documentation of passport-local, it is mentioned that the strategy requires a verify callback.
Below is the example that is provided.
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); }
if (!user.verifyPassword(password)) { return done(null, false); }
return done(null, user);
});
}
));
Here, .verifyPassword(password) is used as a callback?
Link for API is this.
And If I want to give email instead of username then how should I approach this?
1) user.verifyPassword(password) - synchronous function.
2) By default, LocalStrategy expects to find credentials in parameters named
username and password. If your site prefers to name these fields differently,
options are available to change the defaults:
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'passwd'
},
function(username, password, done) {
// ...
}
));

How can i switch to another user account from an admin account

I have a user table in which i have an Admin account and some other normal users accounts.
I want to do all activities which for a particular user. It should act like that activity done by same user.
Can somebody tell me how can i switch to another account from Admin account
without login to that account.
Currently i use passport authentication.(passport-local)
Here is my code
app.get('/secure/group/login', function(req,res,next) {
passport.authenticate('local',function(err,user,info) {
console.log("error is "+err);
req.logIn('tessAccount',function(err) {
console.log("Weer" +err);
});
console.log("dd");
})(req,res,next);
});
});
and passport code
var LocalStrategy = require('passport-local').Strategy;
module.exports = function(passport) {
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.token);
});
passport.use(new BearerStrategy(
function(token, done) {
user.tokenExist(token, function(err, user) {
if (err) {
return done(err);
}
else {
return done(null, user, { scope: 'all' });
}
});
}
));
// used to deserialize the user
passport.deserializeUser(function(accessToken, done) {
user.getUserByAccessToken(accessToken, function(err, dbUser) {
if (err) {
done(err);
} else {
done(null, dbUser[0]);
}
});
});
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'
passport.use('local-signup', 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) {
user.emailExists(email, function(err, exists) {
if (err)
return done(err);
else if (exists) {
return done(null, false, {
message: req.flash('loginMessage')
});
} else {
req.userDetails.status = 0;
req.userDetails.token = md5.digest_s(req.userDetails.email + new Date());
req.userDetails.userImage = config.user.image;
user.register(req.userDetails, function(err, newUser) {
if (err)
return done(err);
else {
/*Get user Shared article if exist start*/
getSharedArticlesOfnewlyuserIfExist(email, newUser.insertId);
/*Get user Shared article if exist end*/
req.userDetails.id = newUser.insertId;
return done(err, req.userDetails);
}
});
}
});
}));
passport.use('local-login', 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
// 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.matchPassword({
email: email,
password: password
}, function(err, newUser) {
// if there are any errors, return the error before anything else
if (err)
return done(err);
// if no user is found, return the message
if (newUser.length > 0) {
var user = {
id: newUser[0].user_id,
email: newUser[0].email_id,
token: newUser[0].user_access_token
};
return done(null, user);
} else {
return done(null, false, {
message: 'Incorrect username or password.'
}); // req.flash is the way to set flashdata using connect-flash
}
});
}));
User.findOne({ username: 'Myusername' }, function(err, user) {
req.logIn(user, function(err){});
});
This worked for me to log into an account without using password, it switches from my admin account to an user account.
Actually I'm using passport.js and mongoose

How to differentiate Login from Sign up when using PassportJS for Facebook

I am trying to set up goals on Google Analytics to track Sign Ups, so I set up a 'thank you ' page as my url goal. It works well when my users sign up with their email address but not when they use facebook to sign up/login. When they login, they are redirected to the thank you page as there is only one url callback when setting up Facebook using Passport JS and Node.
Here is my code:
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(id, done) {
UserActivity.findOne(id,'uid ref', function (err, user) {
done(err, user);
});
});
passport.use(new FacebookStrategy({
clientID: 'XXXXXXXXXXXX',
clientSecret: 'XXXXXXXXXXXXXXXX',
callbackURL: "https://www.xxxxxxx.com/auth/facebook/callback"
},
function(accessToken, refreshToken, profile, done) {
//console.log(profile);
User.findOne({ uid: profile.id }, function(err, uInfo) {
if(err) console.log('Error: '+err);
else{
//User exists: we are done
if(uInfo){
done(err, uInfo);
}
else{
//User doesn't exist: we create a new one
var newUser = new User ({
uid: profile.id,
email:profile.emails[0].value,
ref: 'Facebook'
});
// Saving it to the database.
newUser.save(function (err,uInfo) {
if (err) console.log ('Error on save!');
done(err, uInfo);
});
}
}
})
}
));
app.get('/auth/facebook', passport.authenticate('facebook',{ scope: 'email' }));
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { successRedirect: '/thankyou',
failureRedirect: '/login' }));
If the user exists, I would like to redirect to their dashboard ('/dashboard) and if they are new users, I need to redirect them to /thankyou.
Any idea how to achieve this?
Thanks a lot!
Nevermind, found the answer. Here is the updated code below. Pay attention to the use of passReqToCallback and req.session.newu
passport.use(new FacebookStrategy(
{
clientID: 'XXX',
clientSecret: 'XXX',
callbackURL: "https://www.XXX.co/auth/facebook/callback",
passReqToCallback: true
},
function(req, accessToken, refreshToken, profile, done) {
//console.log(profile);
User.findOne({ uid: profile.id }, function(err, uInfo) {
if(err) console.log('Error: '+err);
else{
if(uInfo){
done(err, uInfo);
}
else{
var newUser = new User ({
uid: profile.id,
email:profile.emails[0].value,
ref: 'Facebook'
});
// Saving it to the database.
newUser.save(function (err,uInfo) {
if (err) console.log ('Error on save!');
req.session.newu=true;
done(err, uInfo);
});
}
}
})
}
));
app.get('/auth/facebook', passport.authenticate('facebook',{ scope: 'email' }));
app.get('/auth/facebook/callback',function(req, res, next) {
passport.authenticate('facebook', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
var redLink = '/dashboard';
if(req.session.newu)redLink = '/dashboard?newu'
return res.redirect(redLink);
});
})(req, res, next);
});
An existing user will be redirected to /dashboard and a new user will be redirected to /dashboard?newu
Google Analytics doesn't need 2 different urls, it just needs a query string. When I set up the url goal, I selected url start with /dashboard?newu.
Hope this helps
The question is a bit old but it might still help someone like me. The OP's answer works but it means you have to take care of log-in user and session, etc. In case you still want to leave those work to PassportJS, use req.session.returnTo in strategy's callback with successReturnToOrRedirect option in passport.authenticate() would work.

Get request object in Passport strategy callback

So here is my configuration for passport-facebook strategy:
passport.use(new FacebookStrategy({
clientID: ".....",
clientSecret: ".....",
callbackURL: "http://localhost:1337/register/facebook/callback",
},
facebookVerificationHandler
));
And here is facebookVerificationHandler:
var facebookVerificationHandler = function (accessToken, refreshToken, profile, done) {
process.nextTick(function () {
.......
});
};
Is there a way to access to the request object in facebookVerificationHandler?
Users are registered to my site with a LocalStrategy but then they will be able to add their social accounts and associate those account with their local accounts. When the callback above is called, the user who is currently logged in is already available in req.user so I need to access req to associate the user with the facebook account.
Is this the correct way to implement it or should I consider another way of doing it?
Thanks.
There's a passReqToCallback option, see the bottom of this page for details: http://passportjs.org/guide/authorize/
Try this.
exports.facebookStrategy = new FacebookStrategy({
clientID: '.....',
clientSecret: '...',
callbackURL: 'http://localhost:3000/auth/facebook/callback',
passReqToCallback: true
},function(req,accessToken,refreshToken,profile,done){
User.findOne({
'facebook.id' : profile.id
},function(err,user){
if(err){
done(err);
}
if(user){
req.login(user,function(err){
if(err){
return next(err);
}
return done(null,user);
});
}else{
var newUser = new User();
newUser.facebook.id = profile.id;
newUser.facebook.name = profile.displayName;
newUser.facebook.token = profile.token;
newUser.save(function(err){
if(err){
throw(err);
}
req.login(newUser,function(err){
if(err){
return next(err);
}
return done(null,newUser);
});
});
}
});
}
);
User is a mongoose model, i save the user in DB.
For this reason instead of setting up the strategy when the application starts I usually setup the strategy when there is a request. for instance:
app.get(
'/facebook/login'
,passport_setup_strategy()
,passport.authenticate()
,redirect_home()
);
var isStrategySetup = false;
var passport_setup_strategy = function(){
return function(req, res, next){
if(!isStrategySetup){
passport.use(new FacebookStrategy({
clientID: ".....",
clientSecret: ".....",
callbackURL: "http://localhost:1337/register/facebook/callback",
},
function (accessToken, refreshToken, profile, done) {
process.nextTick(function () {
// here you can access 'req'
.......
});
}
));
isStrategySetup = true;
}
next();
};
}
Using this you will have access to the request in your verification handler.

Resources