Laravel Auth中间件

时间:2018-10-10 13:58:55

标签: laravel eloquent laravel-5.6

我有一个控制器,在我的控制器中,我有一个索引函数,可将数据返回给用户。

用户可以过滤他们希望索引函数返回的查询。

我注意到,当我尝试调用auth:api时,只有使用Auth::user()中间件的路由才会返回用户对象。

现在,我的函数返回数据库中的所有事件。用户可以像这样?filter=my那样过滤结果,以返回他们创建的事件的列表。这里的问题是,用户必须先登录才能看到他们创建的事件。

我的问题是,如果我用auth:api包裹这条路线,那么来宾用户将无法使用它。但是,如果我不这样做,则要求用户登录的特定过滤器将始终返回空。

这是我的控制者:

public function index(Request $request)
    {
        $categoryId = $request->get("category_id");
        $userId = Auth::check() ? Auth::user()->id : 0;
        $filter = $request->get("filter");
        $keyword = $request->get("keyword");

        $events = Event::with(["category", "organisers", "banners", "schedules.ticketTypes", "schedules.venue", "schedules.programme"])
            ->when(!empty($categoryId), function ($query) use ($categoryId) {
                return $query->where("category_id", $categoryId);
            })
            ->whereNull("suspended_at")
            ->when($filter == "popular", function ($query) use ($categoryId) {
                return $query->orderBy("views", "DESC")
                    ->limit(15);
            })
            ->when($filter == "upcoming", function ($query) {
                return $query->whereHas("schedules", function ($query) {
                    $query->where("date", ">=", Carbon::now())
                        ->where("date", "<", Carbon::now()->addDays(14))
                        ->limit(15);
                });
            })
            /* This part requires the auth:api middleware since I will be querying based on the user's id which I will get from the auth token passed in thee header.*/
            ->when($filter == "my", function ($query) use ($userId) {
                return $query->whereHas("organisers", function ($query) use ($userId) {
                    $query->where("id", $userId)
                        ->limit(15);
                });
            })
            ->when($filter == "search" && !empty($keyword), function ($query) use ($keyword) {
                return $query->where("slug", "LIKE", "%" . $keyword . "%");
            })
            ->get();

        return EventResource::collection($events);
    }

这是我的 Kernel.php:

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\TrustProxies::class,
        \Barryvdh\Cors\HandleCors::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'acl' => \Kodeine\Acl\Middleware\HasPermission::class
    ];
}

总而言之,我的索引功能不需要用户登录即可访问它。但是,当您将过滤器?filter=my传递给url时,则要求用户登录才能返回数据,因为该函数将根据用户的ID返回结果。

编辑: 以前在这种情况下,当我使用tymon / jwt-auth软件包时,我会使用 jwt.check 中间件。但是似乎没有与之等效的护照。

2 个答案:

答案 0 :(得分:0)

如下更新过滤器my

->when($filter == "my" && $userId != 0, function ($query) use ($userId) {
    ...
})

然后,当$userId为0时,它将被忽略。

答案 1 :(得分:0)

我不确定我是否理解正确,但是如果我做了以下事情:

$userId = Auth::guard('api')->check() ? Auth::guard('api')->user()->id : null; 


->when($filter == "my" && $userId, function ($query) use ($userId) {
      return $query->whereHas("organisers", function ($query) use ($userId) {
            $query->where("id", $userId)->limit(15);
      });
 })