Build a Serverless Web App with Firebase - GSP643

Build a Serverless Web App with Firebase - GSP643

Overview

Twelve years ago, Lily started the Pet Theory chain of veterinary clinics. The Pet Theory chain has expanded rapidly over the last few years. Their old appointment system is not able to handle the increased load or allow clients to schedule their own appointments, so Lily asked Patrick, in IT, and Ruby, a consultant, to build a cloud-based system that easily scale. In this lab you will build a fully fledged Firebase web app that allows users to log information and schedule appointments in real time.

Architecture

This diagram gives you an overview of the services you will be using and how they connect to one another:

Architecture diagram

Objectives

In this lab, you will learn how to:

  • Configure Firestore Security to automate server-side authentication and authorization.

  • Add Google sign-in to your web app.

  • Configure your database so users can add their contact information.

  • Explore and deploy code that allows users to schedule appointments.

  • Explore Firebase's real time updates in your web app.

Prerequisites

This is a intermediate level lab. This assumes familiarity with the Cloud Console and shell environments. Experience with Firebase will be helpful, but it is not required. Before taking this lab it is recommended that you have completed the following lab:

You should also be comfortable editing files. You can use your favorite text editor (like nano, vi, etc.) or you can launch the code editor from Cloud Shell, which can be found in the top ribbon:

Open Editor button

Once you're ready, scroll down and follow the steps below to setup your lab environment.

Task 1. Provisioning the Firebase environment

Ruby sends Patrick an email:

Ruby, Software ConsultantHi Patrick,
Patrick, IT AdministratorHi Ruby,
Ruby, Software ConsultantHi Patrick
Patrick, IT AdministratorHi Ruby

Ruby sends Patrick some background information in an email, and they hold a meeting to work out the key activities. From this meeting they determine that he needs to:

  • Add the Firestore CLI to the Google Cloud project.

  • Configure a Firebase project.

  • Establish security policies.

Next, help Patrick accomplish these tasks.

Task 2. Install the Firebase CLI

Note:
The development environment has been preconfigured with Firebase Tools.

  1. Copy the IDE link from the Lab Details panel and paste it into a new browser tab to open Cloud Code.

  2. Open a terminal to access the command line. In the left panel, click the Application menu () > Terminal > New terminal.

  3. Clone the GitHub repository from the command line:

     git clone https://github.com/rosera/pet-theory.git
    
  4. In the left panel, click the Explorer icon, and then Open Folder > pet-theory > lab02. Click OK.

  5. If you get pop-up Do you trust the authors of the files in this folder? then check the box and click Yes, I trust the authors.

  6. Open a terminal again by clicking the Application menu () > Terminal > New terminal.

  7. Install the necessary node packages:

     npm i && npm audit fix --force
    

    Output:

     + firebase-tools@10.7.0
     added 3 packages from 11 contributors, removed 1 package and updated 8 packages in 79.808s
    

You are now ready to register a Firebase application.

Task 3. Register your app

Use an incognito window to open the Firebase Console url. If required enter the username as student-04-d9b226531981@qwiklabs.net and password as wUr7I5mwaI4R.

From the Firebase console select the project labelled qwiklabs-gcp-02-3aa62b0dc4a9.

If you close that page, you open another incognito tab and use the following link to the Firebase Console.

  1. Select the web icon (highlighted below) from the list of "Get started by adding Firebase to your app" icons:

Web icon highlighted

  1. When prompted for an "App nickname", type in Pet Theory.

  2. Then check the box next to "Also set up Firebase hosting for this app".

  3. Click the dropdown featuring the PROJECT_ID

  4. Select the Create a New Site option and amend the value as follows:

     student-project-qwiklabs-gcp-02-3aa62b0dc4a9
    
  5. Click on the Register app button.

  6. Click Next > Next > Continue to console. You should now be on the following page:

Choose a product to add to your app

You have now configured Firebase for the project. Next, you will initialize the project to reference your Firebase host.

Test completed task

Click Check my progress to verify the objective.

Register your app

Check my progress

Task 4. Authenticate to Firebase and Deploy

Use the IDE to connect to Firebase and deploy your application. Type the commands in the terminal available in the editor.

  1. Authenticate to Firebase:

     firebase login --no-localhost
    
  2. Enter in Y if asked if Firebase can collect error reporting information and press Enter.

  3. Copy and paste the URL generated in a new incognito browser tab and press Enter (directly clicking on the link results in an error).

  4. Select your labs account and then click Allow. Click on Yes, I just ran this command to proceed, then confirm your session ID by clicking Yes, this is my session ID. You will then be given an access code:

  5. Copy the access code, paste it in the Cloud Shell prompt Enter authorization code:, and press Enter. You should receive output similar to the following response:

    Output:

    Success! Logged in as gcpstaging86673_student@qwiklabs.net
    
  6. Now initialize a new Firebase project in your current working directory:

     firebase init
    

Running this command will step you through setting up your project directory and Firebase products.

  1. You will be asked to select the Firebase CLI features you want set up in this folder. Use the arrow keys and the spacebar to select Firestore and Hosting. Ensure your shell matches the following and then hit Enter:

     ? Which Firebase CLI features do you want to set up for this folder? Press Space to select features, then Enter to confirm your choices.
      ◯ Realtime Database: Configure a security rules file for Realtime Database and (optionally) provision default insta
      ◉ Firestore: Configure security rules and indexes files for Firestore
      ◯ Functions: Configure a Cloud Functions directory and its files
     ❯◉ Hosting: Configure files for Firebase Hosting and (optionally) set up GitHub Action deploys
      ◯ Hosting: Set up GitHub Action deploys
      ◯ Storage: Configure a security rules file for Cloud Storage
    
  2. Then run through the rest of the steps to configure Firebase:

    • Key down to Use an existing project and press Enter.

    • Select your Qwiklabs Project ID from the list (it's the one that starts with "qwiklabs-gcp-") then Enter.

    • Press Enter and then N to keep your firestore.rules file.

    • Press Enter and then Y to keep your firestore.indexes.json file.

    • Press Enter to keep your public directory and then N to disallow rewrites to your /index.html file.

    • Press Enter to Set up automatic builds and deploys with GitHub? and press N.

    • Enter in N when prompted to overwrite your 404.html file.

    • Enter in N when prompted to overwrite your index.html file.

You should receive the following output:

Wrote public/404.html
    ✔  Wrote public/index.html

    i  Writing configuration info to firebase.json...
    i  Writing project information to .firebase...
    i  Writing gitignore file to .gitignore...

    ✔  Firebase initialization complete!

The local configuration is now complete. Now the database authentication step is required to provide access between the services.

Task 5. Set up authentication and a database

Return to the Firebase Console to complete this step.

  1. Click on the Project Overview button in the left-hand navigation menu.

  2. Select Authentication tile and then click on Get Started:

  3. Click on Sign-in method and then, click on the Google item.

  4. Click the enable toggle in the top right corner and for the Support email for project select your lab account from the drop down list. Your page should now resemble the following:

    Enable toggle highlighted and Project support email dropdown menu

  5. Once you have verified the above, click on the Save button.

You have now set up Firestore authentication. In the following step you will work on hosting the application with Firebase.

Test completed task

Click Check my progress to verify the objective.

Set up authentication and a database

Check my progress

Task 6. Scenario: set up the application

You have assisted Patrick in setting up a working Firebase hosting environment where a web developer can deploy their code. However, Patrick has never enabled Firebase authentication nor has he deployed code to Firebase, so he emails Ruby for some help...

Patrick, IT AdministratorHey Ruby,
Ruby, ConsultantHi Patrick,
Patrick, DevOps EngineerHi Ruby
Ruby, ConsultantHey Patrick
Patrick, IT AdministratorHi Ruby

Now that Patrick has a better understanding of what is required, you will help him deploy Pet Theory as a Firebase application.

Return to the Terminal for this step. Ensure you are still in the pet-theory/lab02 folder.

  1. Run the following command to deploy your firebase application:

     firebase deploy
    

    Output:

    Deploy complete!
    
     Project Console: https://console.firebase.google.com/project/qwiklabs-gcp-7d652f8cf1f91cce/overview
     Hosting URL: https://qwiklabs-gcp-01-8be196f95006.web.app
    
  2. Copy the hosting URL (should resemble [PROJECT-ID].web.app) and open it in a new tab.

  3. Click on the Sign in with Google button:

    Note:
    You see a browser is not supported or 3rd party cookies and data may be disabled error, make sure to enable cookies in your browser.

    Third-party cookies error message

    This can be done in Chrome by clicking the eye icon at the far right of the url tab and following the blue links in the popup. Click on the site not working? link to update your browser settings to accept cookies.

  4. Login with your Qwiklabs account i.e. USERNAME. The following page opens:

    Profile page

    Note:
    Managing passwords is a difficult task and could expose your company to additional risk. Also, users don't want to create yet another user id and password.
    A small company like Pet Theory doesn't have the resources or requisite skill set to do this.
    In this instance it is much better to let the application users log in with their existing Google account (or any other identity providers)!

You have now deployed code to let users use Google authentication to access the appointments app.

Task 7. Add a customer page to your web app

Return to the Terminal and use the editor to view the files in the public folder.

  1. Open the customer.js file and copy and paste the following code:

     let user;
    
     firebase.auth().onAuthStateChanged(function(newUser) {
       user = newUser;
       if (user) {
         const db = firebase.firestore();
         db.collection("customers").doc(user.email).onSnapshot(function(doc) {
           const cust = doc.data();
           if (cust) {
             document.getElementById('customerName').setAttribute('value', cust.name);
             document.getElementById('customerPhone').setAttribute('value', cust.phone);
           }
           document.getElementById('customerEmail').innerText = user.email;
         });
       }
     });
    
     document.getElementById('saveProfile').addEventListener('click', function(ev) {
       const db = firebase.firestore();
       var docRef = db.collection('customers').doc(user.email);
       docRef.set({
         name: document.getElementById('customerName').value,
         email: user.email,
         phone: document.getElementById('customerPhone').value,
       })
     })
    
  2. Open the styles.css file and paste in the following code:

     body { background: #ECEFF1; color: rgba(0,0,0,0.87); font-family: Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 0; }
     #message { background: white; max-width: 360px; margin: 100px auto 16px; padding: 32px 24px 16px; border-radius: 3px; }
     #message h3 { color: #888; font-weight: normal; font-size: 16px; margin: 16px 0 12px; }
     #message h2 { color: #ffa100; font-weight: bold; font-size: 16px; margin: 0 0 8px; }
     #message h1 { font-size: 22px; font-weight: 300; color: rgba(0,0,0,0.6); margin: 0 0 16px;}
     #message p { line-height: 140%; margin: 16px 0 24px; font-size: 14px; }
     #message a { display: block; text-align: center; background: #039be5; text-transform: uppercase; text-decoration: none; color: white; padding: 16px; border-radius: 4px; }
     #message, #message a { box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); }
     #load { color: rgba(0,0,0,0.4); text-align: center; font-size: 13px; }
     @media (max-width: 600px) {
       body, #message { margin-top: 0; background: white; box-shadow: none; }
       body { border-top: 16px solid #ffa100; }
     }
    
  3. From the command line run the following command:

     firebase deploy
    

    Output:

    Deploy complete!
    
     Project Console: https://console.firebase.google.com/project/qwiklabs-gcp-7d652f8cf1f91cce/overview
     Hosting URL: https://qwiklabs-gcp-01-8be196f95006.web.app
    
  4. Go to your application tab and hard refresh the page with CMND+SHIFT+R (Mac) or CTRL+SHIFT+R (Windows). Simple refreshing will not display the needed updates. Enter some customer info—make up a name and phone number and click Save profile.

    Profile form

  5. Return to the Firebase Console and click Build > Firestore Database to view the profile information saved:

    Cloud Firestore, Data tabbed page

  6. Return to the web app page and click on the Appointments link. You will see a blank page since it has not deployed the appointments code yet.

Test completed task

Click Check my progress to verify the objective.

Add a customer page to your web app

Check my progress

Pretty cool! Firestore updates clients (web apps and native mobile apps) in real time, without the user having to refresh or reload.


Solution of Lab

curl -LO raw.githubusercontent.com/quiccklabs/Labs_solutions/master/Build%20a%20Serverless%20Web%20App%20with%20Firebase/quicklabgsp643.sh
source quicklabgsp643.sh