laravel中的多重身份验证系统

时间:2020-02-06 23:36:05

标签: laravel

我正在laravel中创建多重身份验证系统,我为每个实体创建了两个单独的表,一切正常,但是注册后我只面临一个问题,正在使用Web Guard的用户可以自动登录并重定向到用户仪表板,它是完美的,但是如果其他用户使用其他防护,则在完成注册过程后,他们将无法自动登录系统。

所以我的问题是,一旦其他用户类型完成注册步骤,如何为他们启用自动登录过程?下面是我在项目中使用的代码

路由文件

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Auth::routes(['verify' => true]);

Route::get('/home', 'HomeController@index')->name('home')->middleware('verified');

Route::get('/seller/dashboard', 'SellerHomeController@index')->name('seller.dashboard');
Route::get('/seller/login','Auth\Seller\SellerLoginController@showLoginForm')->name('seller.login');
Route::post('/seller/login','Auth\Seller\SellerLoginController@login');
Route::post('/seller/logout','Auth\Seller\SellerLoginController@logout')->name('seller.logout');
Route::post('/seller/password/email','Auth\Seller\SellerForgotPasswordController@sendResetLinkEmail')->name('seller.password.email');
Route::get('/seller/password/reset', 'Auth\Seller\SellerForgotPasswordController@showLinkRequestForm')->name('seller.password.request');
Route::post('/seller/password/reset','Auth\Seller\SellerResetPasswordController@reset')->name('seller.password.update');
Route::get('/seller/password/reset/{token}', 'Auth\Seller\SellerResetPasswordController@showResetForm')->name('seller.password.reset');
Route::get('/seller/register','Auth\Seller\SellerRegisterController@showRegistrationForm')->name('seller.register');
Route::post('/seller/register','Auth\Seller\SellerRegisterController@register');

SellerLoginController

namespace App\Http\Controllers\Auth\Seller;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SellerLoginController 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 = '/seller/dashboard';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest:seller')->except('logout');
    }

    public function showLoginForm()
    {

        return view('auth.seller.login');
    }

    protected function attemptLogin(Request $request)
    {
        return $this->guard('seller')->attempt(
            $this->credentials($request), $request->filled('remember')
        );
    }

    protected function guard()
    {
        return Auth::guard('seller');
    }
}

SellerRegisterController

namespace App\Http\Controllers\Auth\Seller;

use App\Seller;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Auth\Events\Registered;

class SellerRegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/seller/dashboard';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest:seller');
    }

    public function showRegistrationForm()
    {
        return view('auth.seller.register');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'firstname' => ['required', 'string', 'max:255'],
            'lastname' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:sellers'],
            'business_name' => ['required', 'string', 'max:255'],
            'business_description' => ['required', 'string', 'max:255'],
            'business_location' => ['required', 'string', 'max:255'],
            'business_website' => ['required', 'string', 'max:255'],
            'password' => ['required', 'string', 'min:6', 'confirmed'],

        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        $seller =  Seller::create([
            'firstname' => $data['firstname'],
            'lastname' => $data['lastname'],
            'email' => $data['email'],
            'business_name' => $data['business_name'],
            'business_description' => $data['business_description'],
            'business_location' => $data['business_location'],
            'business_website' => $data['business_website'],
            'business_logo' => 'test_logo.jpg',
            'password' => Hash::make($data['password']),
            'user_type' => $data['user_type'],
        ]);
       return $seller;
    }
}// code end here

3 个答案:

答案 0 :(得分:1)

发生这种情况是因为您没有在guard上定义SellerRegisterController方法,并且默认实现检索了默认驱动程序(即web)。

该保护方法为register的{​​{1}}方法中的自动登录过程提供保护:

RegistersUsers

您必须重写$this->guard()->login($user); 类中的guard方法以返回正确的驱动程序,并允许trait在正确的SellerRegisterController驱动程序上执行登录过程:

sellers

答案 1 :(得分:0)

默认情况下,Laravel Auth以“用户”表为主要数据。如果要进行多次身份验证,首先要做的是创建一个具有可通知特征的模型

型号

class Admin extends Authenticatable
{
   use Notifiable;
}

此后,您需要在config/auth.php中创建守护程序和提供程序 这样的例子

<?php

[...]
'guards' => [
    [...]
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
    'writer' => [
        'driver' => 'session',
        'provider' => 'writers',
    ],
],
[...]

[...]
'providers' => [
    [...]
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Admin::class,
    ],
    'writers' => [
        'driver' => 'eloquent',
        'model' => App\Writer::class,
    ],
],
[...]

在登录控制器中,您需要通过执行以下操作来检查哪个防护正在尝试登录

Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))

如果您需要更多详细信息,请尝试阅读此https://pusher.com/tutorials/multiple-authentication-guards-laravel

答案 2 :(得分:0)

// Adminmiddleware
 if(Auth::check() && Auth::user()->role->id == 1)
      {
        return $next($request);
      }else {
        return redirect()->route('login');
      }

//  Authormiddleware
 if(Auth::check() && Auth::user()->role->id == 2 )
      {
        return $next($request);
      }else {
        return redirect()->route('login');
      }

// Admin Route
Route::group(['as'=>'admin.','prefix'=>'admin','namespace'=>'Admin','middleware'=>['auth','admin']], function (){
    Route::get('dashboard','DashboardController@index')->name('dashboard');


});
// Auhtor Route
Route::group(['as'=>'user.','prefix'=>'user','namespace'=>'Author','middleware'=>['auth','user']], function (){
    Route::get('dashboard','DashboardController@index')->name('dashboard');
});

// only auht route
Route::group(['middleware'=>['auth']], function(){
    Route::post('favorite/{post}/add','FavoriteController@add')->name('post.favorite');
    Route::post('review/{id}/add','ReviewController@review')->name('review');
    Route::get('file-download/{id}', 'PostController@downloadproject')->name('project.download');
    Route::post('file-download/{id}', 'PostController@downloadproject');
});