76 lines
1.8 KiB
PHP
76 lines
1.8 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
use Closure;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
|
|
final class EnsureSchoolAccess
|
|
{
|
|
public function handle(Request $request, Closure $next): Response
|
|
{
|
|
$user = $request->user();
|
|
|
|
if (! $user) {
|
|
abort(401);
|
|
}
|
|
|
|
$schoolId = $this->schoolIdFromRoute($request);
|
|
|
|
if (! $schoolId) {
|
|
abort(404);
|
|
}
|
|
|
|
if (! $this->userCanAccessSchool((int) $user->getAuthIdentifier(), $schoolId)) {
|
|
abort(404);
|
|
}
|
|
|
|
return $next($request);
|
|
}
|
|
|
|
private function schoolIdFromRoute(Request $request): ?int
|
|
{
|
|
$school = $request->route('school');
|
|
|
|
if (is_numeric($school)) {
|
|
return (int) $school;
|
|
}
|
|
|
|
if (is_object($school) && isset($school->id)) {
|
|
return (int) $school->id;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
private function userCanAccessSchool(int $userId, int $schoolId): bool
|
|
{
|
|
if (Schema::hasTable('school_user')) {
|
|
return DB::table('school_user')
|
|
->where('user_id', $userId)
|
|
->where('school_id', $schoolId)
|
|
->exists();
|
|
}
|
|
|
|
if (Schema::hasTable('school_users')) {
|
|
return DB::table('school_users')
|
|
->where('user_id', $userId)
|
|
->where('school_id', $schoolId)
|
|
->exists();
|
|
}
|
|
|
|
if (Schema::hasTable('users') && Schema::hasColumn('users', 'school_id')) {
|
|
return DB::table('users')
|
|
->where('id', $userId)
|
|
->where('school_id', $schoolId)
|
|
->exists();
|
|
}
|
|
|
|
return false;
|
|
}
|
|
} |