Firebase by Google Alexandru Toprceanu , Claudiu Groza , - - PowerPoint PPT Presentation

firebase
SMART_READER_LITE
LIVE PREVIEW

Firebase by Google Alexandru Toprceanu , Claudiu Groza , - - PowerPoint PPT Presentation

Firebase by Google Alexandru Toprceanu , Claudiu Groza , Universitatea Politehnica Timioara Intuitive Software Agenda What is Firebase? What features does it offer? What platforms does it support? Overview of real-time


slide-1
SLIDE 1

Firebase

Alexandru Topîrceanu, Universitatea Politehnica Timișoara

by Google

Claudiu Groza, Intuitive Software

slide-2
SLIDE 2

Agenda

  • What is Firebase?
  • What features does it offer?
  • What platforms does it support?
  • Overview of real-time database
  • Support for user authentication (client vs. server)
  • Overview of storage
  • Database and Storage Rules
  • Notifications
  • Integration in academia: Agora & student projects
  • Integration in industry: Canvy
  • Why choose it over other backend solutions?
  • Overview towards future
slide-3
SLIDE 3

What is Firebase?

Mobile platform that helps you quickly develop apps, grow your user base, and earn more money. Firebase is made up of complementary features that you can mix to fit your needs.

slide-4
SLIDE 4

What features does it offer?

  • Analytics
  • Development

○ Cloud messaging ○ Authentication ○ Realtime database ○ Storage ○ Hosting, Test lab, Crash reporting

  • Growth

○ Remote config, Notifications, App indexing, Dynamic links, Invites

  • Earning - AdMob
slide-5
SLIDE 5

What platforms does it support?

iOS Android Web Online documentation, Code lab, API reference, Samples

  • C++ (native Android)
  • Unity (beta)
  • Firebase Admin SDK (Node.js, Admin Java SDK)
slide-6
SLIDE 6

Realtime database

A cloud-hosted NoSQL database Data is:

  • stored as JSON
  • synced across devices in a matter of ms
  • available when the app goes offline

Console

slide-7
SLIDE 7

Realtime database. How does it work?

Data is persisted locally. Even while offline, realtime events continue to fire, giving the end user a responsive experience. Conflicts are merged automatically when connectivity is regained. NoSQL database with different optimizations and functionality compared to a relational database => structure data accordingly

slide-8
SLIDE 8

Realtime database. Structuring data

{ // bad structure "chats": { "one": { "title": "Historical Tech Pioneers", "messages": { "m1": { "sender": "ghopper", "message": "Relay malfunction found. Cause: moth." }, "m2": { ... }, // a very long list of messages } }, "two": { ... } } }

  • E.g. to get list of chat titles (threads): iterate all data (members, messages)
slide-9
SLIDE 9

Realtime database.

{ // better structure "chats": { "one": { "title": "Historical Tech Pioneers", "lastMessage": "ghopper: Relay malfunction found. Cause: moth.", "timestamp": 1459361875666 }, "two": { ... }, "three": { ... } }, // members info "members": { "one": { "ghopper": true, "alovelace": true, "eclarke": true }, "two": { ... }, "three": { ... } }, // messages info "messages": { "one": { "m1": { "name": "eclarke", "message": "The relay seems to be malfunctioning.", "timestamp": 1459361875337 }, "m2": { ... }, "m3": { ... } }, "two": { ... }, "three": { ... } } }

  • Get list of chats (titles)
  • Members in each chat
  • Message thread for each chat
slide-10
SLIDE 10

Realtime database. Set data and listen for changes

Three types of listeners:

  • ValueEventListener: returns all data below node
  • SingleValueEventListener: returns all data below node, once
  • ChildEvenentListener : returns only modified child node under current node

Database reference: node on which R/W operations can be done

databaseRef.child(“messages”).child(“one”).child(“m1”).child(“message”)

slide-11
SLIDE 11

Realtime database. Set data and listen for changes

Listening for changes in a node

ValueEventListener msgListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Get Post object and use the values to update the UI Message msg = dataSnapshot.getValue(Message.class); // ... } @Override public void onCancelled(DatabaseError databaseError) { // Getting Message failed, log a message Log.w(TAG, "loadMessage:onCancelled", databaseError.toException()); // ... } }; databaseRef.addValueEventListener(msgListener);

Triggered every time something changes below the databaseRef node. All data below the node will be re-downloaded

slide-12
SLIDE 12

Realtime database. Set data and listen for changes

Listening for changes in a node Triggered every time something changes below the databaseRef node. Only modified child below the node will be re-downloaded

ChildEventListener childEventListener = new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {...} @Override public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {...} @Override public void onChildRemoved(DataSnapshot dataSnapshot) {...} @Override public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {...} }; ref.addChildEventListener(childEventListener);

slide-13
SLIDE 13

Realtime database. Set data and listen for changes

Writing data

Message msg = new Message(...); databaseRef.child("messages").child("one").child("m1").setValue(msg); databaseRef.child("messages").child("one").child("m1").child("message").setValue("This is a test message");

Map<String, Object> childUpdates = new HashMap<>(); childUpdates.put("name", name); childUpdates.put("mesasage", “This is a test message”); childUpdates.put("timestamp", getTime()); databaseRef.updateChildren(childUpdates);

Overwrite key with single value Overwrite key with object value Update key with values list

slide-14
SLIDE 14

Realtime database. Offline persistence

Firebase apps automatically handle temporary network interruptions for you. Queues r/w operations locally

FirebaseDatabase.getInstance().setPersistenceEnabled(true);

Transactions are not persistent across app restarts (use other solution...)

slide-15
SLIDE 15

Client user authentication

Support for different providers:

  • Email/password (managed by Firebase)
  • Google
  • Facebook
  • Twitter
  • GitHub
  • Anonymous

Templates for: email verification, password reset, change email

slide-16
SLIDE 16

Client user authentication

Listener for auth events

mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in } else { // User is signed out } } }; FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

slide-17
SLIDE 17

Client user authentication

User management operations with callbacks:

mAuth.createUserWithEmailAndPassword(email, password) mAuth.signInWithEmailAndPassword(email, password) user.updateProfile(profileUpdates) user.updateEmail("user@example.com") user.sendEmailVerification() user.updatePassword(newPassword) mAuth.sendPasswordResetEmail(emailAddress) user.delete() user.reauthenticate(credential)

slide-18
SLIDE 18

Client user authentication

Use APP/API key and secret for providers other than Google/Firebase

slide-19
SLIDE 19

Server user authentication

  • Integrate Admin Auth API with own servers
  • Java SDK, Node.js SDK, REST API
  • Service account needed
slide-20
SLIDE 20

Server user authentication

  • User management: programmatic access to users; it offers additional
  • perations (compared to Firebase console)
  • Node.js SDK
  • Retrieve, create, update and remove user credentials
  • Example (Node.js):

admin.auth().getUserByEmail(email) .then(function(userRecord) { // success }) .catch(function(error) { // fail });

slide-21
SLIDE 21

Server user authentication

  • Custom authentication: server composes different claims for an user account;
  • Example (Java):

String uid; HashMap<String, Object> claims = new HashMap<String, Object>(); claims.put("paidAccount", true); FirebaseAuth.getInstance().createCustomToken(uid, claims) .addOnSuccessListener(new OnSuccessListener<String>() { @Override public void onSuccess(String token) { // send retrieved token back to requester } });

slide-22
SLIDE 22

Server user authentication

  • Custom authentication: client uses retrieved custom server token to

authenticate current user with Firebase

  • Example (Java):

FirebaseAuth.getInstance().signInWithCustomToken(token) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { } } });

slide-23
SLIDE 23

Server user authentication

  • Identity verification: server can perform Firebase operations on behalf of the

user

  • Example (Java):

String idToken; // sent by client FirebaseAuth.getInstance().verifyIdToken(idToken) .addOnSuccessListener(new OnSuccessListener<FirebaseToken>() { @Override public void onSuccess(FirebaseToken decodedToken) { String uid = decodedToken.getUid(); } });

slide-24
SLIDE 24

Storage

  • Same hierarchical structure as Firebase Database
  • Used for storing and retrieving user-generated content
  • Robust: an upload/download restarts where it was initially stopped
  • Secure: it can integrate with Firebase Authentication or use a declarative

security model

  • Scalable: it’s backed by Google Cloud Storage
slide-25
SLIDE 25

Storage

  • Create a reference to the storage resource

String uid; StorageReference rootRef = FirebaseStorage.getInstance().getReference().getRoot(); StorageReference imageRef = rootRef.child("images").child(uid).child("avatar.png");

slide-26
SLIDE 26

Storage

  • Upload a local file to Firebase

File file; imageRef.putFile(file) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception exception) { // handle failure } }) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Uri downloadUrl = taskSnapshot.getDownloadUrl(); } });

slide-27
SLIDE 27

Storage

  • Download a file from Firebase

File file; imageRef.getFile(file) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception exception) { // handle failure } }) .addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() { @Override public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) { // content downloaded } });

slide-28
SLIDE 28

Database Rules

  • Supports .read, .write, .validate, .indexOn
  • .read and .write rules cascade
  • .read and .write rules shallower in the database override deeper rules
  • .validate rules do not cascade
  • E.g., a group of chat:

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

slide-29
SLIDE 29

Database Rules

  • Enforce that only authenticated users can write and read

{ "rules": { "friends": { ".read": "auth != null", ".write": "auth != null" } } }

slide-30
SLIDE 30

Database Rules

  • Enforce write only for ‘owner’

{ "rules": { "friends": { "$uid": { ".write": "$uid === auth.uid" } } } }

slide-31
SLIDE 31

Database Rules

  • Apply different validations on new data

{ "rules": { "friends": { "$uid": { ".validate": "newData.hasChildren(['msg', 'timestamp']) && newData.child('msg').val().length < 100" } } } }

slide-32
SLIDE 32

Database Rules

  • Index children based on timestamp

{ "rules": { "friends": { "$uid": { ".indexOn": ["timestamp"] } } } }

slide-33
SLIDE 33

Storage Rules

allow read, write: if <condition>; service firebase.storage { match /b/<firebase-storage-bucket>/o { // flat representation "friends/<UID>/avatar.png" match /friends/{userId}/{allPaths=**} { allow write: if request.auth.uid == userId; allow read: if request.auth != null; } } }

slide-34
SLIDE 34

Notifications

  • Built on Firebase Cloud Messaging
  • Simple and fast user notifications (marketing campaigns)
  • Integrates with Firebase Analytics
  • Demo: https://github.com/firebase/quickstart-android/tree/master/messaging
slide-35
SLIDE 35

Agora with Firebase

slide-36
SLIDE 36

Agora: database structure

1. Poll names and description 2. Poll options + (icons from Storage) 3. Poll results

List of active polls Poll options Poll votes Results in client app Poll option icons

slide-37
SLIDE 37

Student projects with Firebase

  • Parental control and location monitoring app (auth, db, notif, invites)
  • Smart outfit manager (auth, db, storage, notif)
  • Home automation platform (sensors, RasPi, app control) (auth, db)
  • Local cinema reviews (db, storage, notif, invites)
  • Administration-online
  • Real-time parking reservation and access
  • Chat with *special* encryption types (fingerprint, steganography)
  • Game of life with multiplayer
slide-38
SLIDE 38
slide-39
SLIDE 39

Canvy backend services

slide-40
SLIDE 40

Canvy meets Firebase

  • Try not to “overfit” Firebase services and tools
  • Use database data denormalization
  • Keep an eye on how your security rules would look like when designing

your database

  • Bolt compiler may become useful when rules are complex
  • Track application method count when adding new Firebase dependencies
slide-41
SLIDE 41

Why choose Firebase?

  • Solution by Google (security, availability, easy integration)
  • Free: Analytics, App Indexing, Authentication, Cloud Messaging, Crash

Reporting, Dynamic Links, Invites, Notifications & Remote Config

  • Great free plan /
  • Attractive starter plans
slide-42
SLIDE 42

Future: Android Things

  • The “sweetness” of Android development in embedded devices
  • Extends the core framework with additional APIs provided by Things

Support Library

  • Supports a large set of development boards
  • Firebase Cloud Doorbell example
slide-43
SLIDE 43

References and image credits

1. https://firebase.google.com 2. https://developer.android.com/things 3. http://gocanvy.com