dears am getting a bad time with passportjs,since 4 days i couldn't solve my problem
am having local strategy to login using phone number and pin code, the login get success and it's printing the req.user , but once i try the middleware (isLoggedIn) it's always getting failed and printing req.user undefined
this is my setup for app.js
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var options = {
host: 'localhost',
port: 3306,
user: 'root',
password: 'Ey_HfdefdS+N@rNkhH',
database: 'testMig',
schema: {
tableName: 'app_sessions',
columnNames: {
session_id: 'session_id'
}
}
};
// required for passport
var sessionStore = new MySQLStore(options);
app.use(session({
key: 'session_cookie_name',
secret: 'session_cookie_secret',
store: sessionStore,
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
and this is my passport.js and local strategy
/**
* Created by FaisalAlzahrani on 5/12/17.
*/
// config/passport.js
// load all the things we need
var LocalStrategy = require('passport-local').Strategy;
// load up the user model
var User = require('../models/user');
var models = require('../models');
// expose this function to our app using module.exports
module.exports = function(passport) {
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
console.log("deserializeUser");
models.User.findById(id, function(err, user) {
console.log("inside deserializeUser");
return done(err, user);
});
});
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
console.log("serializeUser ==>"+user.id);
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(_id, function(err, user) {
console.log("deserializeUser ==>"+user);
done(err, user);
});
});
passport.use('local-login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'phone_number',
passwordField : 'pin',
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
models.User.findOne(
{
where : {phoneNumber : req.body.phone_number}
}).then(function (user) {
req.user = user;
// if no user is found, return the message
if (!user)
return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
// all is well, return successful user
req.login(user,function (data) {
console.log(req.user);
console.log("success");
return done(null, user)
});
});
}));
};
and my routes for login and profile is:-
index.get("/profile",isLoggedIn,function(req,res,next) {
res.status(200).send("Dooooooone");
});
index.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
index.post('/login', passport.authenticate('local-login', {
session: true,
successRedirect : '/success', // redirect to the secure profile section
failureRedirect : '/fail', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
function isLoggedIn(req, res, next) {
console.log(req.user);
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the home page
res.redirect('/');
}
so the login get success always but when i try to auth the user to redirect him to profile (isLoggedIn) always get failed and req.user is undefined ???
what i noticed also that (deserializeUser) never get called
any suggestions :(
via Faisal
No comments:
Post a Comment