我想要一些仅适用于auth:user
OR auth:admin
中间件的路由。
我尝试了以下代码:
Route::group(['middleware' => ['auth:user', 'auth:admin']], function () {
//many routes here
});
但似乎这些路线同时适用于auth:user
AND auth:admin
!!!
我不想 AND 。我需要 OR 。
任何帮助都将不胜感激
更新1
我决定在userOradmin
档案中创建新的警卫/config/auth.php
。
正如您所看到的,我创建了一个名为userOradmin
的新警卫,它指向提供者usersOrAdmins
(复数名称):
'guards' => [
'user' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins'
],
'userOradmin' => [
'driver' => 'session',
'provider' => 'usersOradmins'
]
]
提供者是:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class
],
'usersOradmins' => [
'driver' => 'eloquent',
'model' => [App\Admin::class, App\User::class] // <-- Is that right?
]
问题出在这里。我应该将这两个类分配给model
吗?
答案 0 :(得分:3)
您需要为此创建一个新的中间件,auth:userOrAdmin
。中间件之间不会相互影响,因此这些中间件都不知道另一个中间件存在。他们只是收到请求,检查并将其发送到线路,因此每个中间件本身都是AND
。
答案 1 :(得分:2)
使用以下代码交换Authenticate
中间件:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Authenticate
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string ...$guards
* @return mixed
*/
public function handle($request, Closure $next, ...$guards)
{
if ($this->check($guards)) {
return $next($request);
}
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
/**
* Determine if the user is logged in to any of the given guards.
*
* @param array $guards
* @return bool
*/
protected function check(array $guards)
{
if (empty($guards)) {
return Auth::check();
}
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
Auth::shouldUse($guard);
return true;
}
}
return false;
}
}
然后你可以在路线中使用它:
Route::group(['middleware' => ['auth:user,admin']], function () {
//many routes here
});