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

19 comments:

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

    ReplyDelete
  2. 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
  3. 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
  4. Today, I was just browsing along and came upon your blog. Just wanted to say good blog and this article helped me a lot, due to which I have found exactly I was looking. wedding anniversary wishes for parents


    ReplyDelete
  5. Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info.

    wedding anniversary wishes for parents

    ReplyDelete
  6. I appreciate the work done by the author. Thanks a lot.Happy holi images 2019

    ReplyDelete
  7. Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work. Webdesign bureau

    ReplyDelete
  8. Your website is really cool and this is a great inspiring article. Thank you so much. app store screenshot templates

    ReplyDelete
  9. I found your this post while searching for some related information on blog search...Its a good post..keep posting and update the information. user experience

    ReplyDelete
  10. i never know the use of adobe shadow until i saw this post. thank you for this! this is very helpful. web design

    ReplyDelete
  11. I admit, I have not been on this web page in a long time... however it was another joy to see It is such an important topic and ignored by so many, even professionals. I thank you to help making people more aware of possible issues. web design in Switzerland

    ReplyDelete
  12. Glad I'm stumbled upon to this blog, the content is very information thanks for sharing such piece of knowledge with us.
    TikiTunes Review

    ReplyDelete
  13. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. website redesign

    ReplyDelete
  14. Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained

    ve may bay di thai lan

    từ tphcm đi malaysia

    vé máy bay đi úc giá rẻ

    vé máy bay đi hàn quốc hạng thương gia

    vé máy bay từ đà nẵng đi seoul

    đặt vé máy bay đi nhật bản

    vé máy bay hà nội tokyo vietnam airlines

    ReplyDelete
  15. What is an outstanding post! “I’ll be back” (to read more of your content). Thanks for the nudge! Indijska-turistična-vizuma

    ReplyDelete
  16. This article was written by a real thinking writer. I agree many of the with the solid points made by the writer. I’ll be back. 印度医疗签证

    ReplyDelete
  17. We appreciate this article. For those of you around the world who wish to travel to Myanmar, there is good news - Myanmar visas have been opened & If you want to know the Myanmar eVisa Fee here is a wonderful site where you get information about fees from your country.

    ReplyDelete
  18. It is really a very informative and interesting article. What is a cloud computing service ? It simply means the service related to computer service like Data storage , networking , software. Data Management etc.


    ReplyDelete