f83f21936f
API CI/CD / Validate (composer + pint) (push) Successful in 3m30s
API CI/CD / Test (PHPUnit) (push) Failing after 5m4s
API CI/CD / Build frontend assets (push) Successful in 1m1s
API CI/CD / Security audit (push) Failing after 49s
API CI/CD / Deploy to shared hosting (PHP) (push) Has been skipped
80 lines
2.2 KiB
PHP
80 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
use App\Support\AccountAvailability;
|
|
use Closure;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Illuminate\Support\Facades\DB;
|
|
use PHPOpenSourceSaver\JWTAuth\Exceptions\JWTException;
|
|
use PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
|
|
class ApiDocsAuth
|
|
{
|
|
public function handle(Request $request, Closure $next): Response
|
|
{
|
|
$user = Auth::user();
|
|
if (! $user) {
|
|
$authHeader = (string) $request->header('Authorization');
|
|
if ($authHeader !== '' && stripos($authHeader, 'Bearer ') === 0) {
|
|
$token = trim(substr($authHeader, 7));
|
|
if ($token === '') {
|
|
return $this->deny('Missing token.', 401);
|
|
}
|
|
|
|
try {
|
|
$user = JWTAuth::setToken($token)->authenticate();
|
|
if ($user) {
|
|
Auth::setUser($user);
|
|
}
|
|
} catch (JWTException $e) {
|
|
$user = null;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (! $user) {
|
|
return $this->deny('Unauthorized access to documentation.', 401);
|
|
}
|
|
|
|
if ($response = $this->denyUnavailableAccount($user)) {
|
|
return $response;
|
|
}
|
|
|
|
if (! $this->userIsAdmin((int) $user->id)) {
|
|
return $this->deny('Admin privileges required.', 403);
|
|
}
|
|
|
|
return $next($request);
|
|
}
|
|
|
|
private function userIsAdmin(int $userId): bool
|
|
{
|
|
return DB::table('user_roles as ur')
|
|
->join('roles as r', 'r.id', '=', 'ur.role_id')
|
|
->where('ur.user_id', $userId)
|
|
->whereNull('ur.deleted_at')
|
|
->whereRaw('LOWER(r.name) = ?', ['admin'])
|
|
->exists();
|
|
}
|
|
|
|
private function denyUnavailableAccount(object $user): ?Response
|
|
{
|
|
if (AccountAvailability::isUnavailable($user)) {
|
|
return response()->json(['message' => 'Account unavailable.'], 403);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
private function deny(string $message, int $status): Response
|
|
{
|
|
return response()->json([
|
|
'status' => false,
|
|
'message' => $message,
|
|
], $status);
|
|
}
|
|
}
|