Firebase – Real-Time Database using Angular 4 + Ionic 3

What’s up guys, Eze is here. Those who follow me on Twitter (if you are not a follower you better do it now @skielo) already know I’ve been working on a new mobile app using Firebase and Ionic 3 (Twitter: @socialtip_app, Facebook). I have several post talking about Firebase and how to use almost all its functionalities from an AngularJS app, in case you missed it you can check it here. Today I want to show you how easy is to get up and running an Angular 4 / Ionic 3 mobile app and connect it to Firebase. This will be the first out of a series of post  where we are going to find out more about those tools.

The skeleton of our app

I want to show you first how to create a new Angular 4 / Ionic 3 mobile app from the scratch. To do that we will need to install in our machines the ionic cli tool. The installation of this tool it’s really simple we just need run the following command npm install -g ionic. Please be sure you have a node version higher than 4 because it’s a requirement for this tool to run. In addition to this we will require Cordova installed as well so you will need run this command too npm install -g cordova.

This tool will provide us lots of functionalities that we are going to use during the development of our app but first we need to create the scaffolding of our app, by executing the following command ionic start app_name blank –v2 the Ionic cli will create a new Angular 4 / Ionic 3 app. The parameter blank indicates to the cli that we want to use a blank template and the parameter –v2 indicates we want a version 2 app if you don’t include this the cli will create an AnguarJs app. We can see our app running by executing ionic serve command.

ionic_screen.png

Adding Angular Fire 2 and Firebase to our project

We already have the basics of our project it’s time to add the reference to Angular Fire 2 and Firebase and we will do it by running the following command inside our project folder  npm install angularfire2 firebase –save. This command is going to install all the necessary files in our project. So now it’s time to dive into our app.module.ts in order to configure our Firebase project. First we need import AngularFireModule and then export the configuration we get from Firebase.

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { Databaseservice } from "../providers/databaseservice";
import { AngularFireModule } from "angularfire2";

export const firebaseConfig = {
apiKey: '',
authDomain: '',
databaseURL: '',
storageBucket: '',
messagingSenderId: ''
};

@NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
AngularFireModule.initializeApp(firebaseConfig)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
Databaseservice
]
})

export class AppModule {}

Creating a Database layer

Now we have configured Firebase to our project so it’s time to create our database layer in order to have access to our database. Again we are going to use Angular cli by typing ionic generate provider databaseservice. This time the command is going to generate a new service but you need to take care of something else which is include the database service in the providers Array in order to allow Angular to inject this new service so we need to add it  in the AppComponent as I did below.

 

import { Injectable } from '@angular/core';
import { AngularFire, FirebaseObjectObservable, AngularFireAuth, FirebaseListObservable } from 'angularfire2';

@Injectable()

export class Databaseservice {
   constructor(private_af: AngularFire) {
   }

   publiclistAccounts(): FirebaseListObservable<any[]>{
      returnthis._af.database.list('/accounts');
   }
}

And that’s it, after doing that we are ready to go. This AngularFire object will give us access to all Firebase functionality. In this example I’m using the databaseobject in particular the list method. As you can see we need pass the path reference to this method and the return will be an FirebaseListObservable object that will let us work with our database.

Using our Database layer

It’s now time to use our Database layer. As I did before I’ll inject it directly using the constructor and for the sake of this demo I’ll call the method to get the data directly in the constructor as well.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Databaseservice } from "../../providers/databaseservice";
import { FirebaseListObservable } from "angularfire2";

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})

export class HomePage {
 accounts:FirebaseListObservable<any[]>
 constructor(publicnavCtrl: NavController, publicdb: Databaseservice) {
   this.accounts = this.db.listAccounts();
 }
}
To complete our view I’ll use the Ionic list component. This component is a mobile like formatted list and as you can see we use the same Angular syntax and also you will find Ionic syntax is really similar to Html so you won’t have too much troubles.
<ion-header>
   <ion-navbar>
      <ion-title>
         List test
       </ion-title>
   </ion-navbar>
</ion-header>

<ion-content padding>
    This is just a list test.
    <ion-list>
      <ion-item class="text" *ngFor="let item of accounts | async">
         {{item.$value}}
      </ion-item>
   </ion-list>
</ion-content>

If you want to see the full code working together I have a working example here. As I told you at the begging of this post I’m working on a mobile app (www.socialtipapp.com) which use the whole Firebase toolbox: Real-Time Database, Authentication, Storage, Cloud Messages, Cloud Functions and much more. Believe guys it’s gonna be awesome.

IMG_2164

For a complete reference of Angular Fire 2 use this link.

For a complete reference of Firebase use this link

For a complete reference of Ionic use this link.

If you found this post useful please don’t forget to press the like button and share it. If you are in doubt don’t hesitate to ask a question and as always thank you for reading.

Cloud Functions for Firebase

What’s up guys, Eze is here. During the past post we were talking about Firebase, AngularJs and a bunch of cool tools to create rapidly powerful front-end apps, in case you missed it you can check here. Today I want to bring you the server side code that runs in a serverless architecture,  and no, I’m not talking about Azure Functions, today we are going to talk about Cloud Functions for Firebase the new tool from the Google Cloud team.

About Cloud Functions for Firebase

Cloud Functions is a hosted, private, and scalable Node.js environment where you can run JavaScript code. What that it means? well basically means you don’t need to take care about where your code is going to run, about which configuration has this server, how much memory is using or which OS version has. You just need to define the code to execute and which event is going to trigger our function. As they say.

Cloud Functions for Firebase provides a way to extend the behavior of Firebase and integrate Firebase features through the addition of server-side code.

Common scenarios for Cloud Functions for Firebase

  • Real-time Database Triggers: Handle events in the Firebase Real-time Database. It’s important to highlight that each change in the database is processed individually, the function runs with Admin privileges and you can change the behavior anytime.
  • Firebase Authentication Triggers: The function can be triggered in response to the creation and deletion of user accounts via Firebase Authentication.
  • Cloud Storage Triggers: The function can be triggered in response to an upload or delete of a file in the cloud storage.

  • HTTP Triggers: Of course the function support HTTP triggers which means that you can manually trigger the function on demand.

notify

Create and deploy your first Function

We are going to use the Firebase CLI tool to create the project for our function. If you haven’t done yet you can install the tool by using this command: npm install -g firebase-tools. Once we have the Firebase CLI tools then we need follow this steps:

  • Run firebase login
  • Navigate to our project folder and run firebase init functions

This will create the following structure:

myproject
 +- .firebaserc    # Hidden file that helps you quickly switch between
 |                 # projects with `firebase use`
 |
 +- firebase.json  # Describes properties for your project
 |
 +- functions/     # Directory containing all your functions code
      |
      +- package.json  # npm package file describing your Cloud Functions code
      |
      +- index.js      # main source file for your Cloud Functions code
      |
      +- node_modules/ # directory where your dependencies (declared in
                       # package.json) are installed

Import the required modules and initialize

At this point our Cloud Function is almost ready to go. First we need import the providers modules. In order to do that we need to edit the index.js file which contains the function code.

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

And now as in every nodeJs application we need export the function we want run. As you can see in the code below we create a HTTP function that takes the parameter from the query string and add it to the database.

exports.addText = functions.https.onRequest((req, res) => {
const original = req.query.text;
admin.database().ref('/messages').push({original: original}).then(snapshot => {
res.redirect(303, snapshot.ref);
});
});

Now we need deploy our function to Firebase. In order to do that we just need execute the following command: firebase deploy –only functions. After do that our function will be available to use via HTTP request.

https://us-central1-MY_PROJECT.cloudfunctions.net/addText?text=AddThisMessage

This is just a small taste of what you can do with this new functionality from the Google Cloud team.  We can use this new tool to maintenance task or just to add more functionality to our current apps. The idea to have a backend for our firebase applications is something really exciting and allow us to have more powerful apps.

For more details of Cloud Functions you can use this link.

For more details of Cloud Functions for Firebase you can use this link.

If you found this post useful please don’t forget to press the like button and share it. If you are in doubt don’t hesitate to ask a question and as always thank you for reading.

Firebase Database Security Rules API

What’s up guys, Eze is here. I already did couple of posts about Firebase and how to use the Real-Time database and the storage with AngularJs in case you missed it you can check here. Today I want to talk about security rules. I’ve answered this question in StackOverflow and that motivated me to write this post.

Understanding Rules object

As almost everything in Firebase the rules for our database will be a JSON Object. We are going to use this object to define security, data structure and of course validations. As you can see below the structure of this object is quite simple. It has only one property called rules which will have the rules definitions.

{
"rules": {
"users": {
".read": "root.child(‘access_token’).child(auth.uid).exists()"
}
}
}

Rules types

Under the security rules we can define four different types. We can apply those types to the complete database as is in the example above or we can define every type at an specific path.

  • .read: This rule is a type of Security Rule which grants a client read access to a database location.
  • .write: This rule is a type of Security Rule which grants a client write access to a database location
  • .validate: This rule is used once a .write rule has granted access, to ensure that the data being written conforms to a specific standard
  • indexOf: This rule tells the database servers to index specific keys in your data to improve the performance of your queries

Rules variables

As you can imagine Firebase use an specific set of variables to perform the rule types that we defined before.

  • auth: This variable will contain the token payload in case the is an authenticated user.
    • provider : The authentication method used by the user.
    • uid: This will be the uid to the authenticated user.
    • token: This variable contains the contents of the Firebase Auth ID token.
  • $location: In this case the $ is used to reference in a generic way to the child within the path.
  • now: Contains the number of milliseconds since the Unix epoch according to the database servers.
  • root: It’s a RuleDataSnapshot to the current data at the root level. That means we can query others path to validate.
  • data: It’s a RuleDataSnapshot corresponding to the actual data in the path.
  • newData: It’s a RuleDataSnapshot corresponding with the data that will result if the write is allowed.

Rules methods and operators

To complete the types and variables Firebase offers us a series of method to apply over the variables that we will use within the types. Just to name a couple we can use the val() method to retrieve the value of the snapshot o child() to query the paths.

In the same way we can use most of the logical operators like === equals , !=== not equals, || or, ! not and so on.

Using all together

In the example below I defined a rule for the path users. Using the $user means that this rule is for every child under the path users with the id user. Then I defined the types so I started with .read, by assigned true means that everyone (even unauthenticated users) can read under this path. For .write path I access to the variable root to query the access_token path with a child that belongs to the authenticated user uid and then use the method exists to validate if there is data under this path. To finish I used the .validate type to validate the newData to write has the right structure.



</span><span class="pun">{
    "rules": {
       "users": {
          "$user": {
             ".read": true,
             ".write": "root.child('access_token').child(auth.uid).exists()",
             ".validate": "newData.hasChildren(['name', 'age'])"
         }
      }
   }
}

 

For a complete reference of Firebase use this link.

If you found this post useful please don’t forget to press the like button and share it. If you are in doubt don’t hesitate to ask a question and, as always, thank you for reading.

Firebase – Real-Time Database using Angular 2

What’s up guys, Eze is here. Those who follow me on Twitter (if you are not a follower you better do it now @skielo) already know I’ve been working on an app to show you how to use Firebase from an Angular 2 app. I have several post talking about Firebase and how to use almost all its functionalities from an AngularJS app, in case you missed it you can check it here. Today I want to show you how easy is to get up and running an Angular 2 app and connect it to Firebase. This will be the first out of a series of post  where we are going to find out more about those tools.

The skeleton of our app

I want to show you first how to create a new Angular 2 app from the scratch. To do that we will need to install in our machines the angular cli tool. The installation of this tool it’s really simple we just need run the following command npm install -g @angular/cli. Please be sure you have a node version higher than 4 because it’s a requirement for this tool to run.

This tool will provide us lots of functionalities that we are going to use during the development of our app but first we need to create the scaffolding of our app, by executing the following command ng new app_name the Angular cli will create a new Angular 2 app. We can see our app running by executing ng serve command.

ng_create.PNG

Adding Angular Fire 2 and Firebase to our project

We already have the basics of our project it’s time to add the reference to Angular Fire 2 and Firebase and we will do it by running the following command inside our project folder  npm install angularfire2 firebase –save. This command is going to install all the necessary files in our project. So now it’s time to dive into our app.module.ts in order to configure our Firebase project. First we need import AngularFireModule and then export the configuration we get from Firebase.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AngularFireModule } from 'angularfire2';

import { AppComponent } from './app.component';

export const firebaseConfig = {
apiKey: '',
authDomain: '',
databaseURL: '',
storageBucket: '',
messagingSenderId: ''
};

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AngularFireModule.initializeApp(firebaseConfig)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Creating a Database layer

Now we have configured Firebase to our project so it’s time to create our database layer in order to have access to our database. Again we are going to use Angular cli by typing ng generate service databaseservice. This time the command is going to generate a new service but you need to take care of something else which is the warning we got from the tool: “WARNING Service is generated but not provided, it must be provided to be used”. In order to provide this new service we need to include it in the AppComponent as I did below.

import { Component } from '@angular/core';
import { DatabaseService } from './core/database.service';

@Component({
moduleId: module.id,
selector: 'my-app',
templateUrl: 'app.component.html',
providers: [DatabaseService]
})
export class AppComponent {

}

As you can see in the code above we use a great feature of Type Script that allows us to define a property in the constructor which means that Angular will automatically inject the right object for us.

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { AngularFire, FirebaseObjectObservable, AngularFireAuth } from 'angularfire2';

@Injectable()
export class DatabaseService {

constructor(private _af: AngularFire) {
}

createBattle(obj: Battle){
return this._af.database.list('/battles').push(obj);
}

And that’s it, after doing that we are ready to go. This AngularFire object will give us access to all Firebase functionality. In this example I’m using the database object in particular the list method. As you can see we need pass the path reference to this method and the return will be an FirebaseListObservable object that will let us work with our database.

If you want to see the full code working together I have a working example here. This example is an small version of the game battleship.

For a complete reference of Angular Fire 2 use this link.

For a complete reference of Firebase use this link

If you found this post useful please don’t forget to press the like button and share it. If you are in doubt don’t hesitate to ask a question and as always thank you for reading.

Firebase – Implementing FirebaseUI for Web Authentication

What’s up guys, Eze is here. Earlier this week I wrote a post explaining how easy is to implement Firebase Authentication in our AngularJs projects, in case you missed it here you go the link. As I told you @lmoroney have written a bunch of posts regarding this topic, in one of his post he pointed out the need to have a good user experience during the login flow. Even if Firebase simplify the login process we still need to write a good user interface to support the process. What if I told you that Firebase team has this covered as well? Well it is true, they have  an amazing tool called FirebaseUI for web. 

Adding the component to our project

First thing we need to do is adding this awesome component to our project. In order to do that we have several options:

  • CDN: just reference the .js and the .css files from this location https://cdn.firebase.com/libs/firebaseui/1.0.0/
  • npm Module: By executing this command you can get all the necessary files $ npm install firebaseui –save
  • bower component: You can add the reference to your bower.json file or just execute the following command to the files $ bower install firebaseui –save and then reference those files in your project.

If you check my code here you can see that I have the reference in my bower.json file but you can use the option that best fit for your needs.

Using FirebaseUI

Unfortunately this component doesn’t have yet a native version for Angular anyway it doesn’t stop us to use it in our Angular projects. If you remember from the last post I’m using $firebaseAuth from the Angular Fire component. In order to use the same instance of the Firebase Authentication object I made an small modification in my auth service as you can see in the code below.

 var authObject = firebase.auth();
 var firebaseAuthObject = $firebaseAuth(authObject);
 var ui = new firebaseui.auth.AuthUI(authObject);

Doing that the AuthUI and $firebaseAuth object are using the same reference to the Firebase Auth object. Then we need to add the following element to our html. FirebaseUI will use it to display the authentication flow.

<div id="firebaseui-auth-container"></div>
<div id="loader"&amp;gt;Loading...</div>

And finally we need to configure FirebaseUI passing a config object to the start method.

 vm.callback = function(currentUser, credential, redirectUrl) {
    $rootScope.$broadcast(AUTH_EVENTS.loginSuccess, {});
    $location.path('/citytimer');
    return false;
 };

 // FirebaseUI config.
 var uiConfig = {
    callbacks: {
       signInSuccess: vm.callback,
       uiShown: function() {
          document.getElementById('loader').style.display = 'none';
       }
    },
    redirectUrl: '',
    credentialHelper: firebaseui.auth.CredentialHelper.ACCOUNT_CHOOSER_COM,
    queryParameterForWidgetMode: 'mode',
    signInFlow: 'popup',
    signInOptions: [
       firebase.auth.EmailAuthProvider.PROVIDER_ID
    ]
 };

 // The start method will wait until the DOM is loaded.
 authService.firebaseUI.start('#firebaseui-auth-container', uiConfig);

As you can see the config object has a lot of properties to define our authentication process.

  • callbacks: This property contains the callback functions to execute.
  • signInOptions: In this property we define the list of providers we have enabled in our Firebase console.
  • signInFlow: Define if we do a full redirect to login or we just open a popup. The full redirect option is recommended for mobile versions.
  • credentialHelper: I’ve configured the account chooser to let the customer select which email select.

login.png

As you can see handle the authentication using Firebase Authentication it’s really simple and even simplest if you add FirebaseUI for web. I have a working example that you can check here. As I always say in this post I just covered the basic to get up and running the authentication in our app. It’s up to you guys continue reading the documentation to get more knowledge.

For a complete reference of FirebaseUI use this link.

For a complete reference of the Authentication API use this link.

For a complete reference of Angular Fire use this link.

For a complete reference of Firebase use this link

If you found this post useful please don’t forget to press the like button and share it. If you are in doubt don’t hesitate to ask a question and as always thank you for reading.

Firebase – Authentication using AngularJs

What’s up guys, Eze is here. In the past weeks I wrote several post about Firebase Real-Time Database, Firebase Storage and the new version of AngularFire 2.3.0 which includes Firebase Storage as well. In my first post I told you that Firebase provides us a wide range of tools and I mentioned Authentication but I didn’t have the opportunity to talk about it yet. Last week @lmoroney have written a bunch of posts regarding this topic, that inspired me to start this serie of posts to give you my point of view of this powerful tool.

Adding Firebase to your web app

We only need to reference AngularJs, Firebase and AngularFire libraries in your  project.

<!-- AngularJS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>

<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/3.6.4/firebase.js"></script>

<!-- AngularFire -->
<script src="https://cdn.firebase.com/libs/angularfire/2.2.0/angularfire.min.js"></script>

Then we need to add Firebase configuration in our index.html. To do that we need to go into the Firebase console and get the initialization code.

Creating your data layer

Now I will create an AngularJs service to use as data layer. This service will be responsible to create our links to the Firebase Authentication. Here we are going to use this time another object from the firebase library $firebaseAuth.

 function authService($firebaseAuth, firebaseDataService, cityTimerService) {
    var firebaseAuthObject = $firebaseAuth();

    var service = {
       firebaseAuthObject: firebaseAuthObject,
       register: register,
       login: login,
       logout: logout,
       isLoggedIn: isLoggedIn,
       sendWelcomeEmail: sendWelcomeEmail
    };

    return service;

    ////////////

    function register(user) {
       return firebaseAuthObject.$createUserWithEmailAndPassword(user.email, user.password);
    }

    function login(user) {
       return firebaseAuthObject.$signInWithEmailAndPassword(user.email, user.password);
    }

    function logout() {
       cityTimerService.reset();
       firebaseAuthObject.$signOut();
    }

    function isLoggedIn() {
       return firebaseAuthObject.$getAuth();
    }

    function sendWelcomeEmail(emailAddress) {
       firebaseDataService.emails.push({
           emailAddress: emailAddress
       });
    }
}

Enable the Authentication methods

Before going further there is something we need to do in our Firebase console in order to enable the sign-in methods as I did in the image below. In my case I enabled two methods Email/Password and Anonymous but as you can see we can also select Google, Facebook, Twitter or GitHub.

authentication.PNG

Understanding the $firebaseAuth object

This object provides us a really good interface to work with the authentication in Firebase. Today I’ll explain you four methods:

  • $createUserWithEmailAndPassword: This method receives two parameters email and password and returns a promise containing a firebase.User.
  • $signInWithEmailAndPassword: This method receives again two parameters email and password and returns a promise containing a firebase.User object. It throws an error in case the email and password don’t match.
  • $getAuth: This method returns a promise containing a firebase.User.
  • $signOut: This method is going to sign out the current logged in user and returns a string containing the email of the user in case of success.

As you can see handle the authentication using Firebase Authentication it’s really simple. In this post I just covered the basic to get up and running the authentication in our app. In the following post I’ll be covering more complex scenarios.

For a complete reference of the Authentication API use this link.

For a complete reference of Angular Fire use this link.

For a complete reference of Firebase use this link

If you found this post useful please don’t forget to press the like button and share it. If you are in doubt don’t hesitate to ask a question and as always thank you for reading.

Firebase – Structuring Data (Denormalization)

What’s up guys, Eze is here. I already did couple of posts about Firebase and how to use the Real-Time database and the storage with AngularJs in case you missed it you can check here. Today I want to go further and show you how to structure your data but more important how to de-normalize your data, yes I’m not crazy we are going to make exactly the oposite we learned with relational database.

Database normalization

I guess this is the case of everyone how has some knowledge about Relational database. One of the first things we learn is how to normalize our database which is reducing data duplication. In this post I’m not saying we need to forget it because if you are working with relational database it’s the way to go but with NoSQL databases things are quite different.

Denormalization: duplicating data

Yes, as simple as that denormalization means that we are going to duplicate data in order to simplify or minimize our queries. If we take as example the model we use in this post.

database_schema

In this model we need to query our database twice as I showed in that post to get the order data + the user data. And this is fine as long as this query runs over an small data set or is a query that you know is not going to run very often but if this is not the case you will probably want to remove the inner query for good.

So taking this into account one posible solution might be to store the user data we want to use like first name and last name under the order object instead of the reference id we are storing right now.

A rule for denormalization

Basically a good rule to know when is useful denormalize our data structure is to design our database after our views. Doing that we warranty that using one single path we will get the right data to show in our views, also that gives us the opportunity to do further queries in case we need it.

Data Consistency

By this time I’m sure that you guys have the following question in your minds: What about the consistency? And you are right we are duplicating data everywhere so how we can warranty the consistency across our database?. Well let me tell you that Firebase has covered that as well with a really good feature called multi-path update that I’m going to cover soon.

For a complete reference of Firebase use this link

For a complete list of querying functions you ca use this link.

If you found this post useful please don’t forget to press the like button and share it. If you are in doubt don’t hesitate to ask a question and as always thank you for reading.