An AngularJs directive to support Google Places Autocomplete API

What’s up guys, Eze is here. Today I want to talk you about a directive I’ve been working on which is a wrapper for Google Places Autocomplete using the Google Places API. As always you can find the code here. This directive is an improvement for a discontinued project.

bower.PNG

Using the directive

This directive it’s really easy to use. First we need to get the code and you can do it via bower using the following command bower install ng-autocomplete-places –save.  Once we reference the file in our html we are almost ready to go. As you can see in the code below we only need add the directive to the input control we want to convert into an autocomplete text-box  and then define the object in our AngularJs controller.

<input type="text" ng-places-autocomplete ng-model="vm.autocomplete" class="form-control" options="vm.options" details="vm.details" initial-address="vm.initialAddress"/>
 vm.result = '';
 vm.autocomplete = {};
 vm.options = {};
 vm.initialAddress = null;

autocomplete.gif

After we select one of the options of the autocomplete, the directive setup into the ng-model property the formatted address from Google Places API, this is what we show into the text-box element. Into the details object we will have available the complete object returned the API. In this object we have really useful information related the place like the geometry information (latitude and longitude), photos, descriptions, rates etc.

autocomplete_returns.PNG

Improvements to the original project

I’ve added to this project the possibility to use a reverse geocoding. If you already have the place_id property or if you have the latitude and longitud of the place you can provide it to the directive in order to initialize the component. Also I merged almost all the pending pull request in the original project.

For a complete documentation of the directive please use this link.

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.

Advertisements

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.

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.

Firebase Storage is officially in AngularFire 2.3.0 – The easiest way to upload binary content

What’s up guys, Eze is here and today I want to talk you about some great news. The AngularFire team have released a new version which is 2.3.0 and you can check it here.  This new version officially supports Firebase Storage and believe me this feature it’s amazing. I already have a post explaining how to upload images using Firebase Storage from AngularJs in case you missed it  here you go the link. So the idea for today’s post is to refactor the actual working example I have (here is the link to the code) and make it work using Angular Fire Storage, let’s see how it works.

Creating your data layer

I’m going to keep the same data layer because the concept it’s the same but this time I’ll add as a reference $firebaseStorage as you can see in the code below. The other change we need to do it’s return an instance of this object in our service because we are going to use this object to communicate with Firebase directly.

 function storageService($http, $firebaseStorage, $q) {
    var storageRef = firebase.storage().ref();
    var storage = null;

    var service = {
       getStorage: getStorage
    };

    return service;

    function getStorage(uid, fileName) {
       if(!storage){
          storage = $firebaseStorage(storageRef.child(uid).child(fileName));
       } 
       return storage; 
    }
 }

So basically we are using the service to create our Firebase Storage object. This new object is going to handle all the communication with Firebase in order to upload our files.

New unterface to interact with

Previously I’ve used the put method to upload our file. This method receives three functions as parameters to handle progress, error and the completion or our upload. Well all this is part of the past. With this brand new version we are going to use  use the method $put to upload our file and this method is going to return us an Upload Task object. We need to provide a callback function to the method $progress, $error and $complete in order to handle the events as we did before.

 
	vm.uploadTask = vm.storageRef.$put(vm.file);

	vm.uploadTask.$progress(function(snapshot) {
			var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
			vm.progress = 'Upload is ' + progress + '% done';
			switch (snapshot.state) {
				case firebase.storage.TaskState.PAUSED:
					console.log('Upload is paused');
					break;
				case firebase.storage.TaskState.RUNNING:
					console.log('Upload is running');
					break;
			}
	}); 
	vm.uploadTask.$complete(function(snapshot) {
		vm.newPlace.photoUrl = snapshot.downloadURL;
		vm.places.$add(vm.newPlace);
		$rootScope.$broadcast('successAlert', { header: 'Well done.', msg: 'Your request has been process successfully.' });
	});
	vm.uploadTask.$error(function(error) {
		var msg = '';
		switch (error.code) {
			case 'storage/unauthorized':
			msg = 'User does not have permission to access the object.';
			break;
			case 'storage/canceled':
			msg = 'User canceled the upload.';
			break;
			case 'storage/unknown':
			msg = ' Unknown error occurred, Please try later.';
			break;
		}
		$rootScope.$broadcast('dangerAlert', { header: 'Oh snap!', msg: msg });
	});

As you can see now it’s much easier upload files and handle event with this new Firebase Storage Service. I have a working example in this link if you want to see the complete implementation. In this example I created an app that allows you to select different places around the world and upload an image that appears in a google maps.

firebase_storage

For a complete reference of Firebase storage 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 + Azure Functions + Azure Service Bus + Microsoft Bot Framework – Connecting the dots.

What’s up guys, Eze is here. I’ve been working in an example that you can check it here, this example uses Firebase, AngularJs and Azure Functions. I used a bunch of cool tools to create rapidly powerful front-end app, in case you missed it you can check here. Today I’ll add couple of new tools like Microsof Bot Framework and Azure Service Bus to enhance our app in a decouple way. The idea is to create a bot that receives a place name and response with the current date time at that location. After the bot parse the input and generate the proper response puts into the Azure Service Bus a message that will trigger our NodeJs Azure Funtion to store the data in Firebase, pretty cool, isn’t it? You can check the working version here.

NodeJs Azure Function

Today we are going to put the focus only in our Azure Function so I’ll talk about how to create a NodeJs Azure function and how to configure it in order to be able to use Firebase from a NodeJs Azure function.

As we did last time, in case you missed it you can check here our Azure function is composed for two files the function.json (function metadata) and because this one is a NodeJs function we need to have an index.js file to place our code to execute. All JavaScript functions must export a single function via module.exports for the runtime to find the function and run it. This function must always include a context object. In the example below you can see how I configure my function.

module.exports = function(context, mySbMsg) {
   if(!app) {
      context.log('Initializing Firebase App');
      app = firebase.initializeApp(config);
   }
   var defaultAuth = app.auth();
   if(!_user){
      defaultAuth.signInAnonymously()
                 .catch(function(error) {
                    context.log('Anonymous login failed: ' + error.message);
                    context.done();
                 });
   }

   defaultAuth.onAuthStateChanged(function(user) {
   if (user) {
      _user = user;
      context.log('User is signed in. user uid: ' + _user.uid);
      var defaultDatabase = app.database().ref().child('requests').child(_user.uid).child('userRequests');
      mySbMsg['userName'] = 'Anonymous';
      defaultDatabase.push(mySbMsg)
                     .then(function() {
                          context.log('JavaScript ServiceBus queue trigger function processed message', mySbMsg);
                          context.done();
                     })
                     .catch(function(error) {
                          context.log('Synchronization failed');
                          context.done();
                      });
    } else {
       context.log('User is signed out.');
       context.done();
    }});
};

Configuring the environment

Before going further with the explanation of the function I want to explain first how to configure the Azure function to use Firebase node package. Let’s remember that this function is going to run in Azure serverless. That only means that we don’t have full control over our server but we still can run npm install  in the function app’s SCM (Kudu) command line interface in order to add packages to our app:

  1. Navigate to: https://<function_app_name&gt;.scm.azurewebsites.net.
  2. Click Debug Console > CMD.
  3. Navigate to D:\home\site\wwwroot\<function_name>.
  4. Run npm install firebase --save.

kudu

After doing this we will be able to import our Firebase library like this:

var firebase = require('firebase');

After that we can use our firebase object as we did before so let’s dive directly into our function so I can explain you what’s going on. First I use the method signInAnonymously under the object auth and this is because I need a logged in user to write in my database, don’t worry we didn’t talk about it yet but believe me I’m going to explain you more about database rules and authentication with Firebase.

Then I use the object that I receive as parameter from my Azure Service Bus and directly store it in our database. During this week I’ll be posting about the other parts of this system so you can know more about Microsoft Bot Framework and Azure Service Bus

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

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

For mode details of Firebase npm package us 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.