Initial commit - WASL Digital Wallet
This commit is contained in:
70
Backend/app/Http/Middleware/JwtAuthenticate.php
Normal file
70
Backend/app/Http/Middleware/JwtAuthenticate.php
Normal file
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Services\JwtService;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class JwtAuthenticate
|
||||
{
|
||||
protected JwtService $jwtService;
|
||||
|
||||
public function __construct(JwtService $jwtService)
|
||||
{
|
||||
$this->jwtService = $jwtService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response) $next
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle(Request $request, Closure $next)
|
||||
{
|
||||
$authorization = $request->header('Authorization');
|
||||
|
||||
if (!$authorization || !str_starts_with($authorization, 'Bearer ')) {
|
||||
return response()->json([
|
||||
'error' => 'Unauthorized',
|
||||
'message' => 'Authorization token is missing or malformed.',
|
||||
], Response::HTTP_UNAUTHORIZED);
|
||||
}
|
||||
|
||||
$token = substr($authorization, 7);
|
||||
$payload = $this->jwtService->validateToken($token);
|
||||
|
||||
if (!$payload) {
|
||||
return response()->json([
|
||||
'error' => 'Unauthorized',
|
||||
'message' => 'Authorization token is invalid or expired.',
|
||||
], Response::HTTP_UNAUTHORIZED);
|
||||
}
|
||||
|
||||
$user = User::where('uuid', $payload['sub'])->first();
|
||||
|
||||
if (!$user) {
|
||||
return response()->json([
|
||||
'error' => 'Unauthorized',
|
||||
'message' => 'User associated with this token does not exist.',
|
||||
], Response::HTTP_UNAUTHORIZED);
|
||||
}
|
||||
|
||||
if ($user->status === \App\Enums\UserStatus::BANNED || $user->status === \App\Enums\UserStatus::SUSPENDED) {
|
||||
return response()->json([
|
||||
'error' => 'Forbidden',
|
||||
'message' => 'Your account has been ' . $user->status->value . '.',
|
||||
], Response::HTTP_FORBIDDEN);
|
||||
}
|
||||
|
||||
// Set authenticated user
|
||||
Auth::setUser($user);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user