+ All Categories
Home > Software > Playing with Fire : Build a real-time application with Firebase

Playing with Fire : Build a real-time application with Firebase

Date post: 07-Apr-2017
Category:
Upload: michael-dowden
View: 73 times
Download: 0 times
Share this document with a friend
43
Copyright © 2017 Mx3 Studio 1 For this workshop you will need: A Google account A computer An editor of your choice (we will be using Atom) Git Node http://playingwithfire.live/ Playing With Fire
Transcript
Page 1: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio 1

For this workshop you will need:A Google accountA computerAn editor of your choice (we will be using Atom)GitNodehttp://playingwithfire.live/

Playing With Fire

Page 2: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Playing With FireMx3 Studio

2

Page 3: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Workshop ResourcesWebsite

http://playingwithfire.live/

Slack

https://playingwithfirelive.slack.com/messages/indy-code-2017

GitHub

https://github.com/Mx3-Studio/fireside/

3

Page 4: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

What is Firebase?●Real-Time Object Database with Advanced Permissions

●Authentication Service including OAuth providers

●File Storage with Permission Control

●Static hosting service

●Admin via web console, REST API, or command line

●Web, Android, and iOS application support

4

Page 5: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Workshop GoalsBuild real-time public chat application: Fireside Chat

Authenticate with OAuth

User Search and Private Messaging

Security controls on web, database, and storage

Firebase hosting and command-line interface

Add image upload backed by Firebase Storage

5

Page 6: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Who we are...Martine Dowden @Martine_DowdenUX Designer, Web Developer, Artist, AuthorTCC / Mx3 Studio / M2D2 / Andromeda / Eleven Fifty

Michael Dowden @mrdowdenSoftware Architect, Entrepreneur, Speaker, AuthorCSpring / Mx3 Studio / M2D2 / Andromeda / Eleven Fifty

Michael McGinnis @mybrokenwallsSoftware Engineer, Mobile Developer, MusicianCSpring / Mx3 Studio / Andromeda

6

Page 7: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Install PrerequisitesHomebrew (Mac)

Git

Node

Gulp

Bower

7

http://playingwithfire.live/#/systemSetup

Page 8: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Install & Test Starter App

8

$ git clone https://github.com/Mx3-Studio/fireside.git

$ cd fireside

$ npm install

$ bower install

$ gulp validate serve-dev

http://playingwithfire.live/#/systemSetup2

Page 9: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Firebase Console

9

Page 10: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 StudioCopyright © 2017 Mx3 Studio

Firebase Setup1. Set up a Firebase account:

https://console.firebase.google.com/

2. Create the Fireside project: “Fireside”

3. Load the starter database from starter-database.json

4. Edit firebase database rules

1010

{ "rules": { ".read": true, ".write": true }}

http://playingwithfire.live/#/gettingStarted

Page 11: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 StudioCopyright © 2017 Mx3 Studio

Firebase APIInitialization script

May use path notation to locate an object: /chats/-Kf9kfiG0rwnlB1gtquA

firebase

Database

Reference

AngularFire

1111

Fireside-73c10 { "chats" : { "-Kf9kfiG0rwnlB1gtquA" : { "content" : "Hey", "displayName" : "Martine Dowden", } }}

// reference to database root: /var db = firebase.database().ref();

// reference database objectsvar chatsRef = db.child('chats');var messageRef = chatsRef.child('-Kf9kfiG0rwnlB1gtquA');

// reference valuesVar messageContentRef = messageRef.child('content');

Page 12: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Firebase App Initialization1.Copy initialization script from Firebase Console

2.Paste configuration into FirebaseRef service

3.Return the database reference from FirebaseRef as “db”

4.Run the app and test http://localhost:8080/#/check

12

http://playingwithfire.live/#/gettingStarted3

Page 13: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 StudioCopyright © 2017 Mx3 Studio

Reading Data

13

// reference to database root: /var db = firebase.database().ref();

// reference to chatsvar chatsRef = db.child('/chats');

// readchatsRef.child('-Kf9kfiG0rwnlB1gtquA').once('value').then(function(snapshot) { var message = snapshot.val().content;});

// readvar data = $firebaseArray(chatsRef);

Fireside-73c10 { "chats" : { "-Kf9kfiG0rwnlB1gtquA" : { "content" : "Hey", "displayName" : "Martine Dowden", } }}

13

Page 14: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 StudioCopyright © 2017 Mx3 Studio

Advanced Read

14

$loaded()Returns a promise which is resolved

when the initial object data has been downloaded from the database. The promise resolves to the $firebaseObject itself.

As a shortcut, the resolve() / reject() methods can optionally be passed directly into $loaded():

14

var db = firebase.database().ref();

// firebase APIdb.on('value').then(function(data) { console.log(data);});

// AngularFire $loadedvar obj = $firebaseObject(db);obj.$loaded().then(function(data) { console.log(data === obj);});

Page 15: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Real-Time Chat: Display Messages

Display chat messages from Firebase

Update the ChatController to get the chat thread from the database/chats

Click on Hashtags to see only related chats

15

http://playingwithfire.live/#/realTimeChat

Page 16: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 StudioCopyright © 2017 Mx3 Studio

Writing Data

1616

Push● Generates a new child location

using a unique key and returns its Reference.

● Returns: non-null firebase.database.ThenableReference Combined Promise and Reference; resolves when write is complete, but can be used immediately as the Reference to the child location.

var myData = { content: 'Hello, World!', timestamp: Date.now()}

var db = firebase.database().ref();

var itemRef = db .child('/chats') .push(myData);

var itemId = itemRef.key;

itemRef.then(function(snapshot) { console.log(snapshot);});

Page 17: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 StudioCopyright © 2017 Mx3 Studio

Writing Data

1717

Set● This will overwrite any data at this

location and all child locations.● Returns: non-null firebase.Promise

containing void Resolves when write to server is complete.

var myData = { content: 'Hello, World!', timestamp: Date.now()}

var db = firebase.database().ref();

var itemRef = db .child('/chats') .child(chatId).set(myData);

itemRef.then(function(snapshot) { console.log(snapshot);});

Page 18: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 StudioCopyright © 2017 Mx3 Studio

Writing Data

1818

Update● Updates only the values provided

(Doesn’t replace the entire object)● Can be used to write multiple

values to the Database at once. (Shown on the next slide)

● Returns: non-null firebase.Promise containing void Resolves when update on server is complete.

var myData = { // content: 'Hello, World!', timestamp: Date.now()}

var db = firebase.database().ref();

// only update the timestampvar itemRef = db .child('/chats') .child(chatId).update(myData);

itemRef.then(function(snapshot) { console.log(snapshot);});

Page 19: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 StudioCopyright © 2017 Mx3 Studio

Advanced Write - Update

19

function newMultiUpdate(content, uid) { // Some content and a UID. var data = { content: content, uid: uid };

// Get a key for the new Muti Update. var newUpdateKey = firebase.database().ref().child('chats').push().key;

// Write the data simultaneously to more than one location var locations = {}; locations['/chats/' + newUpdateKey] = data; locations['/users/' + uid + '/' + newUpdateKey] = data;

return firebase.database().ref().update(locations);}

19

Page 20: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Real-Time Chat: Create MessagesCreate new chat messages

Modify the createChat function in ChatControllerGet a key for the new chat object/chats/{chatId}

Modify the createChat function to store the new chat messageAdd the reference to the updates array/chats/{chatId}

20

http://playingwithfire.live/#/realTimeChat

Page 21: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Intermission21

(5 Minutes)

Page 22: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 StudioCopyright © 2017 Mx3 Studio

Firebase Authentication

OAuth ProvidersGoogleFacebookTwitterGitHub

Username / PasswordAccount resetEmail verificationCredential protection

Anonymous Authentication

2222

// Firebase API OAuth Loginfirebase.auth().signInWithPopup('google').then(function(userCredential) { console.log(userCredential);});

// AngularFire OAuth Login$firebaseAuth().$signInWithPopup('google').then(function(user) { console.log(user);});

// AngularFire Logout$firebaseAuth().$signOut();

Page 23: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Adding Security: AuthenticationLogin using Google OAuth

Enable the Google Sign-in Provider from Firebase console

Implement methods in the FirebaseAuth service:authenticate()logout()

23

http://playingwithfire.live/#/security

Page 24: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 StudioCopyright © 2017 Mx3 Studio

Application Security

Firebase API currentUser property may be null if authentication is not yet complete (won’t automatically update)

AngularFire $getAuth synchronously retrieves the current authentication state of the client.

AngularFire $firebaseObject retrieves a single object from the given reference (instead of an array like $firebaseArray)

2424

var db = firebase.database().ref();var auth = firebase.auth();

// Current user from Firebase APIvar currentUser = auth.currentUser;

// Retrieve the User Authvar user = $firebaseAuth() .$getAuth();

// Load a user profilevar ref = db .child('/users').child(user.uid);var profile = $firebaseObject(ref);

Page 25: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 StudioCopyright © 2017 Mx3 Studio

AuthorizationAngularFire $waitForSignIn returns a

promise fulfilled with the current authentication state.

AngularFire $requireSignIn returns a promise fulfilled with the current auth (if currently authenticated), or rejects the promise otherwise.

2525

$routeProvider.when('/profile', { templateUrl: 'view/profile.html', controller: 'ProfileCtrl as vm', resolve: { user: ['$firebaseAuth', getUser] }});

function getUser($firebaseAuth) { return $firebaseAuth .$waitForSignIn();}

Page 26: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Adding Security: AuthorizationDisplay User Avatar and Display Name with Messages

Implement the getProfileByID method in Profile ServiceReturn the user profile from /users/{userId}/profile

Update the createChat method in the ChatControllerAdd user attributes to the chat object

Update the Routes to correctly resolve the currentUserOption on / and /hashtag/:hashRequired on /friends and /friends:friend

26

http://playingwithfire.live/#/security

Page 27: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 StudioCopyright © 2017 Mx3 Studio

Database Security{ "rules": { "check": { ".read": true, ".write": false }, "users": { "$user_id": { ".read": "$user_id === auth.uid", ".write": false, "profile": { ".read": true } } }}

2727

{ "check": { "status": "You are connected to the database" }, "users": { "3gtKgnNf1GbkVRaxnUmAPY1" : { "profile": { "name": "John Doe" } } }}

Page 28: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Adding Security: Database RulesPrevent unauthorized access to Firebase objects

Modify the database Rules in the Firebase console to reflect the following:

/check - anyone can read, no one can write/chats - anyone can read, must be authenticated to write/users/{userId} - a user can read and write their own object/users/{userId}/profile - anyone can read/profile - anyone can read or write

28

http://playingwithfire.live/#/security

Page 29: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Intermission29

(5 Minutes)

Page 30: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 StudioCopyright © 2017 Mx3 Studio

Firebase Query

30

Returns data from a database location that is ordered and filtered by one of the Firebase methods

.orderByChild()

specifies the child key to order the results by

.equalTo()

Return items equal to the specified key or value, depending on the order-by method chosen 30

var db = firebase.database().ref();query = '[email protected]';

db.child('profiles').orderByChild('email').equalTo(query));

Page 31: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Private Chat SearchSearch for friends by email address using a firebase query

Update the searchUsers method

Make sure the correct email returns and displays

31

http://playingwithfire.live/#/privateMessages

Page 32: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 StudioCopyright © 2017 Mx3 Studio

// Load Friends (list of IDs)var friends = $firebaseArray( firebase.database() .ref() .child('users') .child(currentUser.uid) .child('chats'));

// Load list of Profilesfriends.$watch(function (event) { // Get Profile for each Friend});

Advanced Read

32

$watch(callback, context)Registers an event listener which will

be notified any time there is a change to the data. Returns an unregister function that, when invoked, will stop notifying the callback of changes.

Unregister using unwatch();

32

Page 33: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Private Chat MessagesUpdating multiple places at once

Get the correct chat thread from the database

Watch the friends list for changes

Modify the database rules

33

http://playingwithfire.live/#/privateMessages

Page 34: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Firebase CLIinit to create the firebase.json and database.rules.json configuration

fileslogin to establish a session (may also logout)list and use to manage active projectserve to run locally and deploy to push to public serverMay import and export user accountsManipulate the database, including updates and queriesAllows script support for your maintenance and operations

34

Page 35: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Install Firebase CLI & Login

Copy database Rules from Firebase console to database.rules.json

Preview build using Firebase CLI

Deploy application to Firebase Hosting

Connect to Fireside through public Firebase URL

Deploy to Firebase Hosting

35

http://playingwithfire.live/#/deployToFirebaseHosting

Page 36: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Firebase HostingHosting configuration in firebase.json

Ignore paths that shouldn’t be hostedSpecify redirects including wildcards and parameter captureRewrite URLsAdd Headers

Hosting ConsoleCurrent versionDeploy historyEasily roll back versionAdd custom domainsSee Usage report

36

Page 37: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 StudioCopyright © 2017 Mx3 Studio

Firebase StorageUpload and share user generated

content, such as images and video

data is stored in a Google Cloud Storage bucket

Separate component of firebase APIfirebase.storage()Rules are managed separately

3737

var storage = firebase.storage().ref();

Page 38: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 StudioCopyright © 2017 Mx3 Studio

Firebase StorageRead

Metadata includes

Name

Size

content Type (MIME Type)

fullPath

downloadURLs

3838

// Create a reference to the file whose // metadata we want to retrievevar ref = firebase.storage().ref() .child('images/myMeme.png');

// Get metadata propertiesref.getMetadata().then(function(metadata) { // Metadata now contains the metadata // for 'images/myMeme.png'}).catch(function(error) { // Uh-oh, an error occurred!});

Page 39: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 StudioCopyright © 2017 Mx3 Studio

Firebase StorageWrite

Files / Blobsangular-file-model

https://github.com/ghostbar/angular-file-model

3939

// Create a root referencevar ref = firebase.storage().ref();

// Files & Blobsref.child('images').put(file).then(function(snapshot) { console.log('Uploaded a blob or file');});

Page 40: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Challenge: Add Images to ChatsEnable upload of images to Firebase Storage

Display uploaded images in the chat stream

Prevent unauthorized submission of imagesFirebase Storage Rules

Bonus: Delete Images

40

http://playingwithfire.live/#/challengesImages

Page 41: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Challenge: Deploy with CordovaRun in Browser with Cordova

Run in Android (or iOS) with CordovaMust install Android SDK or XCodeChallenge: Authentication with Popup or Redirect won’t work

41

http://playingwithfire.live/#/challengesCordova

Page 42: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Other Firebase FeaturesThree-way Form Binding with Angular JSCloud FunctionsCross PlatformFirebase Cloud MessagingMobile AnalyticsMobile Crash Reporting

42

Page 43: Playing with Fire : Build a real-time application with Firebase

Copyright © 2017 Mx3 Studio

Michael McGinnis@[email protected]

Playing With Fire

43

Michael Dowden@[email protected]

Martine Dowden@[email protected]

Mx3 Studio

http://playingwithfire.live/


Recommended