Firebase Web/Javascript Starter Lab  Note: Please do not edit this document.  Feel free to make your own copy if you wish to make changes or  customize the codelab for your event. 

  Introduction  Prep  Prerequisites  Sign up for Firebase  Send data to Firebase  Create the HTML Page  Begin Connecting to Our Firebase  Store an Object  Working with an Array of Objects  Getting Data Back from Firebase  Monitor Events  Polish  Optional steps  Make your Application available to everyone!  Authenticate Users  Secure (and validate) your Data  Resources and Further reading  License 

Introduction    This tutorial is adapted from ​ https://www.firebase.com/tutorial/#gettingstarted     In this lab we’re going to create our Firebase app ­ a chat application. We’re going to be using  HTML, plain Javascript and CSS to create our application.    Keep in mind that these aren’t our only options, we can also do the same thing in Objective­C or  Swift for iOS or Java for Android. Firebase also offers integration with popular frameworks such  as Angular, Ember, ReactJS and Ionic. Complete documentation is available from  www.firebase.com/docs​ .    To start we need to get a Firebase Account. No worries, Firebase accounts are free.    



Prep  Prerequisites     ● ● ● ●

You need to have an internet connection.  You need to have a browser  You need to have the ability to write HTML/JS/CSS  A text editor would help 

 

Sign up for Firebase     Go to ​ http://www.firebase.com​  and sign up.   

    Once you’ve done that a new development only Firebase will automatically be created for you.  It’ll be named ​ [PROJECTID].firebaseio.com​  and you’ll use this Firebase for the codelab (you  can of course chose to create a new one).   



Send data to Firebase  Create the HTML Page    Start with a relatively blank ​ index.html​  page:   ​ ​ Firebase Chat​




​/div> <  

  We’re now going to call the Firebase library by adding this to the head of the html document:  ​ Firebase Chat​  

  Note: you can get the latest version and changes of the Firebase JavaScript API here :  https://www.firebase.com/docs/web/changelog.html 

Begin Connecting to Our Firebase    Okay, we’re all set to start with what we have here, so let’s start by adding a reference to our  Firebase entry:   

  Now we want to capture the event when someone adds a message.  So I add an eventListener  to post button (and define a few shorthands for the UI controls):   var myFirebase = ​ new​Firebase(​ '​ https://[PROJECTID].firebaseio.com/​ '​ ); var usernameInput = document.querySelector(​ '#username'​ ); var textInput = document.querySelector(​ '#text'​ );



var postButton = document.querySelector(​ '#post'​ ); postButton.addEventListener(​ "click"​ , function() { }); 

  Now I need to grab the contents of the form and send them to Firebase:  postButton.addEventListener(​ "click"​ , function() { var username = usernameInput.value; var text = textInput.value; myFirebase.set(username + " says: " + text); textInput.value = ​ ""​ ; });

  Note that all of this JavaScript coding could be living in a separate JavaScript file referenced in  the HTML page but let’s try out what we have: 

  After pressing “Post” go to ​ https://[PROJECTID].firebaseio.com/​ . You should see something like  this: 

   

Store an Object    We stored a string version of message, but we should store it as an object, and leave the string  building to the client. So we change our code to:  var username = usernameInput.value; var text = textInput.value; myFirebase.set({username:username, text:text}); textInput.value = ​ ""​ ;



  Then fire off a new message in the client:

And the result in Firebase should look something like this:

  So as you see, we have just one value that we’re updating. Every time we do a ​ set​ , we’re just  overwriting that value to a different value.  What we really want for a chat app is a stream of  messages.  So we need to append the value instead of just setting and resetting it.  

Working with an Array of Objects    First though we should clear out what we have in Firebase already, so in the firebase interface  highlight the top­level node (“tpryan­chat” in the screenshot above) and an X will appear next to  it.  Click this X to clear out the data.     Now to add a record to a list, instead of updating we use the ​ push​  command:  var username = usernameInput.value; var text = textInput.value; myFirebase.​ push​ ({username:username, text:text}); textInput.value = ​ ""​ ;

  Reload the client, and add another message. And another. And one more. Looking at Firebase  you should see this: 



    You’ll notice that each record has a unique identity. This allows for the same values to come in  at the same time from different clients and still be recorded separately.   

Getting Data Back from Firebase  Monitor Events  Okay we’ve written to Firebase, but the real magic is in getting the info back. We’ll do this by  registering a listener to the ​ child_added​  event which is called with a snapshot of any data  added to Firebase:  myFirebase.on(​ 'child_added'​ , function(snapshot) { var msg = snapshot.val(); var html ​ =​​ '
'​​ + ''​​ ​ +​msg.username ​ +​​ ''​​ + '

'​​ ​ +​msg.text ​ +​​ '

'​​ + ​ ​ '
'​ ; document​ ​ .querySelector(​ "#results"​ ).innerHTML ​ +=​html; });

  Once you’ve added this code, reload your page in the browser, you should have something like  this: 



  Now going back to the earlier code for a minute, we probably want to protect ourselves from  XSS that a malicious user would want to throw our way before sending the data to Firebase :    var username = usernameInput.value; var text = textInput.value;

// basic and probably insufficient XSS protection // consider using document.createTextNode() instead username = ​ username​ .replace(/\/g, ​ ">"​ ); text = ​ text​ .replace(/\/g, ​ ">"​ ); myFirebase.​ push​ ({username:username, text:text}); textInput.value = ​ ""​ ;

Polish    That looks terrible, let’s add a bit of style before we continue:  ​ ​ Firebase Chat​  

  And we’re going to slightly tweak the javascript too:  var msg = snapshot.val(); var html ​ =​​ '
'​​ + ''​​ ​ +​msg.username ​ +​​ ''​​ + '

'​​ ​ +​msg.text ​ +​​ '

'​​ + ​ ​ '
'​ ; document​ ​ .querySelector(​ "#results"​ ).innerHTML ​ +=​html;

Now reload the front end, choose a different name, and send a new message: 

    Launch another browser window open to the page we’ve been playing with, and send a  message with your original name.  You should see both copies update in real time.    



    There, you’ve built your first chat client!   

Optional steps  Make your Application available to everyone!    So far we’ve been using the application locally. Wouldn’t it be nice to share this application with  other users? You could host your HTML pretty much on any server but here we’ll use Firebase’s  integrated hosting feature.    The Firebase CLI (Command Line Interface) requires, as a one­time setup, that you install  Node.js and npm. For that simply download Node.js from ​ https://nodejs.org​  and install it (this will  also install npm). Then install the CLI using this command:  $ npm install -g firebase-tools 

  Then simply issue this one­time command from the directory holding your HTML file:  $​ firebase init Initialization Warning - Creating new firebase app inside a non-empty directory. Please sign into your Firebase account to continue...



Email: [email protected] Password: xxx ---------------------------------------------------Your Firebase Apps [email protected] --------------------------------------------------- ---------------------------------------------------Enter the name of the Firebase app you would like to use for hosting Firebase app​ ---------------------------------------------------Site URL: https://.firebaseapp.com ---------------------------------------------------Enter the name of your app's public directory. (usually where you store your index.html file) Public Directory​(current directory) Initializing app into current directory... Writing firebase.json settings file... Successfully initialized app To deploy: ​ firebase deploy

  Note how the domain for the hosted project is now firebaseapp.com. The final step is to actually  deploy the application:  $​ firebase deploy Public Directory: ​ /path/to/html Preparing to deploy Public Directory... Uploading 2 files with total compressed size = 1.14 kB progress: 100% Successfully deployed Site URL: https://.firebaseapp.com, or use ​ firebase open

  You can now share your chat application with your friends!    Any local changes you make to the application will only require a new ​ firebase deploy​  for the  modification to be pushed live.     Of course you can deploy this HTML file anywhere you’d like, this is just one (simple) option.  The command­line tool used for hosting Firebase application is documented here:  https://www.firebase.com/docs/hosting/command­line­tool.html 

Authenticate Users    Let’s now offer the users the ability to sign­in with their Twitter account. This requires a few  changes to the layout of our page. First replace the username input element by a login 

 

Next we need to allow our Firebase application and Twitter to know about each other. This is a  one­time, two­step process:    1. create a twitter application​  at ​ https://apps.twitter.com/​  with:  a. your name,  b. a description for the app,  c. web site (​ https://.firebaseapp.com​ ),  d. and https://auth.firebase.com/v2//auth/twitter/callback​  as the  Callback URL.    2. Enable Twitter Authentication for your Firebase application in the “Login and Auth”  section and configure the ​ Twitter API Key and Secret​  obtained in step #1 : 

If you’d rather use Google as the identity provider, the steps are very similar and detailed here:  https://www.firebase.com/docs/web/guide/login/google.html​ .    Let’s finally add the code to authenticate users with Twitter by writing only client­side code. 

11 

First, we’ll replace the ​ usernameInput​  field with a login button. Upon successful login, the  button’s content is set to the user’s handle and the button is disabled. Note also that the ​ post  button is now disabled until the user has successfully logged in:

 

  A ​ username​  variable is set for the duration of the user session (a page reload will require to  re­authenticate as we’ll see later) and we also create the shorthand for the ​ loginButton​ : var myFirebase = new Firebase(​ 'https://[PROJECTID].firebaseio.com/'​ ); var username = null; var loginButton = document.querySelector(​ '#login'​ ); var textInput = document.querySelector(​ '#text'​ ); var postButton = document.querySelector(​ '#post'​ ); 

  Now add an event listener to the login button that will trigger the authentication flow and on  successful completion store the ​ username​ :  loginButton.addEventListener(​ "click"​ , function() { myFirebase.authWithOAuthPopup(​ "twitter"​ , function(error, authData) { if (!error) { username = ​ "@"​+ authData.twitter.username; postButton.textContent = ​ "Post as "​+ username; postButton.disabled = false; } }, {remember: ​ "none"​ } ​ // will end authentication on page close ); });

Note you might find ​ remember: "none"​ to be annoying as it requires login in on every page reload. Feel free to remove it or to use ​ remember: "sessionOnly"​ instead. Finally, the part of the code that updates the UI should now be placed in the ​ onAuth() callback. Here is the full code:  myFirebase.onAuth(function(authData) { if (authData) { ​ // user has authenticated myFirebase.on(​ 'child_added'​ , function(snapshot) { var msg = snapshot.val(); var html ​ =​​ '
'​​ + ''​​ ​ +​msg.username ​ +​​ ''​​ + '

'​​ ​ +​msg.text ​ +​​ '

'​​ + ​ ​ '
'​ ; document​ ​ .querySelector(​ "#results"​ ).innerHTML ​ +=​html; }); } });

12 

Deploy now your modified HTML with ​ firebase deploy​ . You should now require users to login  with Twitter before they can post. Their content is now associated with their twitter handle. 

  Firebase offers multiple user authentication mechanisms, from identity providers such as  Twitter, Facebook, Google or GitHub to old­style email & password and even custom JSON  Web Token­based login. Firebase User Authentication is fully documented here:  https://www.firebase.com/docs/web/guide/user­auth.html   

Secure (and validate) your Data    Other than the simple HTML escaping code we’ve added, users are able to enter anything. Let’s  limit the message size to 42 characters by adding a validation rule in the Firebase dashboard : 

13 

Also, so far, any application pointing to your firebase (the [PROJECTID].firebaseio.com URL)  can read and write any data.  We’ll add a simple set of rules to allow reading and writing data  only if the user is authenticated. This should also prevent un­authenticated users to see the  content of the chat as it is the case in the previous step.   

{ "rules": { ".read": ​ "auth != null", ".write": ​ "auth != null" } }   In addition to ​ .read​  and ​ .write​  rules, you can implement validation rules using ​ .validate​ . This  can for instance help you limit the length of a message using the ​ newData ​ predefined variable  like this:   

"$messageID": { "text" : { ".validate": "newData.isString() && newData.val().length < 42" } }   … where ​ $messageID​  is a reference to the unique message IDs.    It’s probably also a good idea to add a constraint to the HTML control itself :

 

  Another useful validation rule would be to check for a user’s credentials and to make sure the  message is indeed from who it says it is. And while we’re at it we could also make sure the  payload has ​ text​  and ​ username​  fields. Here’s how to do that :   

"$messageID": { ".validate": "newData.hasChildren(['text', 'username'])"​ , "text" : { ".validate": "newData.isString() && newData.val().length < 42" }, "username" : { ​ ".validate": "(newData.val() == auth.twitter.username)" } }

14 

  Security and Firebase Rules are documented here:  https://www.firebase.com/docs/security/guide/securing­data.html     

Resources and Further reading    ● ● ●

Firebase Documentation: ​ https://www.firebase.com/docs   Fully functional chat application built with Twitter auth, bootstrap and jQuery:  https://github.com/jwngr/gdg­summit/tree/master/chat   Firebase Presentation slides: ​ https://github.com/jwngr/gdg­summit  

 

License    This work is licensed under a Creative Commons Attribution 2.0 Generic License. 

15 

Firebase Web/Javascript Starter Lab Introduction -

Swift for iOS or Java for Android. Firebase also offers integration with popular frameworks such as Angular, Ember, ReactJS and Ionic. Complete documentation ...

688KB Sizes 0 Downloads 243 Views

Recommend Documents

Firebase Web/Javascript Starter Lab Introduction -
Swift for iOS or Java for Android. Firebase ... Page 3 ... We're now going to call the Firebase library by adding this to the head of the html document: .... XSS that a malicious user would want to throw our way before sending the data to Firebase :.

Introduction to Lab 2
Sep 15, 2010 - http://www.it.uu.se/edu/course/homepage/realtid/ht10/lab2. Lab report ... Based on OSEK (industry standard for automotive embedded systems).

Introduction to Lab 2 (LEGO)
Sep 15, 2010 - Flash the custom firmware ... Custom FW using fwflash-jh. ▻ Original FW using fwflash- .... Application: Distance and touch sensor sensing. 1.

HomeAway - Firebase
Building upon that idea, the team also wanted to deliver this experience in areas with no Internet connection. Finally, they wanted to do all this without the usual ...

Introduction-To-Networks-Lab-Manual-V5-1-Lab-Companion.pdf ...
3. Page 3 of 3. Introduction-To-Networks-Lab-Manual-V5-1-Lab-Companion.pdf. Introduction-To-Networks-Lab-Manual-V5-1-Lab-Companion.pdf. Open. Extract.

Fabulous - Firebase
increased by 10% with. App Invites vs. standard SMS. & email share options. 2x higher retention for users acquired via App Invites vs. other channels (including organic). *30-day averages. “It took me only a few hours to implement App Invites vs. s

25% 24% - Firebase
Page 1. Rockbite boosts revenue up to 25% with Firebase Predictions. Introduction. Rockbite Games, a fast-growing game development company based in. Armenia, is the creator of popular app titles like Deep Town. With more than five million users all o

lab 1: introduction to programming
looping is fundamental to programming. Java provides three types of loop statements: while loops, do-while loops, and for loops. LAB SHEET 4.1: The while Loop. ESTIMATED TIME ... get the correct output. CONCLUSION. : The while loop checks the loop-co

Google Patent Starter Program
great ideas, the passion and the long hours that develop them, and the resulting ... Program, which offers eligible startups and developers the following benefits:.

Halfbrick uses Firebase Predictions to boost ... - Firebase
Based on the results of the experiment, we decided to roll-out the in-game promotion to our entire user base. Now, any user that Predictions identifies as 'will churn' receives a gift of 2000 gold coins and 25 gacha tokens. We can't wait to test. Pre

Auger Labs - Firebase
Company. Auger ( www.augerlabs.com ) is a mobile apps-as-a-service company for the art community. Artists receive their own beautifully designed, ...

66%+ 2x - Firebase
company hopes to one day make it available to the general public. Challenge ... Using Cloud Firestore's data structure and client libraries, HomeAway set up the infrastructure within a few minutes and delivered a real-time user experience ...

The Guardian - Firebase
On Android, Google will also surface install buttons for users who do not yet have your app installed. Learn how to get your app into the Google index at g.co/ ...

Hawkin Dynamics - Firebase
Internet-connected force plates collect athletes' data, which is then analyzed ... company serves customers in the NHL, NCAA, EPL and other leagues. Challenge ... With Firebase Realtime Database, we felt we had built the best force-plate.

Cookpad - Firebase
by 10%. Search results page. “App Indexing has been a great way for us to get more of our users using ... On Android, Google will also surface install buttons for ...

Tabelog - Firebase
about 10%. In-app deep link. “We feel that with App Indexing becoming ... On Android, Google will also surface install buttons for users who do not yet have your.

25% 24% - Firebase
Introduction. Rockbite Games, a fast-growing game development company based in. Armenia, is the creator of popular app titles like Deep Town. With more than five million users all over the world, the Rockbite team is dedicated to providing high-quali

66%+ 2x - Firebase
app events. Many companies use multiple layers of software to meet ... also wanted to deliver this experience in areas with no Internet connection. Finally, they ...

66%+ 2x - Firebase
million places to stay in 190 countries. To help travelers get the best experience at their destinations, the HomeAway mobile group formed a ... company hopes to one day make it available to the general public. Challenge. Developing apps for ...

25% 24% - Firebase
Town, their latest mobile game for Android and iOS, they implemented two monetization models: in-app purchases and in-app ads. First, they enabled in-app purchases within a digital store so that users could buy in-game currency such as crystals and c

AliExpress - Firebase
in search impressions and 30-40% increase in clicks for eligible searches on Android when the user has the app installed. Compared to mobile website users,.

24% 14% 85K - Firebase
In January 2015, they launched their mobile app, which provides quick, inexpensive ... campaign performance and user activity across iOS and Android devices.

Starter & Legendary Guide.pdf
There was a problem previewing this document. Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item.

Starter & Legendary Guide.pdf
TORCHIC BULBASAUR TOTODILE CHARMANDER. Level 10 Level 10 Level 10 Level 10. Fire Grass / Poison Water Fire. Available as. Combusken in Route 6.