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.

Advertisements

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.

Deploying an Angular 2, .Net Core 1.1 Web API and MongoDB using Docker Containers

What’s up guys, Eze is here. Again to those who follow me on Twitter (if you are not a follower you better do it now @skielo) already knows I’ve been working on an app to show you how to create an Angular 2 app using a ASPNET Core 1.1 Web API with a MongoDB database and using all those components in different Docker containers. Today I want to show you how easy is to get up and running an Angular 2 app and connect it to ASPNET Core 1.1 Web API to retrieve data from a MongoDB database, sounds amazing right? well this will be the first out of a series of post  where we are going to find out more about those tools

The frontend skeleton

First we need build the frontend and the back-end for our app. As I already told you the front-end will be an Angular 2 app. To create it we are going to use the Angular cli tool. There is nothing new here, and you can follow the steps I already wrote here. The only difference is this time we are creating a server.js file which will be our entry point in the Docker container.

The back-end skeleton

Well the back-end will be an ASPNet Core 1.1 Web API. This API will receive request from the frontend, get/put data to the database and provide a response. to create this application we will use the Yeoman generator. So let’s first install all the required dependencies by running the following command npm install -g yo generator-aspnet@0.2.6 generator-docker. This will install the latest version of the Yeoman tool + the latest generator for aspnet projects and a docker generator. The last one is not completely necessary but it good to have it.

Creating the code

Once we have all the required tools by executing this command yo aspnet Yeoman will create an small web api project. In order to test if our project has been created correctly we need navigate into the project folder and execute this commands: dotnet restore and then dotnet run, when the server has started we can browse this url http://localhost:5000/api/values to test our webapi.

yo_webapi

In order to create a data layer to access our MongoDB from our Web API project I’m using MongoDB Driver for C#. Basically I’m using the repository pattern, if you want to know more about that please follow this link. Something which is important to highlight is that within the connection string I’m using as a server name / ip address the name mongodb after the docker image. I will go into more details lately.

Then  I’ve created a new web api controller to handle the request from our Angular 2 app.

Installing Docker

Well we are almost ready to go. In order to complete our system we need to get the right version of Docker according with our operating system. Please follow this link to get it. Also it’s important to know that we will required the docker-toolbox, you can find it here. This toolbox will create the docker machine in our computer and using this console we will interact with our docker application.

By running this command yo docker and selecting .Net Core as a project we need to follow some bootstrapping scripts to create the docker files in our project. Regardless of the structure used by this tool in my project I’ve created a folder called .docker where I place the created dockerfile. This is a recommendation by @DanWahlin.

Exploring the dockerfile

In the dockerfile we will find the instruction for docker to build and run our images. In the example below we instruct docker to base our image in one from the docker hub: microsoft/dotnet:latest but, what that means? Well that means that we are going to use the official docker image created by microsoft to run a dotnet app. Then we select which port will be available within our container and which is the entry point for this image.

FROM microsoft/dotnet:latest
WORKDIR /app
COPY bin/Debug/netcoreapp1.1/publish /app
ENV ASPNETCORE_URLS http://*:80
EXPOSE 80
ENTRYPOINT ["dotnet", "WebAPIApplication.dll"]

Exploring the docker-compose file

This is the file we are going to use to build our images. In this file we specify all the characteristics of our images.  We also define the container_name (otherwise docker will pick a funky name on runtime for us), the image we want to use, the internal al external port for the container and something which is really cool, the network. This network specification will allow us to talk from one container to another. As you can see in the code below I’m using as a container_name for the database mongodb, the same I used in the connection string of our web api.

version: ‘2’

services:
webapiapplication:
container_name: webapiapplication
image: webapiapplication
build:
context: .
dockerfile: .docker/Dockerfile
ports:
– "80:80"
networks:
– webapi-network

node:
container_name: nodeapp
image: nodeapp
build:
context: .
dockerfile: .docker/Dockerfile
environment:
– NODE_ENV=development
ports:
– "3000:3000"
networks:
– webapi-network

mongodb:
container_name: mongodb
image: mongo
networks:
– webapi-network

networks:
webapi-network:
driver: bridge

Start the engine

Now we have our applications ready, we already configured the containers so it’s time to start our system. The first step is build and publish our .Net Core app. By running this commands dotnet build and dotnet publish we will do that. Then we need open the Docker Toolbox terminal. This will initialize our docker machine.

If you are running docker in Windows you probably are using hyper-v, if this is your case you might have to edit the start.sh file for your docker-toolbox in order to use hyperv as a driver and a virtual switch.

docker-machine create –driver hyperv –hyperv-virtualswitch “My Internal Switch”

Once the toolbox terminal is done we need to navigate to our project folder and run the command docker-compose build. This will build our images and after that by running docker-compose up -d, Docker is going to start up all our images and keep it running in daemon mode. And that’s it, our application will work all together. Because the images are running in daemon mode we can check the logs by executing docker-compose logs, there is another useful command which is docker ps -a which will show us all the instance for our images.

If you want to see the full code working together I have a working example here. Be aware that this is only an example, is not meant to be use in a production environment because as you can see the database doesn’t have any security at all. If you want more details please follow the official documentation.

For a complete reference of Angular 2 use this link.

For a complete reference of .Net Core use this link

For more references about Mongo images 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.

Microsoft Bot Framework – Forms dialog from JSON Schema.

What’s up guys, Eze is here. I’ve already written few posts about Microsoft Bot Framework, in case you missed it you can check it here. Today we are going deeper and review another really good feature of the Form Dialog, the possibility to create a form using a JObject. As we did before the Form Dialog is going to create a form and allow our Bot to ask field by field until completes the form but instead of using a static c# class to define our form we are going to provide a JSON Schema.

In order to utilize this feature you need to ensure that you add the NuGet project Microsoft.Bot.Builder.FormFlow.Json to your project. This defines the new namespace Microsoft.Bot.Builder.FormFlow.Json that contains the code to allows using JSON Schema for FormFlow.

Creating the JSON Schema

Now we need to define our form, this time we are going to create a json file to do it.  In the References property we are going to define all the dependencies for our form. In the same way under the Imports property we define all the namespaces to include. And another important property for our form is the OnCompletion property, here we are going to put a C# script to execute after our bot complete to fulfill the form. And then we have the properties field where we are going to place the fields we want our bot ask to the customer.

{
 "References": [ "CityTimerBot.dll" ],
 "Imports": [ "CityTimerBot.Models" ],
 "type": "object",
 "required": [
   "SelectedPlace"
 ],
 "Templates": {
 "NotUnderstood": {
 "Patterns": [ "I do not understand \"{0}\".", "Try again, I don't get \"{0}\"." ]
 }
 },
 "properties": {
 "PlaceName": {
 "Prompt": { "Patterns": [ "Name a place to know the current date-time {||}" ] },
 "Before": [ { "Message": [ "Welcome to the City Timer bot!" ] } ],
 "Describe": "Name of the place",
 "type": [
 "string",
 "null"
 ]
 },
 "SelectedPlace": {
 "Prompt": { "Patterns": [ "Select a place {||}" ] },
 "Before": [ { "Message": [ "Welcome to the City Timer bot!" ] } ],
 "Describe": "Place to find the current date time",
 "type": [
 "string",
 "null"
 ]
 }
 },
 "OnCompletion": "var businesLogic = new CityTimerBot.Models.LocationBL(); var response = businesLogic.GetCityInfoFromPlaceId(state.SelectedPlace);var reply = string.Empty;if (!string.IsNullOrEmpty(response.cityName) &amp;&amp; !string.IsNullOrEmpty(response.convertedLocalTime)){ reply = $\"Current date time at {response.cityName} is {response.convertedLocalTime}\"; }else{ reply = $\"Sorry we could not find any location called {state.PlaceName}\"; } await context.PostAsync(reply);"
}

Once we have defined the schema file we need create a method to return an object which implements the IForm interface as we did las time. As you can see in the code below we need use the FormBuilderJson object and we just pass the schema in the constructor.

 public static IForm<JObject>; BuildJsonForm()
 {
    using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("CityTimerBot.LocationTemplate.json"))
    {
       var schema = JObject.Parse(new StreamReader(stream).ReadToEnd());
       return new FormBuilderJson(schema)
         .AddRemainingFields()
         .Build();
    }
 }

As you can see this feature gives us the flexibility to define custom forms and the availability to change it dynamically.  Thinking out loud I can imagine an use case where we want to provide to our customers a way to model their forms so we can define the form as a JSON Schema and provide them an admin screen to change it.

bot_fields

For mode details of Microsoft Bot Framework 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 – 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.