Skip to content

Instantly share code, notes, and snippets.

@lamberttraccard
Last active July 6, 2022 15:54
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lamberttraccard/c0ab9c1ff7b52bd4eb9d8fa188c4470c to your computer and use it in GitHub Desktop.
Save lamberttraccard/c0ab9c1ff7b52bd4eb9d8fa188c4470c to your computer and use it in GitHub Desktop.
Middleware Permission to dynamically authorize users for spatie/laravel-permission
<?php
namespace App\Http\Middleware;
use App\Exceptions\UnauthorizedException;
use App\Http\Controllers\UsersController;
use Closure;
class Permission
{
/**
* List of controllers to handle.
*
* @var array
*/
protected $controllers = [
UsersController::class,
];
/**
* List of actions with their mapping name to handle.
*
* @var array
*/
protected $actions = [
'index' => 'view',
'edit' => 'edit',
'show' => 'view',
'update' => 'edit',
'create' => 'add',
'store' => 'add',
'destroy' => 'delete',
];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (!$this->shouldHandle($request)) {
return $next($request);
};
if (auth()->guest()) {
throw UnauthorizedException::notLoggedIn();
}
if (auth()->user()->can($this->getPermission($request))) {
return $next($request);
};
throw UnauthorizedException::forPermission($this->getPermission($request));
}
/**
* Should the request be handled.
*
* @param $request
* @return bool
*/
protected function shouldHandle($request): bool
{
return $this->checkController($request) && $this->checkAction($request);
}
/**
* Check if the controller should be handle.
*
* @param $request
* @return bool
*/
protected function checkController($request): bool
{
return collect($this->controllers)->contains(function ($item) use ($request) {
return is_a($request->route()->getController(), $item);
});
}
/**
* Check if the action should be handle.
*
* @param $request
* @return bool
*/
protected function checkAction($request): bool
{
return collect($this->actions)->has($request->route()->getActionMethod());
}
/**
* Get the permission name for the given request.
*
* @param $request
* @return string
*/
protected function getPermission($request)
{
$routeName = explode('.', $request->route()->getName());
$action = $this->actions[$request->route()->getActionMethod()];
return $action . '_' . $routeName[0];
}
}
@miyasinarafat
Copy link

miyasinarafat commented Jan 8, 2019

I am implemented this gist for Lumen here: https://gist.github.com/iarafat/de44c578936c8a08376624f80bddf2c1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment