3

私は、socket.ioを使用して特定のタスクを実行することを(認証に加えて)ユーザーに許可する最善の方法を決定しようとしています。

エクスプレスでは、これはかなり簡単です。最初に、データベースにクエリを実行してレコードが存在するかどうかを判断するログイン/パスワードフォームがあり、レコードが存在する場合は、ユーザーをreq.sessionデータにアタッチします。

exports.session = function(req, res){
    User.authenticate(req.body.username, req.body.password, function(err, user){
        if (user){
            req.session.user = user;
            res.redirect('/');
        } else {
            console.log("authentication failed");
            res.render('user/login');
        }
    });
};

これができたら、ミドルウェアを使用して特定のリクエストを承認できます。例えば、

app.put('/api/users/:userId', m.requiresLogin, m.isUser, api.putUser);

//Middleware
exports.isUser = function(req, res, next){
  if (req.session.user._id == req.user._id){
    next();
  } else {
    res.send(403);
  }
};

しかし、socket.ioを使用してこれを行う方法について少し混乱しています。ユーザーのプロファイルJSONオブジェクトを指定して、データベース内のユーザーのプロファイルを変更するイベントリスナーがあるとします。

    socket.on('updateProfile', function(data){
    // query the database for data.user._id, and update it with the data attribute
    // but only do this if the data.user._id is equal to the user trying to do this. 
    });

これを達成する方法として何か提案はありますか?セッション情報を通じて行うことはできますか?

4

2 に答える 2

-2

こちらのドキュメントを参照してください。

https://socket.io/docs/migrating-from-0-9/#authentication-differences

io.set('authorization', function (handshakeData, callback) {
// make sure the handshake data looks good
callback(null, true); // error first, 'authorized' boolean second 

});

于 2012-07-28T15:21:29.140 に答える