jeudi 28 février 2019

Laravel limiting scope of models automatically based on API user

I have an API that uses bearer tokens for authentication. Bearer tokens are stored against users. There is some middleware that checks if there is a valid bearer token in the request, and 401's if not.

Given I can infer the user from the token, I'm wanting to limit the scope of all model lookups in this API controller to only show results from the users company id.

Does Laravel have some neat magic way of doing this? Or am I going to be looking up the user again in the controller constructor and adding where clauses into every single action?


Basically I'm wanting to avoid having to do this:

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2II0U3S
via IFTTT

Aucun commentaire:

Enregistrer un commentaire