Attainly/backend/tests/Feature/Auth/MeEndpointTest.php
2026-07-31 11:34:50 +03:00

75 lines
2.1 KiB
PHP

<?php
namespace Tests\Feature\Auth;
use App\Auth\CreateSessionDto;
use App\Auth\SessionRepository;
use App\Http\Middleware\AuthMiddleware;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\UserRepository;
use DateTimeImmutable;
use DateTimeZone;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class MeEndpointTest extends TestCase
{
use RefreshDatabase;
public function test_me_returns_the_authenticated_user(): void
{
$now = new DateTimeImmutable(
'2026-07-31T12:00:00',
new DateTimeZone('UTC'),
);
$user = app(UserRepository::class)->create(new CreateUserDto(
email: new EmailAddress('user@example.com'),
password: 'correct-password',
));
app(SessionRepository::class)->create(new CreateSessionDto(
token: 'valid-token',
user: $user,
createdAt: $now,
expiresAt: $now->modify('+7 days'),
));
$response = $this->withCredentials()
->withUnencryptedCookie(
AuthMiddleware::COOKIE_NAME,
'valid-token',
)->getJson('/api/me');
$response->assertOk()->assertExactJson([
'user' => [
'id' => $user->getId(),
'email' => 'user@example.com',
],
]);
}
public function test_me_rejects_a_request_without_a_cookie(): void
{
$response = $this->getJson('/api/me');
$response
->assertStatus(401)
->assertExactJson(['error' => 'unauthenticated']);
}
public function test_me_allows_credentialed_frontend_requests(): void
{
$response = $this->withHeaders([
'Origin' => 'https://localhost:5173',
'Access-Control-Request-Method' => 'GET',
])->options('/api/me');
$response
->assertNoContent()
->assertHeader(
'Access-Control-Allow-Origin',
'https://localhost:5173',
)
->assertHeader('Access-Control-Allow-Credentials', 'true');
}
}