Wednesday, December 27, 2017

Intoduction laravel multi auth

Step 1: Download laravel and run php artisan make:auth in terminal for create default login.

Step 2: Create two migrations for two logins. (Admin and customer) if you need default admin data you can create

migrations.

<?php
use Illuminate\Support\Facades\Schema; 
use Illuminate\Database\Schema\Blueprint; 
use Illuminate\Database\Migrations\Migration;
class CreateAdminTable extends Migration{ 
 /**     * Run the migrations.     *     * @return void     */ 
 public function up()    { 
Schema::create('site_admins', function (Blueprint $table) {             
 $table->integer('user_id', true);          
$table->string('name', 100)->nullable();          
$table->string('email', 100)->index('email')->unique();          
$table->string('password', 200)->nullable();             
$table->rememberToken(); 
 $table->timestamps(); 
}); 
}
    /**     * Reverse the migrations.     *     * @return void     */ 
 public function down()    { 
Schema::dropIfExists('site_admins'); 
 } 
}



<?php
use Illuminate\Support\Facades\Schema;
 use Illuminate\Database\Schema\Blueprint; 
use Illuminate\Database\Migrations\Migration; 
 
 class CreateCustomerAccountsTable extends Migration{ 
 /**     * Run the migrations.     *     * @return void     */     
public function up()    { 
Schema::create('customer_accounts', function(Blueprint $table)
          $table->bigInteger('customer_id', true); 
 $table->string('email', 100)->index('email')->unique();          
$table->string('password')->nullable();          
$table->string('first_name', 100)->nullable();          
$table->string('last_name', 100)->nullable();          
$table->string('phone_no', 20)->nullable();          
$table->string('activation', 32)->nullable()->index('activation');          
$table->dateTime('registered')->nullable(); 
 $table->dateTime('last_login')->nullable();          
$table->string('last_ip', 20)->nullable();          
$table->integer('default_billing_address_id')->nullable();          
$table->integer('default_shipping_address_id')->nullable(); 
 $table->boolean('customer_status')->default(0)->index('user_status')->comment('Unconfirmed =>0,Active =>1,Banned =>2'); 
 $table->rememberToken();             
$table->timestamps(); 
}); 
}
    /**     * Reverse the migrations.     *     * @return void     */ 
 public function down()    { 
Schema::dropIfExists('customer_accounts'); 
}}

Seeders.
 
 <?php
use Illuminate\Database\Seeder;
class AdminsTableSeeder extends Seeder{ 
 /**     * Run the database seeds.     *     * @return void     */ 
 public function run()    { 
\Illuminate\Support\Facades\DB::table('site_admins')->insert([             
'name' => 'Prabhath',             
'email' => 'prabhath@test.com', 
 'password' => Hash::make('123456'), 
]); 
}}


Step 3: Create models for respective gaurds. (user types)

Admin model.


<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
 use Illuminate\Notifications\Notifiable; 
use Illuminate\Foundation\Auth\User as Authenticatable; 
 
 class Admin extends Authenticatable{    use Notifiable;
    protected $table = 'site_admins';
    protected $primaryKey = 'user_id';
    protected $guard = 'admin';
    protected $fillable = [        'name', 'email', 'password',    ];
    protected $hidden = [        'password', 'remember_token',    ];}

Customer model.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
 use Illuminate\Notifications\Notifiable;
 use Illuminate\Foundation\Auth\User as Authenticatable; 
 
 class Customer extends Authenticatable{    use Notifiable;
    protected $table = 'customer_accounts';
    protected $primaryKey = 'customer_id';
    protected $guard = 'customer';
    protected $fillable = [        'first_name', 'email', 'password',    ];
    protected $hidden = [        'password', 'remember_token',    ];}

Step 4: Then create respective login, and password views for respective users.

Step 5: Create gaurds for two logins.

customer gaurd for customers and admin gaurd for admins.
For this first add your gaurds to Config/auth.php file. there are three arrays named gaurd, providers and passwords. You should add these gaurds to this arrays.

'guards' => [ 
  
'web' => [ 
 'driver' => 'session',         
'provider' => 'users', 
], 
 
     'api' => [         
'driver' => 'token', 
 'provider' => 'users', 
],
    'admin' => [         
'driver' => 'session',         
'provider' => 'admin', 
],
    'admin-api' => [ 
 'driver' => 'token',         
'provider' => 'admin', 
],
    'customer' => [         
'driver' => 'session', 
 'provider' => 'customer', 
],
    'customer-api' => [ 
 'driver' => 'token',         
'provider' => 'customer', 
], 
],


'providers' => [ 
 'users' => [         
'driver' => 'eloquent',         
'model' => App\User::class, 
],
    'admin' => [ 
 'driver' => 'eloquent', 
 'model' => App\Models\Admin::class, 
 ],
    'customer' => [         
'driver' => 'eloquent',         
'model' => App\Models\Customer::class, 
 ]
],
 
'passwords' => [     
'users' => [         
'provider' => 'users', 
 'table' => 'password_resets',         
'expire' => 60, 
 ],
 
    'admin' => [         
'provider' => 'admin',         
'email' => 'admin.auth.emails.password',         
'table' => 'password_resets', 
 'expire' => 60,    ],
 
    'customer' => [         
'provider' => 'admin',         
'email' => 'admin.auth.emails.password',         
'table' => 'password_resets',         
'expire' => 60,    ],], 

Step 6: Create middleware for respective user levels.

RedirectIfNotAdmin.php

<?php
namespace App\Http\Middleware;
use Closure;use Illuminate\Support\Facades\Auth; 
 
 class RedirectIfNotAdmin{    /**     * Handle an incoming request.     *     * @param  \Illuminate\Http\Request  $request     * @param  \Closure  $next     * @return mixed     */ 
 public function handle($request, Closure $next, $guard = 'admin')    { 
 if (!Auth::guard($guard)->check()) { 
 return redirect('/'); 
}
        return $next($request); 
}
 
 }



RedirectIfNotCustomer.php

<?php
namespace App\Http\Middleware;
use Closure;
class RedirectIfNotCustomer{    /**     * Handle an incoming request.     *     * @param  \Illuminate\Http\Request  $request     * @param  \Closure  $next     * @return mixed     */ 
 public function handle($request, Closure $next, $guard = 'customer')    { 
 if (!Auth::guard($guard)->check()) { 
 return redirect('/'); 
 }
        return $next($request);    }
 }

then register this two middlewares in kernel.php in routemiddleware array.

'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,



Step 7: Create login, logout and password reset routes for
        different logins. (Two user logins) 

Route::group(['middleware' => ['web']], function () { 
 
  
 Route::prefix(Config::get('settings.admin_folder'))->group(function () { 
 Route::get('/login','AdminAuth\LoginController@showLoginForm'); 
 Route::post('/login','AdminAuth\LoginController@login')->name('admin.login'); 
 Route::get('/logout', ['as' => 'logout', 'uses' => 'AdminAuth\LoginController@getLogout'])->name('logout'); 
Route::get('/admin-dashboard', 'AdminController@index');
 
Route::post('password/email', ['as' => 'password.email', 'uses' => 'Auth\ForgotPasswordController@sendResetLinkEmail']); 
Route::get('password/reset', ['as' => 'password.request', 'uses' => 'Auth\ForgotPasswordController@showLinkRequestForm']); 
Route::post('password/reset', ['as' => 'password.reset', 'uses' => 'Auth\ResetPasswordController@reset']); 
Route::get('password/reset/{token}', ['as' => 'password.reset', 'uses' => 'Auth\ResetPasswordController@showResetForm']); 
 }); 
     Route::prefix(Config::get('settings.customer_folder'))->group(function () { 
 Route::get('/login','CustomerAuth\LoginController@showLoginForm'); 
Route::post('/login','CustomerAuth\LoginController@login')->name('customer.login'); 
Route::get('/logout', ['as' => '/customer/logout', 'uses' => 'CustomerAuth\LoginController@getLogout'])->name('logout'); 
Route::get('/customer-dashboard', 'CustomerController@index'); 
         Route::post('password/email', ['as' => 'password.email', 'uses' => 'Auth\ForgotPasswordController@sendResetLinkEmail']); 
Route::get('password/reset', ['as' => 'password.request', 'uses' => 'Auth\ForgotPasswordController@showLinkRequestForm']); 
Route::post('password/reset', ['as' => 'password.reset', 'uses' => 'Auth\ResetPasswordController@reset']); 
Route::get('password/reset/{token}', ['as' => 'password.reset', 'uses' => 'Auth\ResetPasswordController@showResetForm']); 
});

Step 8: Create login controllers for two login with login logout   functions

Controllers\AdminAuth\LoginController.php
 
<?php
namespace App\Http\Controllers\AdminAuth;
use App\Http\Controllers\Controller;use Illuminate\Foundation\Auth\AuthenticatesUsers;use Illuminate\Http\Request;use Illuminate\Support\Facades\Auth;
class LoginController extends Controller{    /*    |--------------------------------------------------------------------------    | Login Controller    |--------------------------------------------------------------------------    |    | This controller handles authenticating users for the application and    | redirecting them to your home screen. The controller uses a trait    | to conveniently provide its functionality to your applications.    |    */
    use AuthenticatesUsers;
    /**     * Where to redirect users after login.     *     * @var string     */    protected $redirectTo = '/vwsadmin/admin-dashboard';
    protected $guard = 'admin';
    public function showLoginForm()    {         
if (view()->exists('auth.authenticate')) {             
return view('auth.authenticate');        }
        return view('admin.auth.login');//        return view('admin.login.login_form'); 
 }
    /**     * Create a new controller instance.     *     * @return void     */    public function __construct()    {        $this->middleware('guest')->except('getLogout');    }
    protected function guard()    { 
 return Auth::guard($this->guard); 
}
    public function getLogout(Request $request)    {         
$this->guard()->logout();         
return redirect('/'); 
}}

 
Controllers\CustomerAuth\LoginController.php

<?php
namespace App\Http\Controllers\CustomerAuth;
use App\Http\Controllers\Controller;use Illuminate\Foundation\Auth\AuthenticatesUsers;use Illuminate\Http\Request;use Illuminate\Support\Facades\Auth;
class LoginController extends Controller{    /*    |--------------------------------------------------------------------------    | Login Controller    |--------------------------------------------------------------------------    |    | This controller handles authenticating users for the application and    | redirecting them to your home screen. The controller uses a trait    | to conveniently provide its functionality to your applications.    |    */
    use AuthenticatesUsers;
    /**     * Where to redirect users after login.     *     * @var string     */    protected $redirectTo = '/vwscustomer/customer-dashboard';
    protected $guard = 'customer';
    public function showLoginForm()    { 
 if (view()->exists('auth.authenticate')) { 
 return view('auth.authenticate');        }
        return view('customer.auth.login'); 
}
    /**     * Create a new controller instance.     *     * @return void     */ 
 public function __construct()    { 
 $this->middleware('guest')->except('logout'); 
}
    protected function guard()    { 
 return Auth::guard($this->guard); 
}
    public function getLogout(Request $request)    {         
$this->guard()->logout(); 
 return redirect('/'); 
}}



 Step 9: All done 

get login user by calling gaurd name.

Auth::guard('customer')->check()
 
Auth::guard('customer')->user() 





Share/Bookmark

0 comments:

Post a Comment