简体   繁体   English

Laravel Auth中间件

[英]Laravel auth middleware

I have a controller and in my controller I have an index function that returns data back to the user. 我有一个控制器,在我的控制器中,我有一个索引函数,可将数据返回给用户。

The user can filter the query that they want the index function to return. 用户可以过滤他们希望索引函数返回的查询。

I noticed that only routes with the auth:api middleware would return a user object when I tried calling Auth::user() . 我注意到,当我尝试调用Auth::user()时,只有使用auth:api中间件的路由才会返回用户对象。

Now my function returns all events in my database. 现在,我的函数返回数据库中的所有事件。 A user can filter the results like this ?filter=my to return a list of events they created. 用户可以像这样过滤结果?filter=my以返回他们创建的事件列表。 The issue here is the user has to be logged in before they can see events they created. 这里的问题是,用户必须先登录才能看到他们创建的事件。

My problem is if I wrap this route with auth:api then guest users will not be able to use it. 我的问题是,如果我用auth:api包装这条路线,那么来宾用户将无法使用它。 However if I don't then that particular filter that requires a user to be logged in will always return empty. 但是,如果我不这样做,则要求用户登录的特定过滤器将始终返回空。

This is my controller: 这是我的控制器:

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);
    }

This is my Kernel.php: 这是我的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
    ];
}

In summary my index function does not require user to be logged in to access it. 总之,我的索引功能不需要用户登录即可访问它。 However when you pass the filter ?filter=my to the url then user is required to be logged in for data to be returned since the function will return results based on the user's id. 但是,当您将过滤器?filter=my传递给url时,则要求用户登录才能返回数据,因为该函数将根据用户的ID返回结果。

Edit: previously in situations like this I would use jwt.check middleware when I was using tymon/jwt-auth package. 编辑:以前在这种情况下,当我使用tymon / jwt-auth软件包时,我将使用jwt.check中间件。 However there doesn't seem to be a passport equivalent of that. 但是,似乎没有与之等效的护照。

Update the filter my as follows: 更新过滤器my ,如下所示:

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

Then it will be ignored when $userId is 0. 然后,当$userId为0时,它将被忽略。

I am not sure that i understand it correctly but if I did what about: 我不确定我是否理解正确,但是如果我做了以下事情:

$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);
      });
 })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM