【问题标题】:Laravel limiting scope of models automatically based on API userLaravel 根据 API 用户自动限制模型范围
【发布时间】:2019-03-01 06:39:03
【问题描述】:

我有一个使用不记名令牌进行身份验证的 API。不记名令牌是针对用户存储的。有一些中间件会检查请求中是否有有效的不记名令牌,如果没有则检查 401。

鉴于我可以从令牌中推断出用户,我希望将此 API 控制器中所有模型查找的范围限制为仅显示来自用户公司 ID 的结果。

Laravel 是否有一些巧妙的神奇方式来做到这一点? 还是我要在控制器构造函数中再次查找用户并将 where 子句添加到每个操作中?


基本上我想避免这样做:

public function __construct()
{
    # 401 if there isn't a valid bearer token in the request
    $this->middleware('apitokencheck');

    # Boo to this
    $user = UsersModel::where("api_token", $request->api_token)->first();
    $this->companyContext = CompaniesModel::find($user->company_id);
}

...

public function get(Request $request)
{
    # Boo to this also
    $where = [ 
        "company_id" => $this->companyContext->id
    ];

    # Filters
    return InspectionsModel::where($where)->get();
}

【问题讨论】:

标签: laravel laravel-5 model


【解决方案1】:

作为一个想法,您可以制作一个中间件来将公司上下文与传入请求相关联。我们称之为“AddCompanyContextMiddleware”,它看起来像这样:

<?php

namespace App\Http\Middleware;

use Closure;

class AddCompanyContextMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user = UsersModel::where("api_token", $request->api_token)->first();
        $request['companyContext'] = CompaniesModel::find($user->company_id);
        return $next($request);
    }
}

现在您可以通过 Kernel 注册中间件并将其与任意数量的路由关联,这样当控件到达 COntroller 时,您的 $request 变量中已经包含 companyContext,然后您可以在控制器中使用你喜欢的信息:

public function get(Request $request)
{
    $companyContext = $request->input('companyContext');
    # Boo to this also
    $where = [ 
        "company_id" => $companyContext->id
    ];

    # Filters
    return InspectionsModel::where($where)->get();
}

有道理吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 2013-05-02
    • 2016-01-24
    • 1970-01-01
    • 2018-08-18
    相关资源
    最近更新 更多