Я пытаюсь реализовать паспорт Laravel для двух таблиц, поэтому одна будет по умолчанию для пользователя, а вторая - для устройств. Я создал в конфиге Guard для новой модели, и если я пытаюсь зарегистрировать устройства, то их запись в таблицу Device все, но, прямо сейчас, если я пытаюсь войти, он выдает мне эту ошибку:
Symfony\Component\Debug\Exception\FatalThrowableError: Argument 2 passed to Illuminate\Auth\SessionGuard::__construct() must implement interface Illuminate\Contracts\Auth\UserProvider, null given, called in /Users/petarceho/laravel/api/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on line 127 in file /Users/petarceho/laravel/api/vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php on line 99
Я новичок в Laravel, извините за неспособность объяснить это хорошо, но могу ли я использовать паспорт Laravel для двух таблиц.
Вот мой класс Controller для устройств:
<?php
namespace App\Http\Controllers;
use App\Device;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class DeviceController extends Controller{
//register
public function signupDevice(Request $request)
{
//cant registed with the same email twice
if(sizeof(Device::where('name','=',$request->query('name'))->get()) > 0)
return response()->json(['name has already been taken'],500);
$request->validate([
'name' => 'required|string',
'password' => 'required|string|confirmed']);
$device =new Device(
[
'name'=>$request->name,
'password'=>bcrypt($request->password)
]);
$device->save();
return response()->json([
'message' => 'Successfully created device!'
], 201);
}
public function login(Request $request)
{
if (Auth::guard('device')->attempt(['name' => request(['name']), 'password' => request(['password'])])) {
$details = Auth::guard('device')->user();
$user = $details['original'];
return $user;}
else {return 'auth fail';}
}
public function login1(Request $request){
//validate the data input
$request->validate([
'name' => 'required|string', // |string|name
'password' => 'required|string',
// 'remember_me' => 'boolean'
]);
$credentials = request(['name', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$device = $request->user('device');
// $device = Auth::guard('device')->device();
$tokenResult = $device->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString()
],200);
}
}
Здесьэто мой файл конфигурации auth.php
.
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false,
],
'device'=>
[
'driver'=>'session',
// 'model'=>App\Device::class,
'provider'=>'devices',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'devices' => [
'driver' => 'eloquent',
'model' => App\Device::class,
],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
и мои маршруты:
//routes for device auth
Route::group(
[
'prefix'=>'auth/device'
],function ()
{
Route::post('signup','DeviceController@signupDevice');
Route::post('login','DeviceController@login');
});
Класс приложения / устройства
Подсветка \ Foundation \ Auth \ Device выглядитточно так же, как класс пользователя
<?php
namespace App;
use Illuminate\Foundation\Auth\Device as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class Device extends Authenticatable{
use Notifiable;//,HasApiTokens;
protected $table ='device';
protected $fillable = [
'name', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Есть идеи, как использовать паспорт Laravel для аутентификации Multi-auth для двух таблиц?