2016-05-26 2 views
1

Я пытаюсь сделать простой регистрации пользователя логин на Firebase, но я получаю эту ошибку:Authentication Firebase

Uncaught ReferenceError: FirebaseAuthClient is not defined

Вот мой код:

var authClient = new FirebaseAuthClient(rootRef, function(error, user) { 
    if (error) { 
    alert(error); 
    return; 
    } 
    if (user) { 
    // User is already logged in. 
    doLogin(user); 
    } else { 
    // User is logged out. 
    showLoginBox(); 
    } 
}); 


function showLoginBox() { 

    document.getElementById("#registerButton").addEventListener("click", function() { 
    var email = document.getElementById("#email").val(); 
    var password = document.getElementById("#password").val(); 
    authClient.createUser(email, password, function(error, user) { 
     if (!error) { 
     doLogin(user); 
     } else { 
     alert(error); 
     } 
    }); 
    }); 
} 
+0

Откуда у вас «FirebaseAuthClient»? Я считаю, что класс устарел уже более 2 лет. См. Http://stackoverflow.com/questions/17487968/firebase-firebaseauthclient-class-being-deprecated –

ответ

1

Для того, чтобы избежать проблемы с классом FirebaseAuthClient, вы можете попробовать использовать недавно обновленные функции для авторизации в Firebase:

https://firebase.google.com/docs/auth/ios/password-auth#create_a_password-based_account

После прочтения новых документов и создания приложения я нашел самое легкое решение для регистрации пользователей в качестве пароля электронной почты &. Надеюсь, это то, что вы ищете.

Вот некоторые примеры кода:

import Firebase 

//Register user 
FIRAuth.auth()?.createUserWithEmail(email: String, password: String) { (user, error) in 
     if (error != nil){ 
      print(error!.localizedDescription) 
      return 
     } 
//user registered 
} 

//Login user 
FIRAuth.auth()?.signInWithEmail(email: String, password: String) { (user, error) in 
     if (error != nil){ 
      print(error!.localizedDescription) 
      return 
     } 
//user logged in 
} 

//Check if user is signed in 
if let user = FIRAuth.auth()?.currentUser { 
// User is signed in. 
} else { 
// No user is signed in. 
} 

Теперь иди те пользователи!

+0

Если вы нашли мой ответ полезным, я предлагаю его принять. @Thalita Caetano –

0
private FirebaseAuth mAuth; 
private FirebaseAuth.AuthStateListener mAuthListener;   
mAuth = FirebaseAuth.getInstance(); 
     mAuthListener = new FirebaseAuth.AuthStateListener() { 
     @Override 
     public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { 
      FirebaseUser user = firebaseAuth.getCurrentUser(); 
      if (user != null) { 
       // User is signed in 
       Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid()); 
      } else { 
       // User is signed out 
       Log.d(TAG, "onAuthStateChanged:signed_out"); 
      } 
      // ... 
     } 
    }; 

Ток пожарной базы получить из fcm FirebaseInstanceIdService.

mAuth.signInWithCustomToken(firebase_token) 
        .addOnCompleteListener(getActivity(), new  OnCompleteListener<AuthResult>() { 
         @Override 
         public void onComplete(@NonNull Task<AuthResult> task) { 
          System.out.println("PRINT_DATACHANGE TASK :" + task.isSuccessful()); 

          // If sign in fails, display a message to the user. If sign in succeeds 
          // the auth state listener will be notified and logic to handle the 
          // signed in user can be handled in the listener. 
          if (!task.isSuccessful()) { 
           Log.w(TAG, "signInWithCustomToken", task.getException()); 
         /* Toast.makeText(getActivity(), "Authentication failed.", 
           Toast.LENGTH_SHORT).show();*/ 
          } else { 
           Log.w(TAG, "signInWithCustomToken_else"); 

          } 
         } 
        }); 
0

Я получил это от firecast, вы можете войти и зарегистрировать нового пользователя. Это очень хорошо для меня, я использую его с электронной почтой и паролем auth, так что нет google auth. Я также добавляю простую страницу переадресации, когда вы уже входите в систему, а не входите в систему. если вы забыли логин, вы переадресовываете на dashboard.html, и если вы не заходите в систему, вы будете перенаправлять на login.html. Извините за мой плохой английский.

"use strict"; 
 
    const txtemail  = document.getElementById('txtemail'); 
 
    const txtpass  = document.getElementById('txtpass'); 
 
    const btnlogin  = document.getElementById('btnlogin'); 
 
    const btnreg  = document.getElementById('btnreg'); 
 
    const btnout  = document.getElementById('btnout'); 
 
    const texthiden  = document.getElementById('txthide'); 
 

 
    btnlogin.addEventListener('click', e => { 
 
     const email = txtemail.value; 
 
     const pass = txtpass.value; 
 
     const auth = firebase.auth(); 
 

 
     const promise = auth.signInWithEmailAndPassword(email, pass); 
 
     promise.catch(e => console.log(e.message)); 
 
    }); 
 
    btnreg.addEventListener('click', e => { 
 
     const email = txtemail.value; 
 
     const pass = txtpass.value; 
 
     const auth = firebase.auth(); 
 
     const promise = auth.createUserWithEmailAndPassword(email, pass); 
 
     promise.catch(e => console.log(e.message)); 
 
    }); 
 
    firebase.auth().onAuthStateChanged(firebaseUser =>{ 
 
     if(firebaseUser){ 
 
      console.log(firebaseUser); 
 
      btnout.classList.remove('hide'); 
 
      window.location = "dashboard.html"; 
 
     }else{ 
 
      console.log('not login'); 
 
      btnout.classList.add('hide'); 
 
      window.location = "login.html"; 
 
     } 
 
    }); 
 
    btnout.addEventListener('click', e => { 
 
     firebase.auth().signOut(); 
 
    });
вы также можете скрыть кнопку выйти, если вы хотите, как <button id="btnout" class="btn btn-default btn-group-lg hide">Logout</button>. и javascript отобразит вашу кнопку выхода btnout.classList.remove('hide');

Смежные вопросы