2012-04-30 5 views
1

서버에 게시 할 때 auth 함수에 제공 한 정보에 관계없이 true를 반환합니다. 나의 직감은 내가 동기로 무언가를하려고 시도한다는 것인데, 그것은 본질적으로 비동기이지만, 그것을 고치는 방법을 모른다.이 coffeescript 코드가 항상 true를 반환하는 이유는 무엇입니까?

auth = (username, api_key, device) -> 
    hashed_key = hash.sha256(username + api_key + device, salt) 
    winston.debug('Checking auth for ' + username) 
    redis_client.get hashed_key, (err, data) -> 
    if data == username 
     true 

# Main Handler for posting data for a device. 
server.post "/:customer/:site/:device", create = (req, res, next) -> 
    message = JSON.parse(req.body) 
    winston.info(server.name + ': Recieved event from ' + req.params.device) 
    authenticated = auth(message.username, message.api_key, message.device) 
    winston.debug('****' + authenticated) 
    if authenticated == true 
     winston.debug('Auth passed, got a valid user/device/api combination: ' + message.username) 
     redis_client.publish('device_events', req.body) 
     return next() 
    else 
     winston.debug('Auth failed, cant find device ' + message.device + ' for ' + message.username) 
     return next(restify.NotAuthorizedError) 
+0

auth에 false를 추가하면 그 동작이 변경됩니까? – Menztrual

+0

아니요 - 아무런 차이가 없으므로 auth가 함수 선언으로 true이지만 실행되지 않거나 시간 내에 완료되지 않는다고 생각하게 만듭니다 ...... –

+1

직감이 정확합니다. *'redis_client.get'가 실행되기 전에'auth' 함수가 * 리턴합니다. 그래서 콜백이 필요합니다. 더 이상 같은 범위에 있지 않기 때문에 콜백에서 돌아올 수 없습니다. 비슷한 상황에 대한 [내 대답] (http://stackoverflow.com/questions/9310855/get-and-get-value/9310916#9310916) 및 [이 답변] (http://stackoverflow.com/ 왜이 패러다임을 사용하는지에 대한 설명을 위해 질문/9362823/why-is-a-function-and-a-callback-in-non-blocking-in-node-js/9363071 # 9363071) –

답변

1

무언가가 비동기 적이라는 것을 알고 있다면 (콜백 함수로 이후에 할 일을 전달해야합니다. 나는 서버의 포스트 기능이 어떻게 작동하는지 모르지만, Node HTTP's request과 같은 경우 다음과 같이해야합니다.

+0

답장을 보내 주셔서 감사합니다. 나는 커피/노드 초보자 (복원 사용)이므로 이해할 수 없습니다. 나는 파이썬 녀석이다. 그 실행의 순서가 더 이해가 안 돼 ..... –

+0

아. 당신이 restify를 사용한다고하면 도움이됩니다. auth가 동 기적으로 실행되도록하려면 node-sync를 사용해야 할 수 있습니다. 함수를 작은 덩어리로 분해하여 next()로 인증을 전달할 수 있고, 다시 로깅을 수행하고 이벤트를 게시하는 등의 작업을 수행 할 수도 있습니다. –

관련 문제