Search code examples
javascriptfirebasevalidationgoogle-cloud-firestorefirebase-authentication

want to match email and password from firestore database in js


Email and password are in firestore which is coming from application my job is to create admin panel in js and that admin panel has login page, whenever someone enter there email and password my job is to check email and password, if it matches to the email and password of the firestore email and password then show him/her admin panel otherwise show a pop up that you are not authenticated.

here is the pic of firestore database where I have email and password coming from application

form.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form</title>
    <meta content='width=device-width, initial-scale=1.0, shrink-to-fit=no' name='viewport' />
    <!--     Fonts and icons     -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="https://www.gstatic.com/firebasejs/8.3.3/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.3.3/firebase-firestore.js"></script>
    <!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#available-libraries -->
    <script src="https://www.gstatic.com/firebasejs/8.3.3/firebase-analytics.js"></script>

    <link rel="stylesheet" type="text/css" href="form.css">
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-lg-3 col-md-2"></div>
            <div class="col-lg-6 col-md-8 login-box">
                <div class="col-lg-12 ">
                </div>
                <div class="col-lg-12 login-title">
                    ADMIN PANEL
                </div>

                <div class="col-lg-12 login-form">
                    <div class="col-lg-12 login-form">
                        <form>
                            <div class="form-group">
                                <label class="form-control-label">EMAIL</label>
                                <input type="text" class="form-control email" name="email" id="email"  >
                            </div>

                            <div class="form-group">
                                <label class="form-control-label">COMPANY NAME</label>
                                <input type="text" class="form-control" name="companyname"  id="companyname">
                            </div>

                            <div class="form-group">
                                <label class="form-control-label">PASSWORD</label>
                                <input type="password" class="form-control" name="password" id="password"  >
                            </div>

                            <div class="col-lg-12 loginbttm">
                                <div class="col-lg-6 login-btm login-text">

                                </div>
                                <div class="col-lg-6 login-btm login-button" style='float: right'>
                                    <button class="btn btn-outline-primary" onclick="login()">LOGIN</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <script src="from.js"></script>

        <script>
            // Your web app's Firebase configuration
            // For Firebase JS SDK v7.20.0 and later, measurementId is optional
            var firebaseConfig = {
                apiKey: "AIzaSyCBFPUeRkDtvB9oUYHKH18co6n8sVkktd0",
                authDomain: "insurance-app-515f9.firebaseapp.com",
                projectId: "insurance-app-515f9",
                storageBucket: "insurance-app-515f9.appspot.com",
                messagingSenderId: "507922592990",
                appId: "1:507922592990:web:6ab80539593fc46ea43e4f",
                measurementId: "G-85KC0RZSV8"
            };
            // Initialize Firebase
            firebase.initializeApp(firebaseConfig);
            firebase.analytics();
            const db = firebase.firestore();
            db.setting({ timestampsInSnapshots: true });
        </script>

        <script src="../assets/js/plugins/sweetalert2.js"></script>



</body>

</html>

form.js

function login() {
// var getId=localStorage.getItem("getId");
var useremail = document.getElementById("email").value;   
var companyname = document.getElementById("companyname").value;
var password = document.getElementById("password").value;


db.collection('Companies List').where("CompanyEmail", "==", useremail, "CompanyPassword", "==", password);
Swal.fire({
    title:'Match!',
    text: 'Welcome to the dashboard',
    type: 'success',
      }).then(function() {
  window.location = "dashboard.html";
  });

}

Solution

  • Your query seems to be correct for your requirement. You just need to check if any document has matched the data provided by user. You can do by checking if the snapshot returned is empty or has a matching document

    const docRef = db.collection('Companies List')
       .where("CompanyEmail", "==", useremail)
       .where("CompanyPassword", "==", password);
    // ^ separate .where()
    
    docRef.get().then((snapshot) => {
      if (snapshot.empty) {
        // no docs matched
        console.log("Invalid Credentials")
      } else {
        console.log(snapshot.docs[0].data())
        Swal.fire({
          title:'Match!',
          text: 'Welcome to the dashboard',
          type: 'success',
        }).then(function() {
          window.location = "dashboard.html";
        });
      }
    })
    

    Just a note, ideally you should avoid using Firestore or any database directly for authentication. You could log users in using Firebase Authentication and then store UIDs of users in the respective company document.