Create a system admin panel using Firebase #1 : initialization, user admin settings, and authentication user admin

in #utopian-io5 years ago (edited)

Repository

https://github.com/firebase

What Will I Learn?

  • Firebase initialization and user admin settings
  • Firebase authentication user admin

Requirements

  • Basic HTML, CSS, and javascript
  • Use firebase
  • Local server (Xampp, Wampp, or etc)

Resources

Difficulty

Basic

Tutorial Content

In the tutorial, we will discuss Firebase, which is a tool that is widely used for database matters. We will use firebase to create a simple blog that later we can create an admin system in the application. So we can manage the content that we will present on our blog. I hope you know and understand the basics about Firebase, because in this tutorial, we will not learn the basics of Firebase, so you can learn it on the official website of Firebase. We just start our tutorial about firebase.

Firebase initialization

We will start using firebase, the step that we will first do is to initialize firebase on our application. The following is the application that we will use. We will create a basic page first at index.html and will initialize firebase like the following. But before that, we need you to have to register an account in Firebase so that you are given a free dashboard access. You can register through your Gmail account. after you register you can create a project in our firebase account as shown below.

Screenshot_1.png

I have created a project in my firebase and the name is admin-panel.

  • Firebase initialization

We have created a project in our firebase account. Now, we will initialize firebase by embedding the script in our index.html.

Screenshot_2.png

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Admin panel firebase</title>
</head>
<body>
<h1>Admin panel firebase</h1>
</body>

<script src="https://www.gstatic.com/firebasejs/5.5.7/firebase.js"></script>
<script>
  // Initialize Firebase
  var config = {
    apiKey: "AIzaSyCSPlchU_f5JdqHY3HjcOZREPSy6uiYIaY",
    authDomain: "admin-panel-de482.firebaseapp.com",
    databaseURL: "https://admin-panel-de482.firebaseio.com",
    projectId: "admin-panel-de482",
    storageBucket: "admin-panel-de482.appspot.com",
    messagingSenderId: "274396509060"
  };
  firebase.initializeApp(config);
</script>
</html>

The configuration above is a condition of Firebase, we cannot change it. Now we will create an authentication system using firebase.

Authentication with firebase

Before we create an admin system using firebase, we must first create a login system. The following is a simple frontend display and login form.

  • Login form

We will make the form login simple because what we will emphasize is how this login system is used not on the user interface.

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Admin panel firebase</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    (html comment removed:  Optional theme )
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
</head>
<body>
<div class="container">
   <h1>Admin panel firebase</h1>
    <h3>Login admin</h3>
    <div class="form-group">
        <label for="email">Email address:</label>
        <input type="email" class="form-control" id="email">
    </div>
    <div class="form-group">
        <label for="pass">Password:</label>
        <input type="password" class="form-control" id="pass">
    </div>
      <button type="submit" id="btnLogin" class="btn btn-primary">Login</button>
      <button type="submit" id="btnLogout" class="btn btn-danger hidden">logout</button>
</div>
</body>

<script src="https://www.gstatic.com/firebasejs/5.5.7/firebase.js"></script>
<script>
  // Initialize Firebase
  var config = {
    apiKey: "AIzaSyCSPlchU_f5JdqHY3HjcOZREPSy6uiYIaY",
    authDomain: "admin-panel-de482.firebaseapp.com",
    databaseURL: "https://admin-panel-de482.firebaseio.com",
    projectId: "admin-panel-de482",
    storageBucket: "admin-panel-de482.appspot.com",
    messagingSenderId: "274396509060"
  };
  firebase.initializeApp(config);

  var auth = firebase.auth(); //initialize firebase auth

  var email     = document.getElementById('email');
  var pass      = document.getElementById('pass');
  var btnLogin  = document.getElementById('btnLogin');
  var btnLogout = document.getElementById('btnLogout');

  btnLogin.addEventListener('click', funcLogin);
  btnLogout.addEventListener('click', funcLogout);
</script>
</html>
  • Initialization element to be used

We will initialize the element we will use. We will initialize using pure javascript, So we can use document.getElementById to retrieve the intended element.
Example: document.getElementById('email');.
'email' is the id of input element <input type="email" class="form-control" id="email".

  • Event for element

We can create events with javascript like this btnLogin.addEventListener('click', funcLogin);, btnLogin is element from var btnLogin = document.getElementById('btnLogin');. addEventListener() have two parameters. The first is event 'click' and the second is the function that we will run funcLogin.

  • Create function Login

In this function we will log in with the SignInWithEmailAndPassword() function provided by firebase. in this function, we have two mandatory parameters, e-mail and pass. For more details we can function as follows:

  // Function login
  function funcLogin() {
    auth.signInWithEmailAndPassword(email.value, pass.value)
        .then(function(data){
            console.log("Login Success");
            location.reload();
        }).catch(function(err){
            alert(err)
        })
  }
  • to use the firebase authentication function we must use the an instance of firebase.auth (). We can use auth because it has been defined in the previous section. var auth = firebase.auth();

  • We can get these two parameters from the elements we have initialized.

var email   = document.getElementById('email');
var pass        = document.getElementById('pass')
  • Then we can use this function as promise.then() and you can get the response in data. but when you have failed to login we can catch the error in catch().

  • Setting user in firebase

Before we log in we must register the user. for that, we can open our firebase dashboard. There are a few settings that we will do before using firebase authentication.

sign-in methods

We will set the sign in method what we will use. in this tutorial, we will use the sign in via email.

ezgif.com-video-to-gif (2).gif

Screenshot_3.png
Because we will develop it locally we set the domain on localhost.

Add user

We can add users to the user's section. we will add the user manually.

Screenshot_6.png

Well, the most important part is uid from the user that we registered. Because we will use this user as an admin in our system. that means this user can read and write on our system. The following is how to change the user's rules. in this tutorial, we will use the real-time database system.

ezgif.com-video-to-gif.gif

{
 "rules": {
   ".read": true,
   ".write": "auth.uid =='lCp1yErevFNo24AvG5xYfkdATCf1'"
 }
}

So on a firebase system there are two read and write methods. We allow all users to read ".read": true,, but we will only allow users who have a uid lCp1yErevFNo24AvG5xYfkdATCf1 ".write": "auth.uid =='lCp1yErevFNo24AvG5xYfkdATCf1'" that can write to the firebase system that we created.

  • Use funcLogin() function

We will log in with the user we have created above. we will do console.log() to see what responses we will get.

function funcLogin() {
    auth.signInWithEmailAndPassword(email.value, pass.value)
        .then(function(data){
            console.log("the login was successful");
            console.log(data);
        }).catch(function(err){
            alert(err)
        })
  }

ezgif.com-video-to-gif (1).gif

  • Check Status user

We will create a function that is useful to find out whether the user has logged in or not. we can use the function from firebase which is onAuthStateChanged(). the following is how to use it on our system:

auth.onAuthStateChanged(function(user){
        if(user) {
            //do everthing if user exist.
            //this means the user is logged in 
            btnLogout.classList.remove('hidden');
            btnLogin.classList.add('hidden');
            
        } else {
            //do everthing if user exist.
            //this means the user is logged in 
            btnLogout.classList.add('hidden');
            btnLogin.classList.remove('hidden');
        }
  })

We will play the class hidden in the logout button that we have created
<button type="submit" id="btnLogout" class="btn btn-danger hidden">logout</button>.
We will switch with the remove() and add() functions.

  • Use funcLogout() function

Then we will use the signOut() function provided by firebase to log out a user. The method is simple, just like logging in, log out also uses promise.then (). if I successfully log out. for now, I will only do console.log ("You are logged out").

// function logout
  function funcLogout() {
    auth.signOut().then(function(){
        console.log("You are log out")
    }).catch(function(err){
        alert(err)
    })
  }

ezgif.com-video-to-gif (2).gif

We have successfully created an authentication system and created an admin login system on our application. we will still make a lot of new things in the previous tutorial. Thank you for following this tutorial, hopefully, it can help. see you in the next tutorial which will discuss the admin system more deeply.

Proof of work done

https://github.com/milleaduski/firebaseAdminPanel

Sort:  

Thank you for your contribution @duski.harahap.
We've been reviewing your tutorial and suggest the following points below:

  • We suggest you put more comments in your code. Comments make it easy to interpret your code.

  • Good job at putting pictures on what you are developing.

Thank you very much for the development of your tutorial. We really like this tutorial and we are waiting for the next ones.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thank you for your review, @portugalcoin! Keep up the good work!

Hi @duski.harahap!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @duski.harahap!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.29
TRX 0.12
JST 0.034
BTC 63582.02
ETH 3289.90
USDT 1.00
SBD 3.88