Pregunta

I'm trying auto-generate user accounts that I can save data with, and later promote those to proper username/password accounts. Any ideas on the best way to do that?

It wasn't clear to me whether or not I could switch auth providers from anonymous to password.

¿Fue útil?

Solución

You can start by creating an anonymous login with Firebase, and then store that auth "uid" key to some sort of session or cookie (depending on what framework you're working with). While the client is anonymous, you can link your saved data to this anonymous "uid".

To transfer the data over to the user after they login, you'll need to use Firebase's onAuth() listener. This will notify you when the user's auth data changes. Once you have the new authenticated uid, you can link your stored data to that new uid and delete your anonymous session.

Here's the modified sample from Firebase docs:

var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com');
firebaseRef.onAuth(function(authData) {
  if (authData) {
    // Client is logged in, so check if it's anonymous or a real user

    if (authData.provider === 'anonymous') {
      // user is anonymous
      // save authData.uid to some local session info, to keep track of data
    } else {
      // user is logged in
      // transfer any data that you had stored from the anonymous session to 
      // this new authUser.uid

  } else {
    // Client is unauthenticated

    // This would be a good spot to create the anonymous login
    firebaseRef.authAnonymously(function(error, authData) {
      if (error) {
        // handle login failure
      } else {
        // you are now anonymously logged in, but you really don't need to do anything
        // here, because your onAuth() listener is already going to catch this auth change
      }
  }
});

Firebase doesn't tell you what the previous uid was when the user changes their auth info, so you really need to store that anonymous uid somewhere. You could also do the whole thing without ever creating the anonymous login, by just storing session data until the user logs in, but the anonymous login provides more consistency.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top