2012-07-28 109 views
3

我試圖確定如何最好授權(除了驗證)用戶使用socket.io執行特定的任務。授權與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. 
    }); 

作爲如何實現這一目標的任何建議?它可以通過會話信息完成嗎?

回答

0

您可以掛接到authorization功能socket.io如下:

var io = require('socket.io').listen(80); 

io.configure(function(){ 
    io.set('authorization', function (handshakeData, callback) { 
    // findDatabyip is an async example function 
    findDatabyIP(handshakeData.address.address, function (err, data) { 
     if (err) return callback(err); 

     if (data.authorized) { 
     handshakeData.foo = 'bar'; 
     for(var prop in data) handshakeData[prop] = data[prop]; 
     callback(null, true); 
     } else { 
     callback(null, false); 
     } 
    }) 
    }); 
}); 
+0

IP是用戶來源的BAD指標。一個簡單的例子是企業設置,許多用戶使用相同的網關+ IP上網。與家庭路由器相同。 我正在爲NodeJS + express + Backbone.JS + socket.io實現一個框架,我在這裏使用了我自己放置在cookie上的令牌,所以你可以通過express寫入,並在稍後通過socket.io讀取。 如果您需要靈感,請隨時在這裏查看我的項目http://github.com/romansky/circuits – Roman 2014-05-03 13:54:49

+0

請注意,隨着socket.io版本1.0和更高版本的改變,這已經發生了變化。關於如何將上面的代碼遷移到新的範例的解釋如下:http://socket.io/docs/migrating-from-0-9/#authentication-differences – Nathan 2015-07-28 14:11:35

0

看來好像你使用快遞。
我強烈推薦Express Passport中間件(https://github.com/jaredhanson/passport)。

使用Passport,您可以實現任意數量的策略來驗證用戶(例如,通過Google,Yahoo,Facebook的OpenID;通過Twitter,Facebook的OAuth或本地策略(例如電子郵件註冊))。

最後,回答您的確切問題:一個名爲passport.socketio的項目令人驚訝,因爲它與上面的身份驗證策略配合良好,如果您設置了Express會話,則它也可以很好地發揮作用。 (https://github.com/jfromaniello/passport.socketio