Created
March 19, 2024 04:47
-
-
Save erdum/1e14c4e1cab9eb94ed2043ed6fe43ada to your computer and use it in GitHub Desktop.
Restrict users from accessing routes based on their permissions (Middleware)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Middleware; | |
use Closure; | |
use Illuminate\Http\Request; | |
use Illuminate\Support\Facades\Route; | |
class CheckUserPermissions | |
{ | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next | |
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse | |
*/ | |
public function handle(Request $request, Closure $next) | |
{ | |
$perms = $request->user()->role->permissions; | |
$requested_route_fragments = explode('/', $request->route()->uri); | |
$operation = 'view'; | |
$resource = null; | |
foreach ($requested_route_fragments as $frag) { | |
// Handle Create, Edit, Delete operations | |
if (in_array($frag, array_keys($perms))) { | |
$operation = $frag; | |
} else if (in_array( | |
$frag, | |
array_column(config('app.menu_items'), 'name') | |
)) { | |
$resource = $frag; | |
} | |
} | |
if ( | |
in_array('all', $perms[$operation]) | |
|| in_array($resource, $perms[$operation]) | |
) { | |
return $next($request); | |
} | |
return response( | |
'Operation prohibited! You don\' have the required permissions.', | |
403 | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment