Express(3.x)とNowJS(主にSocket.ioのラッパー)を組み合わせて、最初にログインする必要があるリアルタイムアプリケーションを作成しようとしています。Nodeは初めてですが、各パッケージが個別にどのように機能するかについてのかなり良いハンドル。ただし、NowJSからExpress Session情報にアクセスすることは、私に適しています。
問題は、XHR-Polling(Herokuをホスティングプラットフォームとして使用)を使用せざるを得ないため、Socket.io認証方式でCookie情報に簡単にアクセスできないことです。以下のauthFunctionのコードでは、「data.headers.cookie」は未定義です。回りくどい方法で(Now.jsコード内で)、これはnowjs.on( "connect"、...)コールバックで "this.user.cookie"を空(ただし未定義ではない)のままにします。その結果、セッション情報を取得できなくなります。
読んでみると、CookieはWebSocketを使用している場合にのみ利用できるようです。Cookieがないと、サーバーに対してどのユーザーが呼び出しを行っているのか、ランダムな識別子が生成される以外にわかりません。
誰かがこれにアプローチする方法を提案できますか?Now.jsサーバーへの接続を確立するときに、クライアント側から手動でCookieを送信する必要がありますか?
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.engine('html', consolidate.swig);
app.set('view engine', 'html');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: "secrethere" , store: sessionStore}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler({dumpExceptions: true, showStack: true}));
});
//Map the routes
var routes = require('./routes/routes')(db);
app.get[...] //routes defined here
var server = http.createServer(app, {cookieKey: 'connect.sid'});
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
var parseCookie = require('express/node_modules/connect').utils.parseCookie;
var authFunction = function (data, accept) {
// check if there's a cookie header
if (data.headers.cookie) {
// if there is, parse the cookie
data.cookie = parseCookie(data.headers.cookie);
// note that you will need to use the same key to grad the
// session id, as you specified in the Express setup.
data.sessionID = data.cookie['connect.sid'];
} else {
// if there isn't, turn down the connection with a message
// and leave the function.
return accept('No cookie transmitted.', false);
}
// accept the incoming connection
accept(null, true);
};
var everyone = nowjs.initialize(server, {socketio: {transports: ['xhr-polling', 'jsonp-polling'], authorization: authFunction}});
nowjs.on('connect', function (socket) {
//TODO - This will need to be based on the URL that is being visited, or
//similar to establish that users are viewing the same thing
var sid = unescape(this.user.cookie["connect.sid"]); //# you DO have to unescape the session id!
sessionStore.get(sid, function(err, sess){
console.log("That group who joined? his userId is " + sess.userId)
});
var newRoom = "group";//this.user.session;//.groupName;
var newGroup = nowjs.getGroup(newRoom);
this.now.serverRoom = newRoom;
newGroup.addUser(this.user.clientId);
});
編集:もちろん、ここでのトップアンサーのような単純なソリューションを好みます:Now.jsでのセッションサポート、しかしそれは(おそらく)同じ理由で私には機能しません-私の「クッキー」は空であり、「接続」が含まれていません.sid"キー。