2014-12-24 4 views
0

사용자가 생성되었을 때 사용자 정보를 저장하려하지만이 js 코드를 사용하면 방금 생성 한 사용자의 최초 등록 된 사용자 데이터가 사용됩니다.사용자 데이터를 Firebase에 저장하면 잘못된 사용자가 저장됩니다.

var ref = new Firebase("https://***.firebaseio.com/"); 

$('.btn').click(function(e) { 
    var isNewUser = true; 
    e.preventDefault() 
    var mail = $('#inputEmail').val(); 
    var pass = $('#inputPassword').val(); 
    ref.createUser({ 
     email : mail, 
     password : pass 
    }, function(error) { 
     if (error === null) { 
      console.log("User created successfully"); 
     } else { 
      console.log("Error creating user:", error); 
     } 
     ref.onAuth(function(authData) { 
      if (authData && isNewUser) { 
      ref.child("users").child(authData.uid).set(authData); 
      } 
     }); 
    }); 
    return false; //Extra insurance 
}); 

답변

4

코드는 새로운 사용자를 만들고 있지만 사용자는 자동으로 로그온하지 않습니다. Firebase documentation on creating user accounts 인용 :.에 그 새 계정을 로그인 할 것이다 계정 만들기

을 따라서 onAuth 이벤트 것이다 새 계정이 생성되지 화재,하지만 사용자가 로그인 한 번 (또는 로그 아웃).

Firebase JavaScript 라이브러리 버전 2.0.5 이전에는 새로 작성한 사용자를 프로그래밍 방식으로 액세스하여 authData에 액세스해야했습니다. 귀하의 코드는 그렇게하지 않습니다.

당신의 사용자를 기록하고 콜백에서 사용자 데이터를 설정하여 문제를 해결할 수 있습니다

ref.createUser({ 
    email : mail, 
    password : pass 
}, function(error) { 
    if (error === null) { 
     ref.authWithPassword({ email: mail, password: pass }, function(error, authData) { 
      if (authData) { 
       ref.child("users").child(authData.uid).set(authData); 
      } 
      ref.unauth(); 
     }); 
    } else { 
     console.log("Error creating user:", error); 
    } 

});

version 2.0.5부터 authData도 두 번째 인수로 createUser 콜백 함수에 전달됩니다. 그래서 당신은 또한 단지 수행 할 수 있습니다

ref.createUser({ 
    email : mail, 
    password : pass 
}, function(error, authData) { 
    if (error === null) { 
     console.log("User created successfully"); 
     if (authData) { 
     ref.child("users").child(authData.uid).set(authData); 
     } 
    } else { 
     console.log("Error creating user:", error); 
    } 
}); 

을 이상하게도를 테스트하는 동안 난 단지 마지막 조각으로 uid를 얻을. 이것이 유스 케이스에 충분하지 않다면, 첫 번째 스 니펫을 고수 할 수 있습니다.

+0

위대한 답변! "onAuth 이벤트는 사용자가 로그인하면 시작됩니다." - 사실은 아니지만,'onAuth()'는 인증 상태가 바뀔 때마다 발생합니다. 리스너가 처음으로 연결되면 초기 상태 (아마도 'null')로 시작됩니다. – Kato

관련 문제