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.

Advertisements

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.

Power BI and how to integrate with Azure Tables Storage

What’s up guys, Eze is here. If you remember for this post I created an Azure Function that stores data from our Web application into a Azure Table Storage. Today I want to bring you a really powerful tool: Power BI, a data visualization tool that allows you to bring your data to life.

About Power BI

This is a great tool by Microsoft that allows us to create custom visualization of our data from different data sources, today we are going to put the focus on Azure integration and how to bring to life our data stored in an Azure Table Storage. You can think Power BI as tool to create awesome dashboards. In they words:

Power BI is a cloud-based business analytics service that gives you a single view of your most critical business data. Monitor the health of your business using a live dashboard, create rich interactive reports with Power BI Desktop and access your data on the go with native Power BI Mobile apps. It’s easy, fast, and free.

Connecting to the data source

The first step it’s to download the Power BI desktop application for free in their website. I wont give the details you guys already know how to do it. Once we have the tool we need to configure our Azure Table Storage to pull data so first we connect using our Storage Account Name and Storage Account Key to connect our data source.

power_bi_select

Then we select our Azure Table Store to pull data from. In my case I’ll use the same I used when I create the Azure Function.

power_bi_select_table.PNG

We are almost there. We already have selected our Azure Table Storage, selected our table to pull data so now we need to define our visualization. In my table I have stored the city name on each request so by selecting this column as I did in the image below Power Bi already created a map data visualization displaying each row as a dot in the map.

power_bi_chart.PNG

The next step is save our report locally and the publish it into Power BI web. And that’s it every time a new row is added into our Azure Table Storage Power BI web is going to pull this new data and display it in our data visualization. As you can see this one it’s a really simple example but believe me when I tell you that Power BI gives us much more flexibility to create awesome dashboards. Later on this week I’ll create another post where I will use the Power BI SDK to integrate this report in our custom website.

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

For more details of Power BI 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.

Google Maps API – How to make a custom marker

What’s up guys, Eze is here. Today I want to show you how easy is to create a custom marker using the Google Maps API. First let’s create a map reference using the Google Maps API. We will be using this object to place our marker.

// Create a map centered in NY
vm.map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.7128 , lng: 74.0059},
zoom: 15
});

As you can see in our code above we only need to pass as a parameter the element reference, in my case it’s just a div element with id = ‘map’. The API will create the map view in this element. Then using the PlacesService we get the details of an specific place. I’m using this service because in my working example (you can check the code here) I have an input element where the user can select a place, this input is populated using the autocomplete service so basically I have the place_id parameter to provide but if you don’t want to use it in this way in the request object you can provide a reference property to search different places.

 

var request = {
placeId: place.placeId
};

var service = new google.maps.places.PlacesService(vm.map);
service.getDetails(request, callback);

function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: vm.map,
position: results.geometry.location,
title: results.formatted_address
});
var infowindow = new google.maps.InfoWindow();
vm.map.setCenter({lat: results.geometry.location.lat(), lng: results.geometry.location.lng()})
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('
&lt;div&gt;&lt;img src="'+ vm.place.photoUrl + '" style="width:128px;height:128px;"/&gt;&lt;/div&gt;
');
infowindow.open(vm.map, this);
});
}

Once I get the details for a specific place I use the Marker object to create a new marker in the map. The object I’m using to create this instance contains the reference to my map, the geometry location object which I get from PlacesService and a title. And that’s it, this is all you need to create a new marker in a map using the Javascript library for Google Maps API.

places.PNG

For a complete reference of Google Maps API 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 – Advance querying join reference

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 give you more details on how to do an advance query to join two references.

Let’s suppose we have the schema below and we want to retrieve the list of orders.

database_schema.png

To do that we just need to do as we did several times in our previous examples and attach to the child_added event as I did in the code below. As you can see we get the data under the path orders, but we still need to show the data under the path users which is linked to our orders.

query_first

In the code below we now changed the query in order to get as well the user data from the path users. It’s important to highlight that this time I’m using the method once which will retrieve the data once and this data it’s not going to be live data, we are not going to receive notification if this data changes. There is another way to get the data in real time but we need to keep the reference to dispose the connection we no longer need it. But again if you don’t really need the related data in real time you can use this easy way to join two references.

query_second.PNG

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.

Microsoft Bot Framework – Forms Dialog and how to add dynamic options.

What’s up guys, Eze is here. As you know I’ve already written a post about Microsoft Bot Framework, in case you missed it you can check it here. Today I want to go deeper and explain a really good feature: Form Dialog. This feature is used to create a form and allow our Bot to ask field by field until completes the form and in particular I want to explain how to add dynamic options to our font so let dive into the description right away.

Creating the form

Let’s suppose we have a form and we want our bot to ask for each property in our form to the user in order to complete it so first we need to define our form. In my case I’m using the same I have in my working example. As always the working example is available here.

[Serializable]
 [Template(TemplateUsage.NotUnderstood, "I do not understand \"{0}\".", "Try again, I don't get \"{0}\".")]
 public class PlaceTemplate
 {
    [Prompt("Name a place to know the current date-time {||}")]
    [Describe("Name of the place")]
    public string PlaceName { get; set; }
    [Prompt("Select a place {||}")]
    [Describe("Place to find the current date time")]
    public string SelectedPlace { get; set; }

As you can see in the code above we just define a new class and the properties of this class are going to be used by our bot to complete the form. Then we need to define a static method to return a IForm<object>. As you can see below this method create an instance of the class FormBuilder and then just return the method Build(). In this FormBuilder it’s going to define which field we want to ask to the user, to do that we are going to use the method Field(). And then using the OnCompletion() method we will define the behavior for our bot after populate all the requested fields. As you can see this is a good way to guide our user through a form.

 
 public static IForm<PlaceTemplate> BuildPlaceForm()
{
var logic = new LocationBL();
OnCompletionAsyncDelegate<PlaceTemplate> process = async (context, state) =>
{
var businesLogic = new LocationBL();
var response = businesLogic.GetCityInfoFromPlaceId(state.SelectedPlace);
var reply = string.Empty;
if (!string.IsNullOrEmpty(response.cityName) && !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);
};
var builder = new FormBuilder<PlaceTemplate>()
.Message("Welcome to the City Timer bot!")
.Field(nameof(PlaceName))
.Field(new FieldReflector<PlaceTemplate>(nameof(SelectedPlace))
.SetType(null)
.SetActive((state) =>
{
return string.IsNullOrEmpty(state.SelectedPlace);
})
.SetPrompt(new PromptAttribute("Please select one of the following options: {||}")
{
ChoiceStyle = ChoiceStyleOptions.Buttons

})
.SetDefine((state, field) =>
{
var result = logic.GetPlaces(state.PlaceName);
foreach (var item in result)
{
field
.AddDescription(item.Item1, item.Item2)
.AddTerms(item.Item1, item.Item2);
}

return Task.FromResult(true);
}))
.OnCompletion(process);
return builder.Build();
}

Adding dynamic options to a field.

I saw a lot of examples where the use can chose one of many options but those options are always defined using an Enum. In my case I want to define the options dynamically so to do that our field needs to be an instance of FieldReflector. This new object has a method SetDefine as you can see in the code above which is used in my example to get the list of places and return a list to the user to select one option.

As you can see creating a form using the Microsoft Bot Framework it’s really easy and adding dynamic options to a field is even easier.

bot_fields.PNG

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.