Skip to content

Commit

Permalink
update error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
swoorr committed Jul 28, 2023
1 parent 37552ab commit 31232ea
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
8 changes: 4 additions & 4 deletions app/Http/Middleware/Case365.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ public function handle(Request $request, Closure $next): Response
$apiKey = $request->header('api_key');
$secretKey = $request->header('secret_key');

// check if api_key and secret_key are not empty
if(empty($apiKey) || empty($secretKey))
return response()->json(['status' => false, 'message' => 'APIKEY and SECRETKEY required!'], 401);
if (empty($apiKey)) return response()->json(['status' => false, 'message' => 'APIKEY required!'], 401);
if (empty($secretKey)) return response()->json(['status' => false, 'message' => 'SECRETKEY required!'], 401);

// check if api_key and secret_key are valid from User Model
if(!User::where('api_key', $apiKey)->where('secret_key', $secretKey)->exists())
if (!User::where('api_key', $apiKey)->where('secret_key', $secretKey)->exists()) {
return response()->json(['status' => false, 'message' => 'Unauthorized'], 401);
}

// set auth user
auth()->setUser(User::where('api_key', $apiKey)->where('secret_key', $secretKey)->first());
Expand Down
23 changes: 19 additions & 4 deletions tests/Feature/ApiAuthenticationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,27 @@ public function test_api_response_data(): void

public function test_error_handling(): void
{
$response = $this->postJson('/api/app/users', data: [], headers: ['api_key' => null, 'secret_key' => $this->secretKey]);
$dataProvider = [
'apiKeyNull'=> [
'data' => ['api_key' => null, 'secret_key' => $this->secretKey],
'expect' => ['message' => 'APIKEY required!']
],
'secretKeyNull'=> [
'data' => ['api_key' => $this->apiKey, 'secret_key' => null],
'expect' => ['message' => 'SECRETKEY required!']
],
];

$response = $this->postJson('/api/app/users', data: [], headers: $dataProvider['apiKeyNull']['data']);

$response
->assertStatus(401)
->assertJson([
'message' => 'APIKEY and SECRETKEY required!',
]);
->assertJson($dataProvider['apiKeyNull']['expect']);

$response = $this->postJson('/api/app/users', data: [], headers: $dataProvider['secretKeyNull']['data']);

$response
->assertStatus(401)
->assertJson($dataProvider['secretKeyNull']['expect']);
}
}

0 comments on commit 31232ea

Please sign in to comment.