Skip to content

Commit

Permalink
Merge pull request #480 from range-of-motion/test-endpoint-for-loggin…
Browse files Browse the repository at this point in the history
…g-in

Test endpoint for logging in
  • Loading branch information
range-of-motion authored Dec 30, 2023
2 parents f7f7c4e + 1031619 commit d57e6ae
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 18 deletions.
33 changes: 15 additions & 18 deletions app/Http/Controllers/Api/LogInController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
Expand All @@ -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,
Expand All @@ -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);
}
}
41 changes: 41 additions & 0 deletions tests/Feature/Api/LogInControllerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace Tests\Feature\Api;

use App\Models\User;
use Tests\TestCase;

class LogInControllerTest extends TestCase
{
public function testWithInvalidCredentials(): void
{
$response = $this->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);
}
}

0 comments on commit d57e6ae

Please sign in to comment.