Files
2026-04-28 21:14:25 +03:00

131 lines
3.6 KiB
PHP

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class PermissionControl
{
public function pathToTypeInfo($path) {
$typePrefix = "/admin/types/";
if(strpos($path, $typePrefix) !== false) {
$type = str_replace($typePrefix, "", $path);
$typeInfo = db("types")->where("slug", $type)->first();
} else {
$typeInfo = null;
}
return $typeInfo;
}
public function permissionHave($typeInfo, $levelIndex) {
$fullControl = explode(",", $typeInfo->full_control);
$write = explode(",", $typeInfo->write);
$read = explode(",", $typeInfo->read);
$modify = explode(",", $typeInfo->modify);
$permissions = [];
if(in_array($levelIndex, $fullControl)) {
$permissions[] = "full_control";
}
if(in_array($levelIndex, $write)) {
$permissions[] = "write";
}
if(in_array($levelIndex, $read)) {
$permissions[] = "read";
}
if(in_array($levelIndex, $modify)) {
$permissions[] = "modify";
}
return $permissions;
}
/**
* 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)
{
$exceptPaths = [
'/admin/login',
'/login',
'/logout',
'/',
'/cron',
'/cron-documents',
'/cron-report-builder-queue',
'/clear-cache',
'/mail-link',
];
$thisPath = $request->getPathInfo();
$onlyAdminPath = [
'/admin/users',
'/admin/new/artisan',
'/admin/new/types',
];
if(in_array($thisPath, $onlyAdminPath)) {
if(!isAdmin()) {
echo "Only admin can access this area.";
exit();
}
}
if(!in_array($thisPath, $exceptPaths)) {
$thisTypeInfo = $this->pathToTypeInfo($thisPath);
$userInfo = u();
$levels = levels();
$fullControl = 0;
$write = 1;
$read = 2;
$modify = 3;
//$thisLevel = $levels[$userInfo->level];
try {
if(is_null($userInfo->level)) {
echo "Level is null. Please update this user level";
exit();
} else {
$thisLevelIndex = getLevelIndex($userInfo->level);
if(!is_null($thisTypeInfo)) {
$permissionHave = $this->permissionHave($thisTypeInfo, $thisLevelIndex);
if(in_array("read", $permissionHave) || in_array("full_control", $permissionHave) || in_array("write", $permissionHave)) {
return $next($request);
} else {
echo "You are not authorized to view this area.";
exit();
}
}
}
} catch (\Throwable $th) {
echo "Level is null. Please update this user level";
exit();
}
//dd($thisLevel);
// dd($request);
}
return $next($request);
}
}