Laravel根据API用户自动限制模型范围

时间:2019-02-28 22:26:25

标签: laravel laravel-5 model

我有一个使用承载令牌进行身份验证的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();
}

1 个答案:

答案 0 :(得分:0)

作为一个想法,您可以制作一个中间件来将公司上下文与传入的请求相关联。我们将其称为“ 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);
    }
}

现在,您可以通过内核注册中间件并将其与任意数量的路由关联,这样,当控件进入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();
}

有道理吗?