From 10316197392d0b48a105084d191612029434833a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20van=20Drunen?= Date: Sat, 30 Dec 2023 00:59:46 +0100 Subject: [PATCH] Test endpoint for logging in --- app/Http/Controllers/Api/LogInController.php | 33 +++++++--------- tests/Feature/Api/LogInControllerTest.php | 41 ++++++++++++++++++++ 2 files changed, 56 insertions(+), 18 deletions(-) create mode 100644 tests/Feature/Api/LogInControllerTest.php diff --git a/app/Http/Controllers/Api/LogInController.php b/app/Http/Controllers/Api/LogInController.php index 08512bd1..95b1f0e3 100644 --- a/app/Http/Controllers/Api/LogInController.php +++ b/app/Http/Controllers/Api/LogInController.php @@ -15,11 +15,6 @@ class LogInController extends Controller { public function __invoke(Request $request): JsonResponse { - $request->validate([ - 'email' => ['required'], - 'password' => ['required'], - ]); - if ( Auth::attempt([ 'email' => $request->input('email'), @@ -28,11 +23,12 @@ public function __invoke(Request $request): JsonResponse ) { $userId = Auth::user()->id; - LoginAttempt::create([ - 'user_id' => $userId, - 'ip' => $request->ip(), - 'failed' => false, - ]); + LoginAttempt::query() + ->create([ + 'user_id' => $userId, + 'ip' => $request->ip(), + 'failed' => false, + ]); $apiKey = ApiKey::create([ 'user_id' => $userId, @@ -45,19 +41,20 @@ public function __invoke(Request $request): JsonResponse 'language' => Auth::user()->language, 'theme' => Auth::user()->theme, ]); - } else { - $userByEmail = User::query() - ->where('email', $request->input('email')) - ->first(); + } + + $userByEmail = User::query() + ->where('email', $request->input('email')) + ->first(); - LoginAttempt::create([ + LoginAttempt::query() + ->create([ 'user_id' => $userByEmail ? $userByEmail->id : null, 'ip' => $request->ip(), 'failed' => true, ]); - return response() - ->json(['error' => 'UNABLE_TO_LOG_IN']); - } + return response() + ->json(['error' => 'UNABLE_TO_LOG_IN'], 403); } } diff --git a/tests/Feature/Api/LogInControllerTest.php b/tests/Feature/Api/LogInControllerTest.php new file mode 100644 index 00000000..28edf9d8 --- /dev/null +++ b/tests/Feature/Api/LogInControllerTest.php @@ -0,0 +1,41 @@ +postJson( + uri: '/api/log-in', + data: [ + 'email' => 'johnwrongdoe@gmail.com', + 'password' => 'helloworld', + ], + ); + + $response->assertStatus(403); + } + + public function testWithValidCredentials(): void + { + User::factory() + ->create([ + 'email' => 'johndoe@gmail.com', + 'password' => bcrypt('helloworld'), + ]); + + $response = $this->postJson( + uri: '/api/log-in', + data: [ + 'email' => 'johndoe@gmail.com', + 'password' => 'helloworld', + ], + ); + + $response->assertStatus(200); + } +}