menu

Wednesday 24 July 2019

how can write restful / authenticate API in Laravel latest version

Hope you have already install laravel with new version 5.5 or above

You can write restful authenticate API through the passport package using bellow command, So open your terminal and run bellow command:

$ composer require laravel/passport



After install successfully package, open config/app.php file and add service provider "PassportServiceProvider::class".
config/app.php'providers' =>[Laravel\Passport\PassportServiceProvider::class,],


Now we require to run the migration command 

After run migration command you will get several new tables in the database. If migration table is not there then run the command $ php artisan migrate:install

$ php artisan migrate

Run command and install the package.

$ php artisan passport:install

After successfully install passport package, we have to do the configuration on three place model, service provider and auth config file.

In the customer model, we need to add HasApiTokens class of Passport,
In the AuthServiceProvider we need to add “Passport::routes()”,
In the auth.php, we need to add an API auth configuration.

app/Customer.php
=================================
<?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;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
=============================================================
app/Providers/AuthServiceProvider.php
=============================================================
<?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(); 
    } 
}
===========================================================
config/auth.php
===========================================================
<?php
return [
'guards' => [ 
        'web' => [ 
            'driver' => 'session', 
            'provider' => 'users', 
        ], 
        'api' => [ 
            'driver' => 'passport', 
            'provider' => 'users', 
        ], 
    ],
===========================================================
Create API Route
In this step, we will create API routes. Laravel provides api.php file for write web services route. So, let’s add a new route on that file.
===========================================================
routes/api.php
===========================================================
<?php
/* Define API Routes for call request */

Route::post('login', 'API\UserController@login');

Route::post('register', 'API\UserController@register');

Route::group(['middleware' => 'auth:api'], function(){

Route::post('details', 'API\UserController@details');

});
============================================================
Now we need to create new controler in API folder. CustomerController.php add code:
============================================================
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use App\User; 
use Illuminate\Support\Facades\Auth; 
use Validator;
class CustomerController extends Controller 
{
public $successStatus = 200;
/** 
     * login api 
     * 
     * @return \Illuminate\Http\Response 
     */ 
    public function login(){ 
        if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ 
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')-> accessToken; 
            return response()->json(['success' => $success], $this-> successStatus); 
        } 
        else{ 
            return response()->json(['error'=>'Unauthorised'], 401); 
        } 
    }
/** 
     * Register api 
     * 
     * @return \Illuminate\Http\Response 
     */ 
    public function register(Request $request) 
    { 
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required',
            'c_password' => 'required|same:password',
        ]);


        if($validator->fails()){
            return $this->sendError('Validation Error.', $validator->errors());       
        }


        $input = $request->all();
        $input['password'] = bcrypt($input['password']);
        $driver = Driver::create($input);
        $success['token'] =  $driver->createToken('MyApp')->accessToken;
        $success['name'] =  $driver->name;


        return $this->sendResponse($success, 'Customer register successfully.');
    }
}
===============================================================
Almost every thing has done now ready to run commond:

$ php artisan serve

Laravel development server started: <http://127.0.0.1:8000>

Now you hit register and login API through Postman

http://localhost:8000/customer/register

{ "success": true, "data": { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImQ4YzAxNDMzZWVjN2JlNDcxM2U5ZmI5NmE0ODM1MzJiNzAwYTY2YjJiOGE5YmE4MTNhMGU3NDAxNDJmYmJmZDJiZWY4ODFmZGUzMDkwYzRhIn0.eyJhdWQiOiIxIiwianRpIjoiZDhjMDE0MzNlZWM3YmU0NzEzZTlmYjk2YTQ4MzUzMmI3MDBhNjZiMmI4YTliYTgxM2EwZTc0MDE0MmZiYmZkMmJlZjg4MWZkZTMwOTBjNGEiLCJpYXQiOjE1NjM5NzYxMTQsIm5iZiI6MTU2Mzk3NjExNCwiZXhwIjoxNTk1NTk4NTE0LCJzdWIiOiI2Iiwic2NvcGVzIjpbXX0.V8o37YcjfNPmP6_afoWYsqyxHplcyjcHJdx0Y6k3LfWKmUTzs79gm-w-cm771b4GlBgZI5B-zm5hxan9ny8C_PxzH6Fpe_ztg_pD1LTJhPPg4y_JWKVpeleK8oZYgFHT_CewN43KF_ZWVJ_IRuxdXkeaj6sDkh2qt9iGJ2oXUQKLaxsVuWCBfXP2RDA5xgqCYDI-Qgr3nn_YiQq-dR1UxyJ1TPJdsOPo2Xdc4NsTTL__j7rnA_VUdK6aYTJ-ik4IJg4iytK1DNCNH1VHned3tHamRtGumM6wl6kiO2aHM5-CtOW1DWK65BIhaKLcdU9dT1S-8prsKIQRvL-HNAU1rRooPJS1vwuuK66dtb8Io877K4p92wA6psPv7tmvumNFvA_72kT3oycWsl91gaQl3D3ki7lP9PHvtObc63c4wEdFkEkgSrttgCfJ1Wa_D-_PDDjjMkTvr-82LiYjqBQIeyLxO93PGHjP4LAn-d4B8YDdzheHLsjK_0Cb1l03aKFTymsel0CQX-dtwJ-WA6CvFS7acJQQWHHQ-8-oAfRZds1LmzwgWAHmKiTaeAqXLjigUE4ll7apm7ywF7ZEkAgmk0vJ8zfM4jjZMPGFvIBfcfHd6O28FiPVD89u-wXAql-ijci_1syr5jKqgLfBcXtLjBnJWKI-vyXnK7z_5BZxDK8", "name": "Abc" }, "message": "Customer register successfully." }

http://localhost:8000/customer/login







Tuesday 16 July 2019

How to change Apache default port to a custom port

How to change Apache default port to a custom port

If you have sudo permission you can do easily. The only you need to follow these steps-

1. Change Apache port Ubuntu

Edit /etc/apache2/ports.conf file,

$ sudo vi /etc/apache2/ports.conf

Find the following line:

Listen 80
Replace with a random number of your choice like- Listen 8080.


After the change server to accept connections on port 8080 on all interfaces..
If you want the connect perticular IP to network do this Listen 192.168.1.101:8090
If your server has multiple IP addresses or network interfaces.

Save and close the file.

In Ubuntu and Debian, you need to change the port number in 000-default.conf file.

$ sudo vi /etc/apache2/sites-enabled/000-default.conf


Find the following line and change the port number.

<VirtualHost *:8080>
Save and close the file.

Now required to restart apache service to take effect the changes.

$ sudo systemctl restart apache2

We can check the port settings:

$ sudo netstat -tulpn | grep :8080
Sample output:

tcp6       0      0 :::8090                 :::*                    LISTEN      2067/apache2

You can open the browser and enter the URL: http://IP-address:8000.

Sunday 14 July 2019

How to reset root user password MYSQL on Ubuntu

After the MySQL setup, I have lost my user name and password now I don't want to reinstall. Then I can do this way reset lost root MySQL password on Ubuntu.
If You have access to the server with sudo.

First you need stop the currently running MySQL.

  • $ sudo service mysql stop
Now, create a /var/run/mysqld directory to be used by MySQL process to store and access socket file:
  • $ sudo mkdir -p /var/run/mysqld
Give the permision with mysql
  • $ sudo chown mysql:mysql /var/run/mysqld
Need to start MySQL manually with the following command.
  • $ sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &
  • $ [1] 1907
Check once process is running as expected.
  • $ jobs
  • [1]+  Running     sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &

Now in this stage we can access MySQL without password:
  • $ mysql -u root
After enter the command you are here
  • mysql>
Before to start using MySQL session you need to first flush privileges:
  • mysql> flush privileges;
Now we can reset root password. Use this command for reset MySQL root password to yourpassword:
  • mysql> use mysql; 
  • mysql> update user set authentication_string=PASSWORD('yourpassword') where User='root';

  • mysql> UPDATE user SET plugin="Adavance Web Tutorials" WHERE User='root';
logout from MYSQL
  • mysql> quit                                   
Terminate current mysqld process:
  • $ sudo pkill mysqld                                                                                                                                                        
  • $ jobs                                                                                                                                                                     
  • [1]+  Done       sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking

Now again start MYSQL services:
  • $ sudo service mysql start

If everything is good then we can login with new genrated password.
  • $ mysql -u root -p
  • Password : Yourpassword
  • mysql>
Enjoy with mysql.