What could be causing deserializeUser() to not get called? - passport.js

I'm using passport with nodejs and I'm having a strange problem,
the passport.deserializeUser(function.. never gets called.
Strange thing is that serializeUser(function.. get's called just fine..
And yet stranger thing is that it was working just fine a couple days ago, but now it isn't. I can't think of anything that I changed in my system that would cause this.
var express = require('express');
var app = express();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
app.configure(function(){
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static('public'));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ secret: 'keyboard cat' }));
app.use(app.router);
});
passport.use(new LocalStrategy(function(username, password, done){
return done(null, 'Always Authenticated User');
}));
passport.serializeUser(function(user, done) {
console.log(' serialize OK! ');
done(null, user);
});
passport.deserializeUser(function(id, done) {
console.log('deserialize Never gets called');
done(null,id);
});
app.post('/login'
,passport.authenticate('local'
,{ successRedirect: '/success'
,failureRedirect: '/failure'
,failureFlash: false
} ) );
app.get('/', function(req, res){
// very simple form
res.send("<form id='LoginLocal' action='/login' method='post'><fieldset><legend>Login with username/password</legend><label for='username'> Username: <input type='text' name='username' placeholder='username'><label for='password'> Password: <input type='password' name='password' placeholder='password'><input type='submit' value='Login'></fieldset></form>");
});
app.listen(80);

Moving the app.use(passport.… after the app.use(express.… solved it.
app.configure(function(){
app.use(express.static('public'));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ secret: 'keyboard cat' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
});

As of express v4.x the same answer still applies that passport.(...) must be called only after express.session like so:
app.use(express.session({ secret: 'keyboard cat' }));
app.use(passport.initialize());
app.use(passport.session());
You no longer call them inside app.configure() as it has been deprecated as of express v4.x

Related

Modify Nodejs-Express-Passport server to upload image automatically

I am using a nodejs-express-passport solution for authentication with facebook. My goal is to automatically upload an image from a static directory the moment that a user is successfully logged in.
If my image is simply animal.png located at /images how would I modify
the following node-express server code to accomplish this?
var express = require('express');
var passport = require('passport');
var Strategy = require('passport-facebook').Strategy;
passport.use(new Strategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: 'http://localhost:3000/login/facebook/return'
},
function(accessToken, refreshToken, profile, cb) {
return cb(null, profile);
}));
passport.serializeUser(function(user, cb) {
cb(null, user);
});
passport.deserializeUser(function(obj, cb) {
cb(null, obj);
});
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
app.get('/',
function(req, res) {
res.render('home', { user: req.user });
});
app.get('/login',
function(req, res){
res.render('login');
});
app.get('/login/facebook',
passport.authenticate('facebook','user_photos'));
app.get('/login/facebook/return',
passport.authenticate('facebook', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});
app.get('/profile',
require('connect-ensure-login').ensureLoggedIn(),
function(req, res){
res.render('profile', { user: req.user });
});
app.listen(3000);
For res.render('profile', {user: req.user, image: 'my image string location'})
then with your html just pass in {{image}} to wherever you are trying to src the image from.
I am not super familiar with ejs templating but it'd look something like this:
<img src={{image}} alt="MyAnimal.png" style="width:304px;height:228px;">
Or did you want it to just flash on the screen? If that's the case I think you can do something like that with the flash module.
Edit:
I'll move this up here as this was a question for posting desktop data to facebook and not just popping up a picture from the server.
Passport does authentication handshakes to allow people access to your website via login, it does not however open up all the api's to Twitter/Facebook/Google, you'll need to either make them yourself, or use ones that are pre built like this Facebook API.
https://www.npmjs.com/package/fb

getting authenticated user info from passportjs and express

I have an express application that uses passport for OAuth. I have it working successfully with Google and Facebook. My problem is that I can get req.user on controller functions where the routes are configured like this:
router.post('/', auth.isAuthenticated(), controller.create);
but when I try to access the user info from a controller function that doesn't require authentication, req.user is undefined even though the user is logged in. What am I doing wrong here?
and here is how express and passport are configured:
module.exports = function(app) {
var env = app.get('env');
app.set('views', config.root + '/server/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(compression());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(cookieParser());
// Persist sessions with mongoStore
// We need to enable sessions for passport twitter because its an oauth 1.0 strategy
app.use(session({
secret: config.secrets.session,
resave: true,
saveUninitialized: true,
store: new mongoStore({ mongoose_connection: mongoose.connection })
}));
app.use(passport.initialize());
app.use(passport.session());
.
.
.

Undefined method flash in the view of node.js

Problem in accessing flash messages on view in node.js
In my Controller
this.req.flash('info','successfully submited');
this.redirect("/home");
In my home view I am not able to get flash messages as
req.flash('info');
EDIT
In controller
self.req.flash('message','hello');
In view
<%= req.flash('message) %>
In server.js
app.configure(function (){
app.use(express.cookieParser());
app.use(express.session({ secret:'yoursecret',cookie: { maxAge: 24 * 60 * 60 * 1000 }}));
app.use(passport.initialize());
app.use(locomotive.session());
app.use(flash());
app.use(passport.session());
app.use(app.router);
app.dynamicHelpers({ messages: require('express-messages') });
});
I have the locomotive framework.
Please see tempdata example https://github.com/MKxDev/TempData
var tempData = require('tempdata');
var app = express();
app.configure(function() {
...
// This has to appear BEFORE the router
app.use(express.cookieParser());
app.use(express.session({ secret: 'your_super_secret_session_key' })); // please change this!
app.use(tempData);
...
});
...
// Routes
app.get('/', function(req, res) {
// Retrieve tempData value here. It won't exist unless the request
// was redirected
var tempVal = JSON.stringify(req.tempData.get('test_val'));
res.render('index', { title: 'Express', temp: tempVal });
});
app.post('/', function(req, res) {
// Set tempData value here
req.tempData.set('test_val', { x: 'Hello World!' });
res.redirect('/');
});
Move your app.use(flash()) higher in the order...see below. Flash needs to be initialized before passport so that flash is recognized and available to passport.
app.configure(function (){
app.use(express.cookieParser());
app.use(express.session({ secret:'yoursecret',cookie: { maxAge: 24 * 60 * 60 * 1000 }}));
app.use(flash()); // moved this up a few lines
app.use(passport.initialize());
app.use(locomotive.session());
app.use(passport.session());
app.use(app.router);
app.dynamicHelpers({ messages: require('express-messages') });
});

Node - Express - Session not working?

So I'm stuck as to why this isn't working. Whenever I use the cookie for maxAge, it just doesn't allow me to login. It redirects me to /, so the callback is working but the session data is lost for some reason. Can anybody assist me?
Thanks in advance.
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var login = require('./routes/login');
var register = require('./routes/register');
var http = require('http');
var path = require('path');
var MongoClient = require('mongodb');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var app = express();
// all environments
app.set('port', process.env.PORT || 3001);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.cookieParser());
app.use(express.session({
secret: '1234567890QWERT',
cookie: {maxAge: 30}
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
var dbc;
var User;
MongoClient.connect('mongodb://127.0.0.1:27017/redacted', function(err, db) {
dbc = db;
User = dbc.collection('users');
});
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ email: username }, function(err, user) {
if (password == user.password) {
console.log("Login success!");
// Allows us to keep a log of when the user logs in in:
// user['loggedin'][]
// db.users.update({email: ""}, { $push : {loggedin: new Date()} } )
if(!err) done(null, user );
}
else done(err, null)
});
}
));
passport.serializeUser(function(user, done) {
done(null, {
id: user["_id"],
name: user["name"],
email: user["email"],
registered: user["registered"],
password: user["password"]
});
});
passport.deserializeUser(function(id, done) {
console.log(id);
User.find({_id: id._id}, function(err, user) {
done(err, user);
});
});
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
// User stuff
app.get('/login', login.get);
app.post('/login',
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login?m=fail'
})
);
app.get('/register', register.get);
app.post('/register', register.post);
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Your session cookie is set to last 30ms.
Per Express documentation, maxAge sets the expiration date of the cookie in ms.
Change cookie: {maxAge: 30} to something like cookie: {maxAge: 24*60*60*1000} for a longer-lasting session cookie.

express cookie return undefined

I'm trying to set cookie on express.js but it return undefined.
I've searched many web pages and put express.cookieParser() above app.use(app.router)
but it still can't return the right value.
app.js
app.configure(function(){
var RedisStore = require('connect-redis')(express);
app.use(express.logger());
app.set('view options', { layout: false });
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser({uploadDir: './uploads/tmp'}));
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: "william", store: new RedisStore }));
//Initialize Passport! Also use passport.session() middleware, to support
//persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
//app.router should be after passportjs
app.use(app.router);
app.use(express.compiler({ src: __dirname + '/public', enable: ['less']}));
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/', function(req, res) {
res.cookie('cart', 'test', {maxAge: 900000, httpOnly: true})
});
app.get('/test', function(req, res) {
res.send('testcookie: ' + req.cookies.cart);
});
the result:
testcookie: undefined
Cookies are set in HTTP Headers. res.cookie() just sets the header for your HTTP result, but doesn't actually send any HTTP. If your code was syntactically correct and it ran, it would actually just sit and not return anything. I also fixed some syntax bugs in your code in this app.get():
app.get('/', function(req, res) {
res.cookie('cart', 'test', {maxAge: 900000, httpOnly: true});
res.send('Check your cookies. One should be in there now');
});
You need to send something out, or at least call res.end(), after setting the cookie. Otherwise all res.cookie() does is add some headers to a list of headers that will be sent out later.
Set cookie name to value, where which may be a string or object converted to JSON. The path option defaults to "/".
res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true });
Here is the Link for more detail
http://expressjs.com/api.html#res.cookie

Resources