Login dan Registrasi dengan Firebase Authentication pada Aplikasi Website

Halo semua, pada kesempatan kali ini kami akan membawakan artikel dengan judul Tutorial login dan registrasi dengan Firebase Authentication pada Aplikasi Website. Kita akan memulai dari form pendaftaran atau registrasi, form masuk atau login dan form untuk lupa kata sandi atau password.

Menambahkan Firebase

Pertama buka firebase console. Kemudia klik ikon tambah di bagian header dan pilih web. Isi form yang muncul sesuai keinginan anda. Setelah itu akan muncul script seperti ini

<script src="https://www.gstatic.com/firebasejs/7.14.3/firebase-app.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#available-libraries -->

<script>
  // Your web app's Firebase configuration
  var firebaseConfig = {
    apiKey: "-----",
    authDomain: "-----",
    databaseURL: "-----",
    projectId: "-----",
    storageBucket: "-----",
    messagingSenderId: "-----",
    appId: "-----"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
</script>

Download Form

Untuk form masuk, daftar dan lupa password kita akan menggunakan https://github.com/nauvalazhar/bootstrap-4-login-page jadi silahkan di download. Setelah selesai mendownload kita akan memulai pada bagian daftar.

Registrasi dengan Firebase Authentication pada Aplikasi Website

Ubah halaman register.html , tambahkan script yang diatas ke dalam nya tepatnya di pas sebelum tag <body>. Kita akan menambahkan satu field lain yaitu field no telp.

<div class="form-group">
  <label for="phone">Phone</label>
  <input id="phone" type="text" class="form-control" name="phone" required data-eye>
  <div class="invalid-feedback"> Phone is required </div>
</div>

buat file baru bernama app.js , di dalam file tersebut kita akan melakukan seluruh proses. Tambahkan id="registerForm" pada form register kita. Berikut isi app.js

$("#registerForm").submit(function(event){
    event.preventDefault();
    var form = $(this);
    if (form[0].checkValidity() === false) {
        event.preventDefault();
        event.stopPropagation();
    }else if(form[0].checkValidity() === true){
        signUp();
    }
    form.addClass('was-validated');
});

function signUp(){
    var userFullName = document.getElementById("name").value;
    var userPhone = document.getElementById("phone").value;
    var userEmail = document.getElementById("email").value;
    var userPassword = document.getElementById("password").value;
    firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword).then((rslt) => {
        var user = firebase.auth().currentUser;
        var uid;
        if (user != null) {
            uid = user.uid;
        }
        var db = firebase.firestore();
        db.collection("users").doc(uid).set({
            name: userFullName,
            email: userEmail,
            phone: userPhone,
            active:0
        }).then(function() {
            Swal.fire({icon: 'success', title: 'Success' ,text:'our account was created successfully, you can log in now.'}).then((value) => {
                setTimeout(function(){
                    window.location.replace("./dashboard.html");
                }, 1000)
            });         
        })
        .catch(function(error) {
           console.error("Error writing doc", error);
        });
    }).catch((error) => {
        Swal.fire({icon: 'error',
        title: 'Oops...',text:error.message});
    });
}

Jadi, proses di atas di mulai dengan melalukan pendaftaran di Firebase Auth setelah itu kita memasukan datanya ke firestore.



Berikut adalah file dashboard.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="author" content="Kodinger">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>My Login Page &mdash; Bootstrap 4 Login Page Snippet</title>
  <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">
  <link rel="stylesheet" type="text/css" href="css/my-login.css">
</head>
<body class="my-login-page">
  <section class="h-100">
    <div class="container h-100">
      <div class="row justify-content-md-center h-100">
        <div class="card-wrapper">
          <div class="brand">
            <img src="img/logo.jpg" alt="bootstrap 4 login page">
          </div>
          <div class="card fat">
            <div class="card-body">
              <h4 class="card-title">Dashboard</h4>
            
              <button>dsf</button>
            </div>
            <div class="card-footer"><button onclick="signOut()" class="btn btn-danger float-right"> Logout </button></div>
          </div>
          <div class="footer">
            Copyright &copy; 2017 &mdash; Your Company 
          </div>
        </div>
      </div>
    </div>
  </section>

  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  <script src="js/my-login.js"></script>
  <!-- The core Firebase JS SDK is always required and must be listed first -->
  <script src="https://www.gstatic.com/firebasejs/7.14.3/firebase-app.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/7.14.3/firebase-analytics.js"></script>
  <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-auth.js"></script>

  <script>
  // Your web app's Firebase configuration
  var firebaseConfig = {
    apiKey: "--",
    authDomain: "--",
    databaseURL: "--",
    projectId: "--",
    storageBucket: "--",
    messagingSenderId: "--",
    appId: "--",
    measurementId: "--"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
  firebase.analytics();
  </script>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
    <script src="app.js"></script>
    <script>
      firebase.auth().onAuthStateChanged(function(user) {
      if (!user){
        Swal.fire({icon: 'warning', title: 'Need to login' ,text:'You need to login first'}).then((value) => {
          window.location.replace("./index.html");
        });
      }
    });
    </script>

</body>
</html>

file di atas hanya dapat di akses jika user login jika tidak akan ada alert yang muncul.

Silahkan sekarang anda coba untuk bagian registrasi dengan firebase, jika tidak muncul atau ada error anda dapat meninggalkan komentar dibawah.

Login dengan Firebase Authentication pada Aplikasi Website

Tambahkan id di index.html (form) id="loginForm". Proses login ini tidak jauh berbeda dengan proses daftar, buka app.js anda kemudian tambahkan

$("#loginForm").submit(function(event){
    event.preventDefault();
    var form = $(this);
    if (form[0].checkValidity() === false) {
        event.preventDefault();
        event.stopPropagation();
    }else if(form[0].checkValidity() === true){
        signIn();
    }
    form.addClass('was-validated');
});
function signIn(){
    var userSIEmail = document.getElementById("email").value;
    var userSIPassword = document.getElementById("password").value;
    firebase.auth().signInWithEmailAndPassword(userSIEmail, userSIPassword).then((success) => {
        Swal.fire({icon: 'success', title: 'Success' ,text:'Login success'}).then((value) => {
            setTimeout(function(){
                window.location.replace("./dashboard.html");
            }, 1000)
        });

    }).catch((error) => {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        Swal.fire({icon: 'error', title: 'woops..' ,text:errorMessage}).then((value) => {
            
        });
    });
}

proses login sesingkat ini, jadi silahkan di coba untuk Login dengan Firebase Authentication pada Aplikasi Website. Jika ada error atau ada pertanyaan silahkan isi di kolom komentar.

Memunculkan data user dari firestore

Selanjutnya kita akan mengubah file dashboard.html kita. Kita akan memunculkan data user yang ada di firestore. Tambahkan script dibawah ini didalam .card-body

<div id="usersection"></div>

ubah bagian pengecekan user menjadi seperti ini

firebase.auth().onAuthStateChanged(function(user) {
    if (!user){
      Swal.fire({icon: 'warning', title: 'Need to login' ,text:'You need to login first'}).then((value) => {
        window.location.replace("./index.html");
      });
    }else{
      //console.log(user.uid);
      getDoc(user.uid);
    }
  });
  async function getDoc(id) {
    const snapshot = await db.collection('users').doc(id).get();
    const data = snapshot.data();
    $("#usersection").html("<p>"+data['name']+"</p>" + "<p>"+data['email']+"</p>" + "<p>"+data['phone']+"</p>");
  }

dalam fungsi getDoc(id) kira mengambil data dari firestore. Untuk signout() sendiri seperti ini

function signOut(){
    firebase.auth().signOut().then(function() {
        // Sign-out successful.
        Swal.fire({icon: 'success', title: 'Success' ,text:'Logout success'}).then((value) => {
            setTimeout(function(){
                window.location.replace("./index.html");
            }, 1000)
        });
    }).catch(function(error) {
        // An error happened.
        let errorMessage = error.message;
        swal({
            type: 'error',
            title: 'Error',
            text: "Error",
        })
    });
}

Ubah data di Firestore

Kita akan menambahkan link untuk edit lewat dashboard.html. Jadi ubah menjadi seperti ini

<h4 class="card-title">Dashboard</h4> <small class="text float-right"> <a href="./edit.html"> Edit </a></small>

kemudian buat form edit, kita hanya akan mengubah 2 kolom yaitu nama dan telpon. Seperti ini form nya

<div class="card fat">
            <div class="card-body">
              <h4 class="card-title">Edit</h4>
              <form method="POST" class="my-login-validation" id="updateForm" novalidate="">
                <div class="form-group">
                  <label for="name">Name</label>
                  <input id="name" type="text" class="form-control" name="name" required autofocus>
                  <div class="invalid-feedback">
                    What's your name?
                  </div>
                </div>

                <div class="form-group">
                  <label for="phone">Phone</label>
                  <input id="phone" type="text" class="form-control" name="phone" required data-eye>
                  <div class="invalid-feedback">
                    Phone is required
                  </div>
                </div>

                <div class="form-group m-0">
                  <button type="submit" class="btn btn-primary btn-block">
                    Update
                  </button>
                </div>
              </form>
            </div>
          </div>

kemudian, kita akan memunculkan data user dari firestore dan memasukannya kedalam field-field diatas.

<script>
        firebase.auth().onAuthStateChanged(function(user) {
          if (!user){
              Swal.fire({icon: 'warning', title: 'Need to login' ,text:'You need to login first'}).then((value) => {
                  window.location.replace("./index.html");
              });
          }else{
              console.log(user.uid);
              getDoc(user.uid);
          }
      });
      async function getDoc(id) {
          const snapshot = await db.collection('users').doc(id).get();
          const data = snapshot.data();
            console.log(data);
            $("#name").val(data['name']);
            $("#phone").val(data['phone']);
      }
    </script>

letakan dibawah <script src="app.js"></script>, lalu kita akan membuat fungsi baru di dalam app.js.

$("#updateForm").submit(function(event){
    event.preventDefault();
    var form = $(this);
    if (form[0].checkValidity() === false) {
        event.preventDefault();
        event.stopPropagation();
    }else if(form[0].checkValidity() === true){
        updateData();
    }
    form.addClass('was-validated');
});
function updateData(){
    var phone = document.getElementById("phone").value;
    var name = document.getElementById("name").value;
    firebase.auth().onAuthStateChanged(function(user) {
        db.collection("users").doc(user.uid).update({name: name , phone:phone}).then((result) => {
            Swal.fire({icon: 'success', title: 'Success' ,text:'Update data success'}).then((value) => {
                window.location.replace("./dashboard.html");
            });
        });
    });
}

setelah proses update berhasil, kita akan diarahkan ke halaman dashboard.html dengan data yang baru.

Reset password Firebase Authentication

Untuk mengubah password halaman formnya ada forgot.html isinya seperti ini

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="author" content="Kodinger">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>My Login Page &mdash; Bootstrap 4 Login Page Snippet</title>
  <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">
  <link rel="stylesheet" type="text/css" href="css/my-login.css">
</head>
<body class="my-login-page">
  <section class="h-100">
    <div class="container h-100">
      <div class="row justify-content-md-center align-items-center h-100">
        <div class="card-wrapper">
          <div class="brand">
            <img src="img/logo.jpg" alt="bootstrap 4 login page">
          </div>
          <div class="card fat">
            <div class="card-body">
              <h4 class="card-title">Forgot Password</h4>
              <form method="POST" class="my-login-validation" id="resetForm" novalidate="">
                <div class="form-group">
                  <label for="email">E-Mail Address</label>
                  <input id="email" type="email" class="form-control" name="email"  value="" required autofocus>
                  <div class="invalid-feedback">
                    Email is invalid
                  </div>
                  <div class="form-text text-muted">
                    By clicking "Reset Password" we will send a password reset link
                  </div>
                </div>

                <div class="form-group m-0">
                  <button type="submit" class="btn btn-primary btn-block">
                    Reset Password
                  </button>
                </div>
              </form>
            </div>
          </div>
          <div class="footer">
            Copyright &copy; 2017 &mdash; Your Company 
          </div>
        </div>
      </div>
    </div>
  </section>

  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="js/my-login.js"></script>
  <script src="https://www.gstatic.com/firebasejs/7.14.3/firebase-app.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/7.14.3/firebase-analytics.js"></script>
  <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-auth.js"></script>
  <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-firestore.js"></script>


  <script>
  // Your web app's Firebase configuration
  var firebaseConfig = {
    ...
      konfigurasi anda
    ...
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
  firebase.analytics();
  </script>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
    <script src="app.js"></script>
    
</body>
</html>

lalu pada app.js tambahkan

$("#resetForm").submit(function(event){
    event.preventDefault();
    var form = $(this);
    if (form[0].checkValidity() === false) {
        event.preventDefault();
        event.stopPropagation();
    }else if(form[0].checkValidity() === true){
        resetPassword();
    }
    form.addClass('was-validated');
});
function resetPassword(){
    var userSIEmail = document.getElementById("email").value;
    firebase.auth().sendPasswordResetEmail(userSIEmail).then((success) => {
        Swal.fire({icon: 'success', title: 'Success' ,text:'We have sent you new password'});

    }).catch((error) => {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        Swal.fire({icon: 'error', title: 'woops..' ,text:errorMessage}).then((value) => {
            
        });
    });
}

jika anda jalankan dan email yang anda masukan terdaftar. Anda akan menerima email yang berisi link untuk mengubah password anda.

Link demo firebaseauth.tukangaplikasi.com

Sekian artikel tentang Login dan Registrasi dengan Firebase Authentication pada Aplikasi Website, semoga bermanfaat.

Tinggalkan Balasan

Subscribe To Our Newsletter

Subscribe To Our Newsletter

Kami memberikan tutorial baru tiap harinya !!!

You have Successfully Subscribed!

%d blogger menyukai ini: