简体   繁体   中英

Login page redirection based on user role using javascript and firebase

What I'm trying to accomplish is to create a user login using html/javascript with firestore as my backend provider. Currently my code returns an error

Uncaught (in promise) TypeError: Cannot read property 'uid' of undefined

TypeError: Cannot read property 'uid' of undefined

I understand that get() takes time to run so I used the function then() as a promise when get() works. At the moment the only thing that works is the

 const userCredential = await firebase.auth().signInWithEmailAndPassword(data.email, data.password);

because the console log shows firebase.auth().onAuthStateChanged() but no redirection to any page based on user (based on its occupation) is happening because the uid cannot be found.

here is my .js code

(function(){//initialize the firebase app
    var config = {

        }; 

        firebase.initializeApp(config);
        var auth = null;
        var loginBtn= document.getElementById('btnLogin');
        // var user = db.collection("users");
        // var db = firebase.firestore();
        firebase.auth.Auth.Persistence.SESSION;

    //Login
    loginBtn.addEventListener('click', async e => {
        e.preventDefault();
        if( $('#email').val() != '' && $('#password').val() != '' ){
        //login the user
        var data = {
            email: $('#email').val(),
            password: $('#password').val()
        };

    try{
        const userCredential = await firebase.auth().signInWithEmailAndPassword(data.email, data.password);
        let uid = userCredential.user.uid;
        var documents = await firebase.firestore().collection('users').doc(uid);
        documents.get().then(function(doc){
            if(doc.data['occupation'] != 'Doctor'){
                window.location.href = "patientDashboard.php"; 
            }
            else {
                window.location.href = "doctorDashboard.php";  
            }
        });
    } 
        catch(err) {
            console.log("Login Failed!", err);
            window.alert("Login Failed!", err);
        }
    }
});
})();

I hope I explained it well, thanks in advance!

I'm not sure this line

firebase.auth().signInWithEmailAndPassword(data.email, data.password); //this will work

actually works, because, as the docs say here , that method is asynchronous, so it returns a promise. You would have to use something like this:

const userCredential = await firebase.auth().signInWithEmailAndPassword(data.email, data.password);
let uid = userCredential.user.uid;
// do stuff

So we're awaiting the result of the signIn function and then we're using the value it returned.

Also, as we're using await , the lambda function assigned as an event listener should be declared async .

//Login
loginBtn.addEventListener('click', async (e) => {
        e.preventDefault();
        ...

This is the answer to my redirection problem, it resides in fixing the query code within the try{} code.

try{
    const userCredential = await firebase.auth().signInWithEmailAndPassword(data.email, data.password);
    let uid = userCredential.user.uid;
    var document = await firebase.firestore().collection("users").doc(uid).get();
    //document is a DocumentSnapshot, we can call the get() method
    if (document.get('occupation') != 'Doctor'){
       window.location.href = "patientDashboard.php"; 
    }
    else {
       window.location.href = "doctorDashboard.php";  
    }                   
}    
catch(err){
    console.log("Login Failed!", err);
    window.alert("Login Failed!", err);
}

DISCLAIMER

Be aware that with this code you are NOT implementing a genuine role-based access control system. This is code simply for an academic requirement that I am currently developing and in no way being used for deployment to any clients. You are just redirecting the user based on a value in its user document. Someone could easily reverse engineer your app and redirects to the wrong page.

Full credit to Renaud Tarnec for fixing the error!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM