Sunday, October 23, 2016

Laravel 5.3 : Integration of API Authentiation (Passport)

Hi Everybody

Today we will learn how to itegrate Passport in laravel 5.3 and generate tokens password grant client. Laravel Passport provides a full OAuth2 server implementation for our Laravel application. APIS do not maintain session state between requests. So we need a tokens to Authenticate users. 

Step 1 : Go to your project folder and Install Passport via the Composer package manager with following command.

 composer require laravel/passport  

Step 2 : Register the Passport service provider in the providers array of  yourconfig/app.php configuration file:

Laravel\Passport\PassportServiceProvider::class,
Step 3 : The Passport service provider registers its own database migration directory with the framework, so we should migrate our database after registering the provider. The Passport migrations will create the tables our application needs to store clients and access tokens:

php artisan migrate
Step 4 : We should run the passport:install command. This command will create the encryption keys needed to generate secure access tokens. In addition, the command will create "personal access" and "password grant" clients which will be used to generate access tokens:

php artisan passport:install

Step 5 : After running this command, add the Laravel\Passport\HasApiTokens trait to our App\User model. This trait will provide a few helper methods to our model which allow us to inspect the authenticated user's token and scopes:

<?php

namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}
Step 6 : We should call the Passport::routes method within the boot method of our AuthServiceProvider. This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:

<?php

namespace App\Providers;

use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();
    }
}
Step 7 : Finally, in our config/auth.php configuration file, we should set the driver option of the api authentication guard to passport. This will instruct our application to use Passport's TokenGuard when authenticating incoming API requests:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],
Above step also mentioned in laravel official document for installing Passport.

Now go to your controller, where we want to generate access and refresh token. Inside the controller write the following script.

 $http = new GuzzleHttp\Client();  
 $oauth_client = DB::table('oauth_clients')->where('name', '=', 'Laravel Password Grant Client')  
   ->where('password_client', '=', 1)->first();  
 $response = $http->post(url('/') . '/oauth/token', [  
   'form_params' => [  
     'grant_type' => 'password',  
     'client_id' => $oauth_client->id,  
     'client_secret' => $oauth_client->secret,  
     'username' => $request->email,  
     'password' => $request->password,  
     'scope' => '',  
   ],  
 ]);  
 $response_body = json_decode((string)$response->getBody(), true);  
 $access_token = $response_body['access_token'] ;  
 $refresh_token = $response_body['refresh_token'];  

Now token is generated through password grant client.

Thanks



Saturday, October 8, 2016

Laravel ajax and 500 internal server error

Hi Everyone

Today, we will learn what are the reason and their solution behind the 500 internal server error when using ajax in laravel. Sometimes when we use ajax with Laravel, it gives 500 internal server error. Following are the reasons:

CSRF:

The common reason behind 500 internal server error is missing CSRF token. In Laravel, CSRF token is required for all forms. People generally forget submitting the token with ajax request. Submitting token less ajax request results in 500 internal server error.

To fix this,  just add a hidden field in the form. Below is the code for us to add in our form:

1. For Blade Template Users:

 <input type="hidden" name="_token" value="{{ Session::token() }}">  

2. For non Blade Users:

 <input type="hidden" name="_token" value="<?php Session::token() ?>">  

3. Directly as ajax data:

 var request = $.ajax({  
  url: "test.php",  
  method: "POST",  
  data: { _token : <?php Session::token() ?>},  
  dataType: "html"  
 });  

This will solve your problem.

Other reason for this might be

WRONG ROUTE:

You may be submitting ajax data to wrong route type and even wrong url (404). So first double check the path you are submitting to. Second, check whether the route accepts “Post” or “Get” data type.
Because submitting post data via Get method or vice versa will results in Laravel ajax giving 500 Internal Server Error.

DATA TYPE RETURNED:

If you are returning Boolean and your ajax code is set for Json or any other data type then chances are that you will get internal server error. Try to set data type for all ajax response to json. If you are using jQuery then set dataType to xml.

 var request = $.ajax({  
  url: "/action",  
  method: "POST",  
  data: { id : userId },  
  dataType: "json"  
 });  

CROSS DOMAIN CONFIGURATION:

If you are using ajax for cross domain requests then be sure that you are sending proper headers.
In case of jQuery, just set the crossDomain variable to true. Alternatively set dataType to “jsonp”

.HTACCESS

Check your .htaccess file for any error specially after you have edited it.

Hope this will help someone.

Thanks


Friday, September 30, 2016

Multiple database connections in Laravel 5

Hi Everyone

Today we will learn how to do multiple database connections in laravel.

Sometimes we need to fetch data from multiple database. How can we do it in laravel? To achieve this we need to do following step.

In Laravel in config/database.php file, contains an array of all possible connections like MySQL, PostgreSQL, SQL Server.

 'connections' => [  
     'sqlite' => [  
       'driver'  => 'sqlite',  
       'database' => storage_path('database.sqlite'),  
       'prefix'  => '',  
     ],  
     'mysql' => [  
       'driver'  => 'mysql',  
       'host'   => env('DB_HOST', 'localhost'),  
       'database' => env('DB_DATABASE', 'forge'),  
       'username' => env('DB_USERNAME', 'forge'),  
       'password' => env('DB_PASSWORD', ''),  
       'charset'  => 'utf8',  
       'collation' => 'utf8_unicode_ci',  
       'prefix'  => '',  
       'strict'  => false,  
     ],  
     'pgsql' => [  
       'driver'  => 'pgsql',  
       'host'   => env('DB_HOST', 'localhost'),  
       'database' => env('DB_DATABASE', 'forge'),  
       'username' => env('DB_USERNAME', 'forge'),  
       'password' => env('DB_PASSWORD', ''),  
       'charset' => 'utf8',  
       'prefix'  => '',  
       'schema'  => 'public',  
     ],  
     'sqlsrv' => [  
       'driver'  => 'sqlsrv',  
       'host'   => env('DB_HOST', 'localhost'),  
       'database' => env('DB_DATABASE', 'forge'),  
       'username' => env('DB_USERNAME', 'forge'),  
       'password' => env('DB_PASSWORD', ''),  
       'charset' => 'utf8',  
       'prefix'  => '',  
     ],  
   ],  

Suppose we have to make connection for multiple database on mysql.

So we will make another array in connection like below.

 'connections' => [   
     'mysql_external' => [  
       'driver'  => 'mysql',  
       'host'   => env('DB_HOST', 'localhost'),  
       'database' => env('DB_DATABASE', 'forge'),  
       'username' => env('DB_USERNAME', 'forge'),  
       'password' => env('DB_PASSWORD', ''),  
       'charset'  => 'utf8',  
       'collation' => 'utf8_unicode_ci',  
       'prefix'  => '',  
       'strict'  => false,  
     ],    
   ],  

And we will use different env variable Like below.

  'mysql_external' => [  
       'driver'  => 'mysql',  
       'host'   => env('DB_EXT_HOST', 'localhost'),  
       'database' => env('DB_EXT_DATABASE', 'forge'),  
       'username' => env('DB_EXT_USERNAME', 'forge'),  
       'password' => env('DB_EXT_PASSWORD', ''),  
       'charset'  => 'utf8',  
       'collation' => 'utf8_unicode_ci',  
       'prefix'  => '',  
       'strict'  => false,  
     ],  

Now our env file look like below for database connections.

 DB_HOST=localhost  
 DB_DATABASE=testing  
 DB_USERNAME=homestead  
 DB_PASSWORD=secret  
 DB_EXT_HOST=localhost  
 DB_EXT_DATABASE=testing2  
 DB_EXT_USERNAME=homestead  
 DB_EXT_PASSWORD=secret  

To connect new database in our controller

 class TestController extends Controller  
 {  
   public function getTest()  
   {  
     $db_ext = \DB::connection('mysql_external');  
     $countries = $db_ext->table('countries')->get();  
     print_r($countries);  
   }  
 }  

So, by using above step, we can fetch and insert data from external database.

Hope it will help you.

Thanks

Friday, September 23, 2016

Token Mismatch error in Laravel

Hi Everyone

Today we are going to learn, how to solve token mismatch error on login page.

Sometimes we noticed that, on the login page of Laravel 5, when we leave this page for sometimes and then click on login button, then it shows token mismatch error.

This is because session time of laravel has been expired and current token for that page do not match the actual page.

To prevent this kind of error, we have to write below code

Open the file :  app/Exceptions/Handler.php

and add below code in render function.
  public function render($request, Exception $e)  
   {  
     if ($e instanceof \Illuminate\Session\TokenMismatchException) {  
       return redirect()->guest('auth/login');  
     }  
     return parent::render($request, $e);  
   }  

Now instead of showing token mismatch error, it will redirect to login page and refresh the token.

Thanks

Thursday, September 15, 2016

Laravel: Creating pagination using array instead of an object

Hi Everyone

Today we will going to learn, How to create pagination using array instead of an object.

Generally, In Laravel we use simplePaginate() or paginate() functions to paginate. But these function by default work on if we have an object.

Some time we need to pass an array in blade template. So how can we do pagination on array. To do this we have to use following code.

Firstly include these two lines in our controller where we want to do pagination.

 use Illuminate\Pagination\Paginator;  
 use Illuminate\Pagination\LengthAwarePaginator;  

Then make a function like below in same controller.

   public function paginate($items, $perPage)  
   {  
     $pageStart = \Request::get('page', 1);  
     $offSet = ($pageStart * $perPage) - $perPage;  
     $itemsForCurrentPage = array_slice($items, $offSet, $perPage, true);  
     return new LengthAwarePaginator($itemsForCurrentPage, count($items), $perPage, Paginator::resolveCurrentPage(), array('path' => Paginator::resolveCurrentPath()));  
   }  

In above function first parameter is an array whom we want to paginate and second parameter is number of item we want to show per page.

Now lets see how we can use it.

In the controller suppose we have another function, from where we want to sent data to view.

 public function getData($){  
     $getData = \App\ModelName::all();  
     $dataArray = array();  
     $i=0;  
     foreach($getData as $data){  
       $dataArray[$i]['id'] = $data->id;  
       $i++;  
     }  
     $data = array('data' => $this->paginate($dataArray,'15'));  
      return view("viewName", $data);  
   }  

In blade template we have to use following line of code to show paging.

 {!! $data->render() !!}  

Hope this will help someone.

Thanks

Sunday, September 11, 2016

PHP: Exploring Regular Expression Syntax validating a phone number

Hi Everybody

Today we will learn some regular expression syntax while validating an international phone number for usa and uk.

Following are the format we are going to use an example:

+44 (1232582358)
+1 1472583695
+44 (123)(258)(2358)
+1 (123)(258)(2358)
+1 (123).(258).(2358)
+1 (123)-(258)-(2358)
+1 (123)-258-2358
+1 (0)(123)-258-2358

Seeing above format means, number always start with '+' sign and followed by 1 or 44.

So we will start our expression with \+(44|1)
After that can be space, hyphen(-) or dot (.) will come.

For that we will write ([ -\.])?
Here "?" means 0 or one of either space,hyphen or dot. 

After that some people do write (0) for their national representation. E.g
+1 (0)(123)-258-2358

Some people write some not. So either it will come at one time or not come.

For that we will write (\(0\))?, means either (0) will come one time or not come.

After that , people write their 10 digit number with bracket or without. or 4-3-3 format or 3-3-4 format with or without bracket. Some people use dot(.) or space instead of hyphen.

Below expression cover all those :

(\(?[\d]{10}\)?|(\(?[\d]{4}\)?([ -\.])*\(?[\d]{3}\)?([ -\.])*\(?[\d]{3}\)?)|\(?[\d]{3}\)?([ -\.])*\(?[\d]{3}\)?([ -\.])*\(?[\d]{4}\)?)$

I am going to explain this in step by step.

(\(?[\d]{10}\)? means any digit of whose length is 10 with or without bracket.

"|" sign represents or.

([ -\.])? represents either space , hyphen or dot will come or not come.

\(?[\d]{3}\)? means any digit of whose length is 3 with or without bracket.

After that i have use same expression with "|" sign.

And at the end of expression $ sign represents end of expression. 

Hope it will help you to understand some basic use of regular expression syntax.

Thanks





Sunday, September 4, 2016

Integrate slack recipe with deployer

Hi

Today we will learn how to integrate slack message with deployer. After completing the deployment, a message will be send to slack channel.

First, copy/download the slack recipe from given url

"https://github.com/deployphp/recipes/blob/master/recipes/slack.php", then put it into under your recipe folder.

In this page, please configure below as per your requirement.

 // slack.php
 $defaultConfig = [
     'channel' => '#your slack channel',
     'icon'   => ':sunny:',
     'username' => 'slack username',
     'message' => "Deployment to `{{host}}` on *{{stage}}* was successful\n({{release_path}})",
     'app'   => 'app-name',
   ];
After that, in our deploy.php, include this slack recipe.

 // deploy.php  
 require 'vendor/deployer/deployer/recipe/slack.php';  

after including slack recipe, please configure below setting for slack.

 // deploy.php  
 set('slack', [  
   'token' => 'your slack token',  
   'team' => 'your slack team like team.slack.com',  
   'app'  => 'mrl sandbox',  
 ]);  

Slack token can be generate from slack api website url.

Since we should only notify Slack channel of a successfull deployment, the deploy:slack task should be executed right at the end.

 // deploy.php  
 after('deploy', 'deploy:slack');