From aa0d98f72b31a5293d9e19eb9cf26dbc088befb1 Mon Sep 17 00:00:00 2001 From: ricky rx Date: Wed, 17 Apr 2024 11:52:49 +0700 Subject: [PATCH] feat: simple middleware for superadmin page --- app/Exceptions/Handler.php | 6 ++++++ ...LoginController.php => AuthController.php} | 7 ++++++- app/Http/Middleware/UserAuthMiddleware.php | 21 +++++++++++++++++++ routes/api.php | 9 +++++--- 4 files changed, 39 insertions(+), 4 deletions(-) rename app/Http/Controllers/api/{LoginController.php => AuthController.php} (87%) create mode 100644 app/Http/Middleware/UserAuthMiddleware.php diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index 56af264..7d0ca4b 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -2,6 +2,7 @@ namespace App\Exceptions; +use App\Helper\JSONResponse; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Throwable; @@ -23,6 +24,11 @@ class Handler extends ExceptionHandler */ public function register(): void { + $this->renderable(function (\Illuminate\Auth\AuthenticationException $e, $request) { + return JSONResponse::Unauthorized(); + }); + + $this->reportable(function (Throwable $e) { // }); diff --git a/app/Http/Controllers/api/LoginController.php b/app/Http/Controllers/api/AuthController.php similarity index 87% rename from app/Http/Controllers/api/LoginController.php rename to app/Http/Controllers/api/AuthController.php index cfcc1de..a6af5c6 100644 --- a/app/Http/Controllers/api/LoginController.php +++ b/app/Http/Controllers/api/AuthController.php @@ -8,7 +8,7 @@ use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; -class LoginController extends Controller { +class AuthController extends Controller { public static function login(Request $request) { $request->validate( ['username' => 'required|string'], @@ -33,4 +33,9 @@ class LoginController extends Controller { 'token' => $token] ]); } + + // check in middleware + public static function check(Request $request) { + return JSONResponse::Success(); + } } diff --git a/app/Http/Middleware/UserAuthMiddleware.php b/app/Http/Middleware/UserAuthMiddleware.php new file mode 100644 index 0000000..2f3d90c --- /dev/null +++ b/app/Http/Middleware/UserAuthMiddleware.php @@ -0,0 +1,21 @@ +user()->is_active) return JSONResponse::Unauthorized(); + return $next($request); + } +} diff --git a/routes/api.php b/routes/api.php index 858890b..b74e0c6 100644 --- a/routes/api.php +++ b/routes/api.php @@ -1,6 +1,8 @@ group(function() { +const USER_MIDDLEWARES = ['auth:sanctum', UserAuthMiddleware::class]; +Route::controller(AuthController::class )->group(function() { Route::post('/login', 'login'); + Route::middleware(USER_MIDDLEWARES)->post('/auth/check', 'check'); });