66use App \Models \UsageLog ;
77use Carbon \Carbon ;
88use Closure ;
9+ use Illuminate \Support \Facades \Log ;
910
1011class ApiAuthMiddleware extends BasicAuthMiddleware
1112{
12- /**
13- * Handle an incoming request.
14- *
15- * @param \Illuminate\Http\Request $request
16- * @param \Closure $next
17- * @return mixed
18- */
1913 public function handle ($ request , Closure $ next )
2014 {
2115 $ apiKey = $ request ->header ('x-api-key ' );
2216 $ authHeader = $ request ->header ('Authorization ' );
2317 $ isBasicAuth = $ authHeader && str_starts_with ($ authHeader , 'Basic ' );
2418
25- if (!$ apiKey && !$ isBasicAuth ) {
19+ if (!$ apiKey && !$ isBasicAuth ) {
2620 return response ()->json (['error ' => 'Authentication required. Provide API key or Basic auth ' ], 401 );
2721 }
2822
@@ -31,15 +25,24 @@ public function handle($request, Closure $next)
3125 }
3226
3327 if ($ apiKey ) {
34- $ application = Application::where ('key ' , '= ' , $ apiKey )->first ();
28+ $ application = Application::query ()-> where ('key ' , '= ' , $ apiKey )->first ();
3529
3630 if (!$ application ) {
31+
3732 return response ()->json (['error ' => 'Invalid API key ' ], 401 );
3833 }
3934
40- if (!$ application ->is_active ) {
41- return response ()->json (['error ' => 'Application is inactive ' ], 403 );
35+
36+ if ($ application ->trashed () || !$ application ->is_active ) {
37+ return response ()->json (['error ' => 'Application is unavailable ' ], 403 );
4238 }
39+
40+ $ canAccess = $ this ->canAccessRequestedVersion ($ request ->path (), (array ) $ application ->rules );
41+
42+ if (!$ canAccess ) {
43+ return response ()->json (['error ' => 'Application is not allowed to access this API version ' ], 403 );
44+ }
45+
4346 $ usageLog = new UsageLog ;
4447 $ usageLog ->application_id = $ application ->id ;
4548 $ usageLog ->method = $ request ->method ();
@@ -55,4 +58,17 @@ public function handle($request, Closure $next)
5558
5659 return $ next ($ request );
5760 }
61+
62+ private function canAccessRequestedVersion (string $ path , array $ rules ): bool
63+ {
64+ if (strpos ($ path , 'v1/ ' ) === 0 ) {
65+ return $ rules ['can_access_legacy_whatnow ' ];
66+ }
67+
68+ if (strpos ($ path , 'v2/ ' ) === 0 ) {
69+ return $ rules ['can_access_preparedness_v2 ' ];
70+ }
71+
72+ return true ;
73+ }
5874}
0 commit comments