Saturday, October 21, 2017

Firebase authentication service for web app

To understand firebase authentication service, lets create a simple frontend web app which will talk to firebase.

1) Create Firebase project

- Create a firebase Project at https://console.firebase.google.com.
- Go to Project Overview -> Click "Add firebase to your webapp"
- It will open a popup and you will find apikeys and endpoints as per your project settings.
- You will use this data in your frontend html file that will connect to firebase.

2) Enable Sign-In Method from Authentication

- You are inside your project in https://console.firebase.google.com.
- Go to Authentication tab from left side menu.
- Click on the SignIn Method. You will be seeing all the supported methods like Email/Password, Phone, Google, Facebook, Twitter etc.
- Enable Email/Password and Google.

3) Create frontend webapp

- You can download the project from the git from the below location or you can use your own.

https://github.com/fullstacktechnos/firebase-frontend


- I am using node.js as local server to serve the page. If you want to use node.js then please check the following article:


http://www.fullstacktechnos.com/2017/10/serving-static-file-using-nodejs-and.html


- I have a single page called index.html and a config file called firebaseconf.js inside public. Config file has all dummy data. You have to replace with your actual project configs. I am using jquery to access dom element.

- Open the firebaseconf.js inside public folder.
- Add the firebase initialization code.


  // Initialize Firebase
  var config = {
    apiKey: "bjfuawfbajbawfbawawfbfawbbawflf",
    authDomain: "testproject.firebaseapp.com",
    databaseURL: "https://testproject.firebaseio.com",
    projectId: "testproject",
    storageBucket: "testproject.appspot.com",
    messagingSenderId: "123456789123"
  };
  firebase.initializeApp(config);


Go to the index.html. I have already created the elements and added event listener to call to firebase. However if you want to create your own please follow the steps below.

- Create email and password field and 4 buttons. Signin, Register, Signin With Google, Signout
- Add event listener for all the buttons.
- Call the firebase authentication service for respective actions.
- Google service will handle all the error conditions. You don't need to worry about it. Check the console after each event.


User Registration:

- At the time of user registration, get the email and password and call the firebase auth service createUserWithEmailAndPassword. 
- If the email is already in use, try logging in using google signin. Google signin code is mentioned below in the article.
- Once the user is created successfully you can find it in firebase console. 
- Go to your project inside https://console.firebase.google.com
- Go to "Authentication" -> "Users"
- You can find the newly created user details.
- You can also add/delete user account from the firebase console.



                              $("#register").click(function(e) {
                var email = $("#email").val();
                var password = $("#password").val();
                if (!email || !password) {
                    return console.log('email and password is required');
                }
                firebase.auth().createUserWithEmailAndPassword(email, password)
                .then(function(result) {
                    console.log(result);
                })
                .catch(function(error){
                    // If user is already registered with the same email
                    // then try to login using google signin
                    if (error.code === 'auth/email-already-in-use') {
                        var credential = firebase.auth.EmailAuthProvider.credential(email, password);
                        var provider = new firebase.auth.GoogleAuthProvider();
                        firebase.auth().signInWithPopup(provider)
                        .then(function(result) {
                            console.log(result); 
                        })
                        .catch(function(error1) {
                            console.log('Google sign in error', error1);
                        });
                    }
                })
            });



User Signin :

- At the time of user login, get the email and password and call the firebase auth service signInWithEmailAndPassword. 
- Test with email that is not present in firebase. 


                          $("#signin").click(function(e) {
                var email = $("#email").val();
                var password = $("#password").val();
                if (!email || !password) {
                    return console.log('email and password is required');
                }
                firebase.auth().signInWithEmailAndPassword(email, password)
                .then(function(result) {
                    console.log(result);
                })
                .catch(function(error) {
                    console.log('signIn error', error);
                })
            });


Google Signin :

- It will work if the page is served from a server.
- If you directly open the index.html or your static file in browser it may not work. So better you use any static server to host the page. I am using node.js for it.
- Get the auth provider and use it to call the service. 
- I am using popup window to enter the google credentials so calling signInWithPopup(). 
- You can even use signInWithRedirect()


                            $("#gsignin").click(function(){
                $("#message").text("");
                // Sign in with Google
                var provider = new firebase.auth.GoogleAuthProvider();
                provider.addScope('profile');
                provider.addScope('email');
                return firebase.auth().signInWithPopup(provider)
                    .then(function(result) {
                        console.log(result); 
                    })
                    .catch(function(error) {
                        console.log('Google sign in error', error);
                    });
            });


User Signout :

Call the auth signOut() function.

                $("#signout").click(function() {
                firebase.auth().signOut();
            });


Listening to Auth State :

- Place the following code once the document is loaded. Its not part of any button event listener.
- It will write the user object data to console for debugging purpose every time there is a change in authentication state like user registration, login, signout etc.

           firebase.auth().onAuthStateChanged(function(user) {
                console.log('user', user);
            });



Note :

For more info please visit firebase official documentation link given below.

https://firebase.google.com/docs/auth/web/start


To know more about firebase and cloud functions please find the below articles:

1) http://www.fullstacktechnos.com/2017/10/why-we-need-firebase-cloud-functions.html

2) http://www.fullstacktechnos.com/2017/10/introduction-to-cloud-functions-for.html

5 comments:

  1. Weabers Inc. is focused on the future of the web. We are a fully integrated design and technology company that transforms ideas into future-proof digital experiences, and help our clients reach the next step in their digital evolution.
    let know here > weabersinc

    ReplyDelete
  2. Nice knowledge gaining article. This post is really the best on this valuable topic.
    software development company in delhi

    ReplyDelete
  3. Are you in search of a free top-rated tracking app for your iPhone or Android smartphone? Stop over https://www.toptrackingapps.com/ and check out the reviews of the most trustworthy tracking apps for both iOS and Android devices. It will help you make a decision which is the best app for you.

    ReplyDelete
  4. People watch the Simpsons for that type of entertainment. They likely won't be visiting your website for (or be impressed by) to be "dazzled" by irrelevant attempts to stand out. https://webceed.co.uk/

    ReplyDelete