Use Facebook Sign-In with Ionic and Firebase

10 million of people use Facebook Login everyday to sign-in to applications across the entire web – as per Facebook. By integrating a fully working Facebook sign-in process with your app, your users will have a safe, authentic and consistent experience. They even don’t need to go through such monotonous credentials re-entering process to sign-in to your application. Having this easy and reliable Facebook Login functionality generates a win-win situation for both users as well as developers. That’s why you should include Facebook Login functionality in your application. As this “Why” is clear to you, so let’s proceed to “How” to use Facebook sign-in with Ionic and Firebase to make the development process even easier.

First-off, let’s have a look on the brief of this “How to” process:

1. Sign-in and navigate to your Facebook developer account. Now, create a new app and supply the credentials.

2. Enter into your Firebase console and authorize Facebook authentication for app with the credentials from the aforementioned step.

3. Writing the code to get user authorization from the Facebook and then authentication of that user into Firebase app.

After this brief, let’s start with an in-depth explanation of each step:

1. Facebook Developer Account

Firstly, you have to create a new application via Facebook developer account. So navigate to https://developers.facebook.com/apps. Register yourself as a developer (if not registered yet) and create a new application.

Create New App

 

A short form will pop out as you click on “Create App Id” button. Add a “Display Name” for your app and a contact email address that will be public to your users.

 

Create a New App ID

 

Once after completing “Create App Id” process, you will land to the app’s dashboard. Here you can notice the “APP ID” at the top of the page, adjacent to “View Analytics” option. Note it down as you will require it during Facebook plugin installation.

 

App ID

 

Cordova Plugin Installation

Once you have done with your new app creation on Facebook, it is the time to proceed with the Cordova plugin installation in your Ionic app to make the app calling the Facebook Sign-in widget. So, start off with the opening of your terminal and write the following (everything in the same line):

$ ionic plugin add cordova-plugin-facebook4 --variable APP_ID="168934381" --variable APP_NAME="ABCApplication"

Now replace the values of APP_ID & APP_NAME with your actual credentials. Both of these values can be found under your Facebook Developer Dashboard. Dealing with Cordova plugin is quite difficult. Big thanks to the Ionic team who gave birth to Ionic Native (a TypeScript wrapper for the Cordova plugins) that can be used in a more Ionic way for adding any native functionality in the app as per your needs.

It is the time to install Facebook package from Ionic Native. For that, you need to again open your terminal and write the following:

$ npm install --save @ionic-native/facebook

Once after completing the installation process, now let your app to utilize it. You can do this via importing it in your app.module.ts file.

import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar'
import { Facebook } from '@ionic-native/facebook'

@NgModule({
...,
providers: [ SplashScreen, StatusBar, Facebook ]
})
export class AppModule {}

Add Platform to Facebook

All is set up under development environment. Right? Now lets Facebook know which platforms would you prefer. For example, you’re considering two platforms, iOS and Android. To add both these platforms, navigate to your Facebook dashboard and tap the settings option. There you will notice a button “Add Platform” just right under the app’s information. Click on this button.

Add Platform to Facebook

 

After clicking on this button, you can notice several options for the platforms you’re adding. Let’s first begin with iOS platform. Here you will have to fill the value for “Bundle ID” option.

 

iOs

 

In case you don’t know the Bundle ID, check your default package name while creating an Ionic App (under your config.xml file). You can use this same name for your Bundle ID.

widget id="co.ionic.facebook346" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">

We recommend you to replace “co.ionic.facebook346″ (or what you see there) with something which is much more “On Brand” in tune with your app or business. After adding Bundle ID, carry on with the app creation process and follow the same process for the Android platform. This process differentiates itself in the only way of calling it “Google Play Package Name” in place of “Bundle ID”.

 

Android

 

2. Facebook Authentication Under Firebase Console

As all has been set up under Facebook developer console, you need to navigate to Firebase control for Facebook authentication for your app.

To authorize Facebook sign-in, navigate to your Firebase Console and find the app you’re making use of. Under the app’s dashboard, follow this path:

Authentication > Sign-In Method > Facebook, and click on “Enable” toggle option.

Facebook Sign-In in Firebase

 

Once you’ve clicked it, you will see some field boxes asking for some information, like your Facebook App ID and App secret key. If you don’t know the value for these field boxes, you can find both these under your Facebook console, inside the settings of your app.

3. Users Authentication

You can authenticate your users in whatever step of your app’s process you want. Here is the code that you can utilize by just copying into whichever page you’re using. The foremost thing is to avail the authorization from Facebook. For that, you have to import Facebook plugin from Ionic Native and request your users to sign in.

import { Facebook } from '@ionic-native/facebook'

constructor(public facebook: Facebook){}

facebookLogin(): Promise<any> {
return this.facebook.login(['email']);
}

That function is totally responsible for opening the Facebook native widget and requests the users for app authorization to utilize their data for sign-in objectives.

Now is the time to deal with function response. It will outcome a Facebook access token that should be passed to Firebase.

import firebase from 'firebase';
import { Facebook } from '@ionic-native/facebook'

constructor(public facebook: Facebook){}

facebookLogin(): Promise<any> {
return this.facebook.login(['email'])
.then( response => {
const facebookCredential = firebase.auth.FacebookAuthProvider
.credential(response.authResponse.accessToken);

firebase.auth().signInWithCredential(facebookCredential)
.then( success => {
console.log("Firebase success: " + JSON.stringify(success));
});

}).catch((error) => { console.log(error) });
} 

To easily understand the development process, let’s break down this aforeshared code:

const facebookCredential = firebase.auth.FacebookAuthProvider
.credential(response.authResponse.accessToken);

This coding line is used to create a credential object that can be passed to Firebase. After creating such credential object, pass this to Firebase:

facebookLogin(): Promise<any> {
return this.facebook.login(['email'])
.then( response => {
const facebookCredential = firebase.auth.FacebookAuthProvider
.credential(response.authResponse.accessToken);

firebase.auth().signInWithCredential(facebookCredential)
.then( success => {
console.log("Firebase success: " + JSON.stringify(success));
});

}).catch((error) => { console.log(error) });
}

This coding line “firebase.auth().signInWithCredential(facebookCredential)” ensures about your user’s account creation under your Firebase app. Plus, it also authenticates the user under the Ionic app and stores some data related to authentication inside local storage. This authentication details may include tokens, provider information, tokens and other information.

We at Envision Ecommerce have developed Facebook login ionic app:

https://github.com/envisionecommerce/FBAppDemo

Regardless of this, our highly qualified app development team is there for you. Envision Ecommerce, best mobile app development company, provides the utmost support to customers in developing their Ionic based hybrid business apps at affordable prices. Feel free to contact us at [email protected] or visit: https://www.envisionecommerce.com/blog/store/

What’s New in Laravel 5.5!

Recently, the team Laravel has announced the new series of Laravel 5.5 on its official page. Though, Laravel 5.5 is not yet out, but the documentations are live now.

So here we update you with the 5.5’s powerful features and new exciting changes that will increase security as well as productivity at the same time.

Take a quick look at the new upcoming 5.5 release.

Excel with PHP 7.0+

PHP 7 incorporates speed improvements which will diminish CPU stack significantly. So this is definitely the most important upgradition for those who are using Laravel 5, as it makes things even easier and speeds up database migration with no data loss.

Whoops

Whoops – an error PHP handler framework, used by Laravel 4, was evacuated with the arrival of Laravel 5.0. But, now it is coming back with Laravel 5.5. Whoops actually helps in making the irritating PHP blunders/errors, a little less irritating by changing the way they appear.

# “vendor:publish” Prompt You select a provider or tag

When you run the vendor:publish command in the old version of Laravel, it will publish only migrations, views, configs and other different resources of all vendors. But in 5.5, running the specific command will make easier for you to publish a provider or tag, you want. In fact,

You can also bypass the particular prompt by determining the following command–all’ or ‘–provider’ flag with thepublish`

Email Themes

This new version of Laravel includes the ability to directly indicate a custom theme to Mailable classes, so that you can make a CSS style-sheet like the following:

touch resources/views/vendor/mail/html/themes/batman.css

After that, in your mailable class, indicate this specific filename as ropa perty.

class SendInvoice extends Mailable
{
    protected $theme = 'batman';
    ...
}

Render Mailables to the Browser

Testing your email templates crosswise email clients can be annoying. But, Laravel 5.5 has included the facility to directly show them through your routes and allow them to make instant changes. Make a Mailable like the following:

php artisan make:mail UserWelcome --markdown=emails.user.subscription.canceled

After that, render it by route:

Route::get('/no/way', function () {
    return new App\Mail\UserSubscriptionCanceled();
});

Fresh Migrations

5.5 includes a new Artisan command to the migrate: namespace, which is very much alike to migrate:refresh. This command will drop all tables and relocates them from beginning instead of rolling back your current migrations.

Automatic Package Discovery

In the oldest versions of Laravel, for packages, required to register its service providers as well as including aliases. But in 5.5, it includes the ability to automatically register service providers and include aliases by the package’s composer.json file like the following:

"extra": {
    "laravel": {
        "providers": [
            "The\\Dark\\Knight\\BatmanServiceProvider"
        ],
        "aliases": {
            "Bar": "The\\Dark\\Knight\\Batman"
        }
    }
}

Front-end Presets

As we all know, Laravel incorporates some CSS and JavaScript framework to help quicken coding the bare essential. In spite of the fact that you could expel them and begin over with your own inclinations, and the suggestion was just constrained to the Vue framework.
But, Laravel 5.5 presents three front-end presets, including Bootstrap, Vue, React and an option pick your own. With Vue, you can modify the preset by utilizing the following command:

php artisan preset reacts

You can modify respond in the above-mentioned command to bootstrap, vue or none in view of your inclination.

Improvement in Error Pages Design

There are small changes has been done in the design of the error pages: 404 or 50* in Laravel 5.5. And, some design increments with Flexbox which gets the error message fixated on the page.

Before 5.5:

Before laravel 5.5

In 5.5:

Befor laravel 5.5

Customer Error Reporting

Laravel 5.5 includes bolster for characterizing a report method on any custom exemption. In previous version of Laravel, you required to check in the Handler class’ report method, whether the specific exemption was tossed or not. Before you were performing the things something like the following:

 ...

class Handler extends ExceptionHandler
{
    ...

    public function report(Exception $exception)
    {
        if ($exception instanceof CustomException) {
            // Send email
        }

        parent::report($exception);
    }
}

However, with 5.5, you can remove this and enlist the report method in your custom exemption class. Laravel verifies whether there is a report method in your exemption class, if it does: calls it.

Streamlined Request Validation

To Request feature, Laravel 5.5 accompanies 2 changes.

1) You would now be able to straightforwardly call the validate method on your Request instance. So that you can call the validator on your Request instance, instead of utilizing the controller validator. You never again need to pass the request as the first argument to the validator. See the example below:

...

public function store()
{
    request()->validate([
        'title' => 'required',
        'body' => 'required'
    ]);

    return Post::create(request(['title', 'body']));
}

The second alteration you can make is that the validator restores the request information which you can store in a variable and pass on to the make technique for the model.

...

public function store()
{
    $post = request()->validate([
        'title' => 'required',
        'body' => 'required'
    ]);

    // $data = request()->only('title', 'body');

    return Post::create($post);
}

You should be cautious with this since the information returned by the validator will just contain the fields characterized in the rules. This includes a few security, however you can lose information if a few fields were not characterized rules for. To stay away from this trap, you can include the field with a void lead like the following:

public function store()
{
    $post = request()->validate([
        'title' => 'required',
        'body' => 'required',
        'fieldWithNoRules' => '',
        'andAnotherOne' => ''
    ]);

    // $data = request()->only('title', 'body');

    return Post::create($post);
}

Exception Helper Functions

throw_if and throw_unless are two new helper functions in Laravel 5.5 that help you do exactly or throw exceptions more elegantly. However, if you throw an exception, depend on a condition then these may enable you to diminish a contingent block to a solitary line. They both acknowledge 3 arguments with the 3rd being optional:

  • Boolean

 

  • Exception Class

 

3) An Exception message passed, if you didn’t pass with the instantiation of the exception in the 2nd argument. If the boolean is positive throw_if throws the exception and if the boolean is negative throw_unless throws the exception. See the examples below:

/ For `throw_if:

$foo = true;
throw_if($foo, new BarException('Foo is true'));
// or
throw_if($foo, BarException::class, 'Foo is true');

// For `throw_unless:

$phoo = false;
throw_unless($phoo, new BazException('Phoo is false'));
// or
throw_unless($phoo, BazException::class, 'Phoo is false');

Custom Validations Rules (CVR)

Though nothing is new with custom validation rule feature, but Laravel 5.5 facilitate you to handle the validation. To characterize a specific feature CVR, you have to make a class with two strategies, such as ‘passes’ and ‘message’.
However, you can put this class anywhere in the App\Rules namespace. The passes strategy acknowledges 2 contentions, such as ‘attribute’ and ‘value’, which you can utilize to confirm the field.

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class CustomRule implements Rule
{   
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        // must return true or false for the validation to pass or fail
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        // return a string here for the failing condition
    }
}

Your CVR should actualize the Laravel’s Illuminate\Contracts\Validation\Rule contract.

You can utilize this CVR anywhere in the controller validator or in a form request class or the validator from the Request instance. If you’re utilizing a custom rule, you cannot pass a string with rules isolated by a comma. You have to pass each rule as a solitary component assembled in an exhibit the following way:

$request->validate([
    'someField' => [
        'required', 'min:4', new CustomRule()
    ]
]);

Model Factory Generators

This new version of Laravel facilitates you to easily generate model factories with a brand new Artisan command known as make:factory. See the example below:

php artisan make:factory PostFactory

This will create a new file in the database/factories folder known as PostFactory.php. Not only this, it also allows to generate a factory while creating a model

php artisan make:model Post -f

In fact, You can also pass the flag like -c to include a controller and -m to include a migration, as it will help in rapidly throwing together an asset.

This is all about the new series of Laravel 5.5. Now we hope this guide or above mentioned 5.5 enhancements will get you prepare for the upcoming goodness.

Happy Coding!

React Vs AngularJs Comparison – Who Wins?

Not at all like human beings, technologies don’t have the ability to vie with and slaughter one another. However, the inception of latest technologies usually affects the prominence & market share of standard technologies. Both React & Angular JS are extremely famous frameworks used widely by various mobile app development companies plus web programmers over the world. Each framework is beneficial in its own particular manner and has their own plus sides and negative sides relying upon what mobile app developer are craving for. Let’s analyse the comparison of both so that you can pick the right technology.

AngularJS

AngularJS is essentially the right answer for dealing with data binding. Data binding in AngularJS apps means the automatic data synchronization that works amongst the model (customer input source) and the “view”. This data synchronization works in a way that when the model gets changed, the view mirrors get changed, and vice-versa. By removing or ignoring multiple steps, AngularJS can be an exceptionally captivating choice.

ReactJS

ReactJS is an outstanding framework to deal with DOM (Document Object Model) management, primarily in a case of handling large amounts of data. React supports the creation of a virtual DOM in JavaScript that carries on as an intermediate representation of the DOM. And, this intermediate representation makes it straightforward to make up your mind regarding the element to alter in the DOM and what the outcomes might be.

Comparison Between AngularJS & ReactJS:

Based on Age:

ReactJS has recently come into existance, whereas Angular has been there since long. Thereby, the support for Angular is way higher as compared to ReactJS. On the other hand, Angular’s coding is much more perplexing than ReactJS’s coding. Therefore, if you are using ReactJS, you require a very less assistance from the support communities.

Based on Speed and Features

AngularJS is much more effective but it lacks in speed compared to React. At the point when there is a large database to drag data from, users may have to encounter a slight delay. React is speedier than AngularJS thus it works well during massive data rendering process. It makes a usage of the full MVC architecture. That’s why it is best for skilled coders to use.

It utilizes solely the view part thus it holds less features compared to Angular JS. Also, it would be a wise decision for starters to start with React.

Based on Deployment

AngularJS works from the HTML viewpoint and offers restricted access to the tools for packaging plus code deployment. On the other hand, React works from the Javascript viewpoint and offer a library such as RequireJS to stack the code.

Based on Debugging:

It is simple and effortless to write code in AngularJS however tough to debug it. Moreover, with React, it is significantly simpler to debug the pre-written code. You only need to access React Developers Tools extension for your chrome browser and get started.

The Final Verdict – Who Wins?

Well, without any further ado, the appropriate answer is both. Let’s make use of both with the company of each other and not in opposition to one another. The clean & simple JavaScript environment offers mobile app developers with greater adaptability and effortless learning. And at the point when Angular limits something, you can anticipate that React will give you full freedom. Uniformly effective, so utilize a mix of both in your next enormous mobile app project.

If you are looking for affordable yet high-quality mobile app development solutions, our highly qualified app development team is available for you. Envision Ecommerce – the best mobile app development company, offers the utmost support to customers in developing their AngularJS mobile app solutions at affordable prices. You can contact us at [email protected] or visit: https://www.envisionecommerce.com/blog/store/.