Table of contents
- Overview
- Objectives
- Task 1. Provisioning the Firebase environment
- Task 2. Install the Firebase CLI
- Task 3. Register your app
- Task 4. Authenticate to Firebase and Deploy
- Task 5. Set up authentication and a database
- Task 6. Scenario: set up the application
- Task 7. Add a customer page to your web app
- Solution of Lab
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:
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:
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 Consultant | Hi Patrick, |
Patrick, IT Administrator | Hi Ruby, |
Ruby, Software Consultant | Hi Patrick |
Patrick, IT Administrator | Hi 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.
Copy the IDE link from the Lab Details panel and paste it into a new browser tab to open Cloud Code.
Open a terminal to access the command line. In the left panel, click the Application menu () > Terminal > New terminal.
Clone the GitHub repository from the command line:
git clone https://github.com/rosera/pet-theory.git
In the left panel, click the Explorer icon, and then Open Folder > pet-theory > lab02. Click OK.
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.Open a terminal again by clicking the Application menu () > Terminal > New terminal.
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.
- Select the web icon (highlighted below) from the list of "Get started by adding Firebase to your app" icons:
When prompted for an "App nickname", type in Pet Theory.
Then check the box next to "Also set up Firebase hosting for this app".
Click the dropdown featuring the PROJECT_ID
Select the Create a New Site option and amend the value as follows:
student-project-qwiklabs-gcp-02-3aa62b0dc4a9
Click on the Register app button.
Click Next > Next > Continue to console. You should now be on the following page:
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.
Authenticate to Firebase:
firebase login --no-localhost
Enter in Y if asked if Firebase can collect error reporting information and press Enter.
Copy and paste the URL generated in a new incognito browser tab and press Enter (directly clicking on the link results in an error).
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:
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
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.
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
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.
Click on the Project Overview button in the left-hand navigation menu.
Select Authentication tile and then click on Get Started:
Click on Sign-in method and then, click on the Google item.
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:
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 Administrator | Hey Ruby, |
Ruby, Consultant | Hi Patrick, |
Patrick, DevOps Engineer | Hi Ruby |
Ruby, Consultant | Hey Patrick |
Patrick, IT Administrator | Hi 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.
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
Copy the hosting URL (should resemble
[PROJECT-ID].web.app
) and open it in a new tab.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.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.
Login with your Qwiklabs account i.e.
USERNAME
. The following page opens: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.
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, }) })
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; } }
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
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.
Return to the Firebase Console and click Build > Firestore Database to view the profile information saved:
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