问题描述
我的Laravel auth.PHP安装程序具有多个提供程序和多个守护程序。
'guards' => [
'web' => [
'driver' => 'session','provider' => 'users',],'account' => [
'driver' => 'session','provider' => 'accounts','providers' => [
'users' => [
'driver' => 'eloquent','model' => App\Models\User::class,'accounts' => [
'driver' => 'eloquent','model' => App\Models\Account::class,
在config / backpack / base.PHP中,它具有一个选项,您可以在其中设置'guard' => null
。我想对其进行配置,以使其同时查看account
和web
防护,而不仅仅是默认的web
防护。我知道我可以更改此设置,但是我想允许具有web
或account
警卫的用户访问背包管理员。
解决方法
警告
我已经测试了以下内容,直到登录为止(使用“用户”和“帐户”登录名,一切都按预期进行。我尚未测试其他身份验证功能,例如注册,忘记密码的电子邮件) ,密码重设。我希望它们可以按照以下更改进行操作,但是如果遇到问题,可能还需要进行一些调整,此外,如果您允许users
和{ {1}}表,这可能会产生意外的结果,因此您可能希望避免这种情况。
假设您正在使用所有默认的Backpack控制器,或者至少没有对它们进行过多修改...
完成此操作的一种方法是执行以下操作:
-
运行
accounts
see here,这将允许您在 背包尝试加载其助手功能之前加载自己的帮助文件。 -
在
composer require funkjedi/composer-include-files
上创建具有以下内容的自定义帮助文件:app/Helpers/Backpack.php
-
像这样更新composer.json文件:
<?php if (! function_exists('backpack_guard_name')) { /* * Returns the name of the guard defined * by the application config */ function backpack_guard_name() { $guards = array_keys(config('auth.guards')); return implode(',',$guards); } } if (! function_exists('backpack_auth')) { /* * Returns the user instance if it exists * of the currently authenticated admin * based off the defined guard. */ function backpack_auth() { return \Auth::guard(find_current_guard()); } } if (! function_exists('find_current_guard')) { /* * Returns the guard name being used by the * currently authenticated user,or the default */ function find_current_guard() { // set to the default to start with $guard = config('backpack.base.guard'); // get all possible guard names $guards = array_keys(config('auth.guards')); foreach ($guards as $currentGuard) { if (\Auth::guard($currentGuard)->check()) { $guard = $currentGuard; break; } } return $guard; } }
-
在
"extra": { "laravel": { "dont-discover": [] },"include_files": [ "app/Helpers/Backpack.php" ] },
上使用此内容创建自定义登录控制器(或将其放置在其他任何地方,只要将其放在其他位置,只需调整后面的步骤即可)app/Http/Controllers/Admin/Auth/LoginController.php
在 -
(如果不存在,则创建)中添加此代码,请注意,此处包括所有默认的Backpack路线,但随后注释掉了Login路线,并在底部添加了指向我们在上面创建的控制器的自己的登录路由:
routes/backpack/custom.php
namespace App\Http\Controllers\Admin\Auth;
use Illuminate\Http\Request;
class LoginController extends \Backpack\CRUD\app\Http\Controllers\Auth\LoginController
{
/**
* Attempt to log the user into the application.
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
protected function attemptLogin(Request $request)
{
$loggedIn = false;
// get all possible guard names
$guards = array_keys(config('auth.guards'));
foreach ($guards as $currentGuard) {
$loggedIn = \Auth::guard($currentGuard)->attempt(
$this->credentials($request),$request->filled('remember')
);
if ($loggedIn) {
break;
}
}
return $loggedIn;
}
}
内的