Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Possible ACL Middleware Implementation for Laravel 5.1.11+
<?php
use AppName\Posts\Post;
use Illuminate\Http\Request;
class GenericAclMiddleware
{
private $entityClasses = [
'post' => Post::class
];
public function handle(Request $request, $next, $permission, $entityParam = null)
{
$user = $request->user();
$instance = $this->getEntityInstance($entityParam);
if($instance) {
$valid = $user->can($permission, $instance);
} else {
$valid = $user->can($permission);
}
if($valid) {
return $next($request);
}
abort(403);
}
private function getEntityInstance($entityParam)
{
if(!$entityParam) {
return null;
}
$entityId = $this->route($entity);
if(!$entityId) {
return null;
}
$entityClass = $this->entityClasses[$entity];
$model = new $entityClass;
return $modelInstance->findOrFail($entityId);
}
}
<?php
use Illuminate\Http\Request;
/**
* @property string $entityParam The route parameter containing the instance of the relevant entity
* @property string $entityClass The class path of the relevant eloquent model
*/
trait EntityAclMiddlewareTrait
{
public function handle(Request $request, $next, $permission)
{
$user = $request->user();
$instance = $this->getEntityInstance($request);
$valid = ($instance) ? $user->can($permission, $instance) : $user->can($permission);
if($valid) {
return $next($request);
}
abort(403);
}
protected function getEntityInstance(Request $request)
{
$entityId = $request->route($this->entityParam);
if(!$entityId) {
return null;
}
$class = $this->entityClass;
$instance = new $class();
return $instance->findOrFail($entityId);
}
}
<?php
use AppName\Posts\Post;
class PostEntityMiddleware
{
use EntityAclMiddlewareTrait;
property $entityClass = Post::class;
property $entityParam = 'posts';
}
<?php
Route::post('posts', [
'middleware' => 'acl:create-posts',
'uses' => 'PostsController@store'
]);
Route::put('posts/{post}', [
'middleware' => 'acl:update-posts,post',
'uses' => 'PostsController@update'
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.