Creating & Managing Users with Google Firebase (Case)

This is a case study for use in a class like Software Development.

Please note: This case builds on a prior case called ‘Automating Your Gruntwork with Javascript’ and assumes familiarity with its contents.

And Now…For Some Users!

Frangelico DeWitt is working with his team to develop a new suite of software for their employer HVAC in a Hurry (a heating and air conditioning service business). Their current focus is on a web application that helps field technicians find availability and pricing for replacement parts.JQuery-Prototype-4

Frangelico is not a developer by training, but through diligent tinkering and self-study, he has managed to build a prototype working on JS Fiddle that’s been working well for concept development, user testing, and demo’s. Now that they’ve validated the concept and are ready to move to something live for users, the team has decided they want to use Google’s Firebase platform to build the application.

The winter holiday starts next week and while Frangelico plans to enjoy himself, he’s curious to try out Firebase and see if he can get something working. He talked with the rest of his team about the idea of tinkering with Firebase himself, and they love the idea- his code might need to be rewritten for any number of reasons, but the experience can only help.

The team has a few user stories in their product backlog that Frangelico plans to work. Basically, they deal with users creating accounts on the platform and signing in to the system. The idea is to keep the implementation of these stories very focused and simple so they can move on to part ordering, at which point they will have something they could actually test with users. You’ll find the initial set of stories about login in Exhibit A. The later exhibits have notes on working with Firebase and getting started with the sample code.

Creating & Managing Users with Google Firebase

Here’s a sample in JS Fiddle to get you started: Creating & Managing Users with Firebase.

1. Can you follow what the code is doing?
– There are a bunch of Firebase functions being called that aren’t listed in the Javascript. Where are those coming from?
– What’s an observer function and how is ‘firebase.auth().onAuthStateChanged’ an example of one? For background, see Exhibit: Key JS Concepts and Techniques.
– What are the various HTML forms and when, where do they appear?
– How does the data flow from the user login event to the actual log in event on Firebase? What’s happening?
– There are a few instances of .then(…) in the code. What are those doing and why are they necessary? For background, see Exhibit: Key JS Concepts and Techniques.
– Firebase.auth().onAuthStateChanged is what’s called an observer function. What does that mean and why is the observer pattern a good fit for the particular job this code is doing? For background, see Exhibit: Key JS Concepts and Techniques.

2. Let’s suppose Frangelico wants to restrict new users to a specific email domain. How would you modify the code to do that?
Note: You’d probably want them to confirm their identity over email before you sign them in, but you can skip that for now. If you’re particularly interested in trying it out, however, it is a feature of Firebase.

3. For this user story: ‘As Ted the Technician, I want to sign in to the system so I can order a part.’, there are a couple of test cases that add more detail:
Make sure that if a tech (user) submits a username/email with the @hvacnhurry.com domain that doesn’t exist on the new system, they get a descriptive error like: ‘For now, this is a stand-alone system. If you haven’t created an account here, just click create account. Sorry for the extra step!’.

What else do you think is worth trying? Try it out!

Exhibit A: User Stories on Sign Up and Log In

These user stories deal with signup, but as with any story we should answer the question of ‘why?’ for the user in a testable way. In this case, the why is that a user can’t actually order a part until they’ve logged in. We’re implementing the login first and not covering the interaction where a user orders in this case.

Generally speaking, this is a bad idea! It’s super important to implement in small slices that you can meaningfully test with users as you go (so you make sure you’re building something worthwhile). In this case, Frangelico has decided to work on a very basic set of login stories, which is fine as long as he keeps it simple and focused and moves on to the interaction where the user orders directly after these stories.

Epic User Story

‘As Ted the HVAC technician, I want to sign in to the system so I can order a part.’

Storyboard

hinh--user-signup-highres

Child Stories

User Story

Test Cases

As Ted the Technician, I want to sign in to the system so I can look up a part. Make sure that if they submit a username/email with the @hvacnhurry.com domain that doesn’t exist on the new system, they get a descriptive error like: ‘For now, this is a stand-alone system. If you haven’t created an account here, just click create account. Sorry for the extra step!’

Make sure that if they get a bad password error, remind them that this is a separate system from ‘HVAC Central’ and their password may be different.

 As Ted the Technician, I want to create an account so I can try out the system.
 As Ted the Technician, I want to reset my password, so I can log in to the system. Make sure if they attempt to reset against an account we don’t have that they get the reminder above about this being a stand-alone system.

Exhibit B: Setting Up a Project on Firebase

Please Note!

You do not need to set up your own Firebase project to work on the case. This appendix is for general reference- for example, if this is something you want use for your own project at a later date.

What is Firebase?

Google Firebase is an example of Infrastructure As a Service, where Google manages all of your cloud infrastructure for apps so that you don’t have to. Other examples include various services from Amazon Web Services and Heroku (part of Salesforce), where these companies host all of your servers, applications, and databases externally. The great thing about using these services is that you end up writing and maintaining less code. While the subscription and usage fees may not make sense for a big operation at scale, for a small project who’s trying to learn if it’s on to something, these services are a great fit.

Firebase has a suite of products, which are kind of like different modules on top of the platform. In this case, we’ll be using the Authentication product. Unless/until you’re scaling to something in production with a substantial number of users, you’ll be able to use the free ‘Spark’ plan.

How do I set up Firebase to run the code in the JS Fiddle?

Tasks:
– Create a server-side project/application (this is your “back end” used to keep track of and authenticate users)
– Add and configure Google Firebase’s pre-built user authentication to this application
NOTE: You need a valid Google/Gmail login to use Firebase.

The administrative interface for configuring Firebase is called the Console. In a browser where you’re logged into your Google account, access the Google Firebase Console:
firebase_setup_A
Add a new project and give it a title by clicking “Add project”:

firebase_setup_B

Now, select “Authentication” on the left sidebar underneath “Develop” (pictured below). Once you’re here, select “Set up Sign-In Method”:

firebase_setup_C

The sample client on JS Fiddle uses an email + password pair, so in the menu that follows you’ll select ‘Email / Password’ login. Once we enable this, we allow authentication against our registry of verified users.

firebase_setup_D

At this point, we can add users to our application’s built-in, Google-maintained database. Go ahead and add a user for yourself, using the your email and a unique password.

firebase_setup_E_post

We now have everything we need to test out authentication. Just to recap, we created an application in Google’s Firebase Cloud Infrastructure and added user authentication by email/password. Then, we created a user for ourselves so that we can test that this authentication works in our own/forked version of the JS Fiddle.

Next, we will fork the sample code and reconfigure it to use our project on Firebase.

How do I configure the sample code to use my new project?

Tasks
– Fork the existing JS Fiddle client code so you have your own version you can edit and save
– Replace the existing Firebase configuration to reference your own application/project
– Verify that your new client and configuration is working

First off, you’ll want your own version of the Fiddle that you can edit and save. Make sure you’re logged in to your account on JS Fiddle, and click ‘Fork’ on the top menu. Now you have your own copy of the Fiddle that you can edit.

In order to test our new Firebase application, we need to configure our ‘client-side’ code in JSFiddle to work with our new ‘server-side’ application through the Firebase API (application program interface). The various Firebase-specific functions you see in the sample code like ‘firebase.auth().onAuthStateChanged’ are calling or making a client request to the Firebase server through its API. If you want to know more about API’s check out this quick read: What is an API? In English, please.

In order to use Google Firebase from our JSFiddle client, we need to grab a set of configuration parameters (including secure credentials) from our Google Firebase application. Go ahead and navigate back to the Google Firebase Console, and on the first page you see, click the red circular ‘</>’ icon (‘Add Firebase to your web app’) to get a copyable snippet of the project settings (see below):

Now, replace the like section in the HTML window of your JSFiddle- see the comments ‘ // Initialize Firebase’.

JS-fiddle-client

The simplest way to test your reconfigured JSFiddle is to try logging in with the user you created in the prior step- does it work? If not, verify that the staring code is working properly (with the previous configuration) and then double check your update of the configuration.

Exhibit B’: Reminder on Finding Console Output in JSFiddle

The ‘console’ is basically a place you can see statements that Javascript sends there, which, as I mentioned, is a very common thing for JS coders to do. Recently, JSFiddle made a change where they implement the console inside the Fiddle itself. I prefer the native Chrome Console, and that’s what the balance of this case (and related cases) shows. However, this is not currently the default in JSFiddle. Once you open the sample code in JSFiddle, you’ll need to:
1: Click ‘Settings’ in the upper right
2: Disable the option ‘Console in the editor’

js-fiddle-ugh.001From there, to see the console  in Chrome just right click within the browser and click ‘Inspect’. Now in the top of menu of the frame that appears, click ‘Console’. You’re there. For more, see this tutorial: The Console in Chrome.

Exhibit C: Key JS Concepts and Techniques

There’s a little bit more going on in this sample code vs. the last case you saw (Automating Your Grunt Work with Javascript). You’ll notice that just handling the cases around user log in, sign up, and password recovery takes more than a few lines of code. Both to anchor your foundation understanding and to make sure you’re able to work effectively with the code, this appendix will briefly introduce two concepts: asynchronous execution and the observer pattern. If you want more depth on the topics, the explanations below provide references. My only caution is that you make sure to manage your time to complete the assignment itself because full coverage of these topics is fairly involved.

Asynchronous Execution

In the cases you’ve seen, the team is building an interactive webpage. The user’s browser requests the assets of the page and those are then presented to the user- as quickly as possible. These assets include items like HTML that lays out the page (with the help of CSS), media (images, video), and Javascript code that may help set up the page or deliver on-page interactions.
Let’s take the code you worked with in Making Stuff Happen with Javascript as an example. The actions that page’s Javascript needs to execute don’t happen in a single, serialized order. For example, after the page loads, the user can filter the various parts as part of their search (this is the code you worked with in the case). It wasn’t very relevant to the case and so probably wasn’t apparent to you that this block of code:
goButton.addEventListener('click', filterParts);
would execute ‘asynchronously’, but given that the user might initiate this code at any time and on several occasions, it can’t just be part of a single sequence that runs from a to z and then is done. For example, if you added this line of code at the very end of the Fiddle:
console.log(‘I’m the end of the line…Or am I?’);
you’d see that console statement before any of the console statements in the code related to clicking the search/Go button.

This asynchronous execution happens through the use of ‘callback functions’, which is when you pass a function to a function. If that sounds strange, take heart- you’ve already worked with them. In the code block above, we passed passed a function to the click event on the search/Go button. That’s the code that deals with executing on the filter inputs the user selects. Your browser moves on from that line of code (to, say, our hypothetical new console statement) once it’s read in all that code- but it won’t take the action of performing the filter until the click event. All it initially does is load the code and starts ‘listening’ for that click event- more on that in the section on the Observer pattern below.

This works well for our current purposes, but what if you need to react to the results of one of those asynchronous calls? You can’t just add code after the function like you would if you have a very procedural set of code that runs once from a-z. For example, when a user submits a password reset request, if there’s no error we want to suggest they check their email and proceed to log in, but if there is an error, we want to explain it to them and suggest that maybe they still need to register. In the recover_password function, you’ll see:
function recover_password() {
//(various things to send the email and let the user know about that omitted)
}).catch(function(error) {
//(various things to let the user know about an error (if there is one) and provide guidance about what to do)
});

You’ll see that pattern a few places in the code and it’s important for case handling after an asynchronous function finishes and returns.

If you’re interested in more examples and depth, this is a pretty good introductory post: Introduction to asynchronous JavaScript.

The Observer Pattern

The code that’s listening for that button click (search/Go) uses what’s called the observer pattern. The button with ID ‘#go-btn’ is what’s known as the subject and the function it calls (filterParts) is coded to observe the click event and then execute itself.
goButton.addEventListener('click', filterParts);
Another example you’ll see in the current Fiddle is the onAuthStateChanged function:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
//(various things we want to do if there’s a user logged in like change the upper right text from ‘Log In’ to ‘Log Out’)
} else {
//(various things we want to do if there’s isn’t a user is logged in)
}
});

This is an important pattern because it turns out, particularly in the kind of work we’re doing where there are a lot of on-page events, the situation where there’s a certain event (often user-generated) and you want to then trigger various actions is quite common. For more on this, here’s a quick set of notes: Observer Pattern.

Exhibit D (Supplemental): The JS ‘SPA’ Framework- React and Angular

SPAs, short for “single page apps”, are the most recent large development in JS and its ubiquity for the creation of user interfaces. If you’ve heard of the programming frameworks Angular or React, these are JS SPA frameworks principally maintained by two of the largest tech org’s: Google and Facebook (now Meta), respectively. These frameworks dealt with the need to more elegantly manage user interactions with a single page.

SPA-breakdown

The JS code handles all the various state changes that might need to happen as the user decides whether they want to log in, register, or retrieve their password, if they forgot it. The ‘plain’ JS code that does this is kind of long and awkward. For each of the transitions above (ex: from what you see for ‘Log In’ to what you’d see for ‘Register’), there’s a block of code that essentially says:
1. hide the other forms
2. show the form in question (ex: Register)
SPA frameworks like AngularJS or React offer a more structured approach to dealing with coding jobs like this, among others.

Through the reuse and abstraction of View components, React makes this kind of code easier to create and maintain. Just to give you a general sense of how this works, the following starter HTML and JS code produces a simple “Hello, world!’ on a web page:

//The Starter HTML
<div id="root">
<!-- This element's contents will be replaced with your component. -->
</div>

//The React JS
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<h1>Hello, world!</h1>);

The first line of JS creates a ‘root’ or starter component for this simple page by going and finding the existing HTML with the ID ‘root’. The second line then instructs the element with that ID (a div) to take on and post to the View an H1 with the text “Hello, world!”. Many teams find this approach to coding both their Views and the UI or ‘front’ Controllers preferable to the alternative of having larger, stand-alone files with HTML and CSS that Controllers then manipulate.