I have been experimenting with Ember.js and Node.js, and have run into a problem. I have protected my API routes on the server with the standard Express.session system, but I have run into a problem when those APIs are serving an Ember.js application. Since the Ember app does not have the ability to store values in req.session, my app doesn't function. How should I do my authentication so that I still can session-protect my API? Here is some of my current server login code:
a "check login" function:
var checkLogin = function(req, res, callback) {
if (req.session.user) {
callback();
} else {
res.send({error: "AuthRequired"});
}
};
Error when Ember makes a request:
TypeError: Cannot read property 'user' of undefined
Middleware setup:
app.configure(function () {
app.use(express.bodyParser());
app.use(express.static(__dirname + '/static/'));
app.use(express.cookieParser(<SECRET>));
app.use(express.session());
//to not care about invalid JSON requests
app.use(function(err, req, res, next) {
if (err.message == 'invalid json') {
next()
} else {
next(err)
}
});
});
Have you tried Passport?
This middle-ware adds user to your session, I recommend trying its passport-local provider.
The guide on the website may not be fully working code, you better refer to the example folder on git repo.
UPDATE:
It may be the sequence of config that is not okay.
Here's my config for Locomotive server (replace this with app), try it out.
this.use(poweredBy(null));
this.use(express.favicon());
this.use(express.logger('dev'));
this.use(express.compress());
this.use(express.cookieParser());
this.use(express.static(__dirname + '/../../public'), { maxAge: 60*10*1000 });
this.use(express.bodyParser());
this.use(express.methodOverride());
this.use(express.session({ secret: '<SECRET>' }));
// Initialize Passport! Also use passport.session() middleware, to support
// persistent login sessions (recommended).
this.use(flash());
this.use(passport.initialize());
this.use(passport.session());
this.use(this.router);