2016-08-16 5 views
0

Я только что начал новый проект, и я работаю над auth. Я могу войти в систему для пользователей, использующих электронную почту, google или github. Но как перенаправить их на другую страницу успешной регистрации: Вот код ниже:Как перенаправить пользователя после успешного входа в firebase?

var config = { 
apiKey: "asdfasdfasdf", 
authDomain: "asdfasdfasdf", 
databaseURL: "asdfasdfasdf", 
storageBucket: "asdfasdfasdf", 
}; 
firebase.initializeApp(config); 

//The stuff 
var logine = document.getElementById("logine"); 
var reggy = document.getElementById("reggy"); 
var usr = document.getElementById("usr"); 
var pwd = document.getElementById("pwd"); 
var reset = document.getElementById("forgot"); 
var google = document.getElementById("google"); 
var logout = document.getElementById("logout"); 
var github = document.getElementById("github"); 

//Login event 
function loginEvent(){ 
//Retreive the email and dat pwd 
var email = usr.value; 
var password = pwd.value; 
var auth = firebase.auth(); 
//User signs in 
var promise = auth.signInWithEmailAndPassword(email,password).catch(function(error){ 
//Handle any errors here 
var errorCode = error.code; 
    var errorMessage = error.message; 

    if (errorCode === 'auth/wrong-password'){ 
    alert('Get the password right'); 
    } else { 
    alert(errorMessage); 
    } 
}); 
promise.catch(e => console.log(e.message)); 
if (email.length < 12){ 
    document.getElementById("bademail").classList.remove("hide"); 

} 
if(password.length < 6){ 
    document.getElementById("bademail").classList.remove("hide"); 
} 
} 

//Register event 
function registerEvent(){ 
    var email = usr.value; 
var password = pwd.value; 
var auth = firebase.auth(); 

//User signs in 

// TODO: Check for email 
var promise = auth.createUserWithEmailAndPassword(email, password).catch(function(error){ 
    //Handle any errors here 
    var errorCode = error.code; 
    var errorMessage = error.message; 

    if(errorCode === 'auth/weak-password'){ 
    alert('All passwords are must be 6 characters or more') 
    } else { 
    alert(errorMessage); 
    } 

    }); 
    promise 
    .catch(e => console.log(e.message)); 
    if (email.length < 12){ 
    document.getElementById("bademail").classList.remove("hide"); 
    } 

    } 
function logoutEvent(){ 
firebase.auth().signOut(); 
} 
//Signing in with Google 
function googleAuth(){ 
//Google Auth 
var provider = new firebase.auth.GoogleAuthProvider(); 
firebase.auth().signInWithPopup(provider).then(function(result) { 
// This gives you a Google Access Token. You can use it to access the Google API. 
var token = result.credential.accessToken; 
// The signed-in user info. 
var user = result.user; 
// ... 
}).catch(function(error) { 
// Handle Errors here. 
var errorCode = error.code; 
var errorMessage = error.message; 
// The email of the user's account used. 
var email = error.email; 
// The firebase.auth.AuthCredential type that was used. 
var credential = error.credential; 
// ... 
}); 
} 
//Signing in with github 
function githubAuth(){ 
var provider = new firebase.auth.GithubAuthProvider(); 
firebase.auth().signInWithPopup(provider).then(function(result) { 
// This gives you a GitHub Access Token. You can use it to access the GitHub API. 
var token = result.credential.accessToken; 
// The signed-in user info. 
var user = result.user; 
// ... 
}).catch(function(error) { 
// Handle Errors here. 
var errorCode = error.code; 
var errorMessage = error.message; 
// The email of the user's account used. 
var email = error.email; 
// The firebase.auth.AuthCredential type that was used. 
var credential = error.credential; 
// ... 
}); 

} 
//Password reset email 
function sendPasswordReset() { 
    var email = document.getElementById('usr').value; 
    // [START sendpasswordemail] 
    firebase.auth().sendPasswordResetEmail(email).then(function() { 
    // Password Reset Email Sent! 
    // [START_EXCLUDE] 
    alert('We sent the email so check tu inbox'); 
    // [END_EXCLUDE] 
    }).catch(function(error) { 
    // Handle Errors here. 
    var errorCode = error.code; 
    var errorMessage = error.message; 
    // [START_EXCLUDE] 
    if (errorCode == 'auth/invalid-email') { 
     alert(errorMessage); 
    } else if (errorCode == 'auth/user-not-found') { 
     alert(errorMessage); 
    } 
    console.log(error); 
    // [END_EXCLUDE] 
    }); 
    // [END sendpasswordemail]; 
    } 

    //Realtime listener 
    firebase.auth().onAuthStateChanged(firebaseUser => { 
    if(firebaseUser){ 
    console.log(firebaseUser); 
    document.getElementById("logout").classList.remove('hide'); 
    window.location("index.html"); 
     }else{ 
    console.log("GET OUT KID"); 
    document.getElementById("logout").classList.add('hide'); 
     reset.addEventListener('click', sendPasswordReset, false); 
     google.addEventListener('click', googleAuth, false); 
     logine.addEventListener('click', loginEvent, false); 
     reggy.addEventListener('click', registerEvent, false); 
     logout.addEventListener('click', logoutEvent, false); 
     github.addEventListener('click', githubAuth, false); 
} 
}); 

ответ

4

Для обработки входа и выхода из системы, всегда используйте onAuthStateChanged()

//Handle Account Status 
firebase.auth().onAuthStateChanged(user => { 
    if(user) { 
    window.location = 'home.html'; 
    } 
}); 

В тот момент кто-то логины, user будут заполнены информацией пользователя, и вы можете использовать ее для перенаправления на другую страницу.

+0

работает также отлично с угловыми 2 :) спасибо :) – Blueblazer172

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