2012-07-28 7 views
3

socket.io를 사용하여 특정 작업을 수행하도록 사용자를 인증하는 것 이외에 인증하는 방법을 결정하려고합니다.with 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

다음과 같이 socket.io의 authorization 함수에 연결할 수 있습니다 : 당신은 Express를 사용하는 것처럼

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는 사용자의 출처에 대한 나쁜 지표입니다. 간단한 예는 많은 사용자가 동일한 게이트웨이 + IP를 사용하여 회사에 들어가는 회사 설정입니다. 홈 라우터와 동일한 문제입니다. NodeJS + express + Backbone.JS + socket.io에 대한 프레임 워크를 구현 중입니다. 쿠키 자체에 토큰을 사용하고 있으므로 express를 통해 작성하고 나중에 socket.io를 통해 읽을 수 있습니다. 영감이 필요하면 여기에서 내 프로젝트를 확인하십시오. http://github.com/romansky/circuits – Roman

+0

이것은 socket.io 버전 1.0 이상으로 변경되었습니다. 위의 코드를 새로운 패러다임으로 마이그레이션하는 방법에 대한 설명은 다음에서 제공됩니다. http://socket.io/docs/migrating-from-0-9/#authentication-differences – Nathan

0

이 나타납니다.
Passport (https://github.com/jaredhanson/passport)라고하는 Express 미들웨어를 적극 권장합니다.

Passport를 사용하면 Google, Yahoo, Facebook을 통한 OpenID, Twitter, Facebook을 통한 OAuth 또는 현지 전략 (예 : 이메일 등록)과 같은 사용자 인증을위한 전략을 다양하게 구현할 수 있습니다.

마지막으로 정확한 질문에 대답하십시오 : passport.socketio라는 프로젝트는 위의 인증 전략과 잘 어울리 며 Express 세션을 설정하면 잘 작동합니다. (https://github.com/jfromaniello/passport.socketio)