Closed blendsoft closed 7 years ago
PRs are welcomed! Could look into implementation not early than next week.
It's not trivial thing because you need to resolve what exact model will be checked in middleware. You could create it in your own application:
Imagine that you have AccountController
and all methods need to check if current user is owner of an Account
model.
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class AccountController extends Controller
{
public function __construct()
{
$model = App\Account::class;
$id = 1; // Here you need to determine ID from your route
// Call middleware and pass a model's class name and an id
$this->middleware("OnlyOwnerAccess:{$model},{$id}");
}
// Here goes actual methods: show, edit, update, ...
}
And create your middleware:
<?php
namespace App\Http\Middleware;
class OnlyOwnerAccess
{
public function handle($request, Closure $next, $ownableClass, $id)
{
$user = auth()->user();
if (!$user) {
return redirect('/'); // Redirecting guest on main page
}
// Instantiate the model from App Container and find a specific one by id
$ownable = app($ownableClass)->whereKey($id)->whereOwnedBy($user)->firstOrFail();
// Or write your custom logic of resolving and checks.
// Maybe you need to send flash message to user or log this action to admins.
return $next($request);
}
}
Don't forget to register middleware in App\Http\Kernel
.
@blendsoft I will be glad to receive your feedback about this solution. At this moment I wouldn't add this in package because it's tightly coupled with application's logic.
It would be good to start a PR if you'll find more flexible and easy way to handle it.
Closing this issue. Feel free to continue conversation if there is need.
Could you make route middleware for ownership checking ?