Files
laravel-api-kit/tests/Feature/Api/V1/EmailVerificationTest.php

160 lines
5.2 KiB
PHP
Raw Normal View History

Feature (#16) * feat: add email verification endpoints and tests Add comprehensive CI/CD pipeline using GitHub Actions - Run Pest tests on PHP 8.3 and 8.4 with MySQL 8.0 - Automated code style checks with Pint - Static analysis with Larastan/PHPStan - Parallel job execution for faster builds - Composer dependency caching - MySQL service container with health checks * feat: implement password reset flow with secure tokens , add forgot password and reset password functionality - Created password_reset_tokens table migration - Added POST /api/v1/forgot-password endpoint - Added POST /api/v1/reset-password endpoint - Both endpoints rate-limited to 6 requests per minute - Integrated with Laravel's Password facade for secure token management - Revokes all user tokens upon successful password reset - Created ForgotPasswordRequest and ResetPasswordRequest with validation - Added comprehensive test suite (6 test cases) Password reset uses signed, time-limited tokens stored in the database. All user sessions are invalidated after successful reset for security. * feat: add reusable API middleware examples , Implement three production-ready middleware patterns for APIs ForceJsonResponse: - Ensures all API responses are JSON formatted - Sets Accept: application/json header automatically - Handles non-JSON responses gracefully LogApiRequests: - Logs API requests with timestamp, method, URL, IP, user ID, status - Tracks and logs response time in milliseconds - Adds X-Response-Time header to all responses - Configurable via APP_LOG_API_REQUESTS env variable EnsureEmailVerified: - Protects routes requiring verified emails - Returns 403 with descriptive message for unverified users - Works with MustVerifyEmail contract All middleware registered as aliases in bootstrap/app.php: 'force.json', 'log.api', 'verified' These provide common API patterns that developers can apply to routes as needed. * docs: update README with new API endpoints , Update API endpoints table with email verification and password reset routes - Added 4 new endpoint rows to API documentation - Updated rate limits for protected routes (60/min -> 120/min) - Documented email verification endpoints - Documented password reset endpoints - All new endpoints properly documented with auth requirements" * Update 0001_01_01_000000_create_users_table.php * Fix test suite configuration and update route names to standard Laravel conventions * style: fix code formatting per Laravel Pint standards * refactor: revert password_reset_tokens back to users create_users migration * Update 0001_01_01_000000_create_users_table.php * fix: resolve all code style and type safety issues Pint fixes: - Fixed concat_space issues - Removed unused imports (MustVerifyEmail from EnsureEmailVerified) - Fixed not_operator_with_successor_space formatting Rector fixes: - Applied EncapsedStringsToSprintfRector for better type safety - All code quality improvements applied PHPStan fixes: - Changed all middleware return types from Response to mixed (Laravel standard) - Added Response type guard in LogApiRequests before accessing methods - Removed redundant instanceof MustVerifyEmail check (User always implements it)
2026-01-29 04:16:33 +01:00
<?php
declare(strict_types=1);
use App\Models\User;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\URL;
uses(RefreshDatabase::class);
describe('Email Verification', function (): void {
it('verifies email successfully with valid link', function (): void {
Event::fake();
$user = User::factory()->create(['email_verified_at' => null]);
$token = $user->createToken('test-token')->plainTextToken;
$verificationUrl = URL::temporarySignedRoute(
'verification.verify',
now()->addMinutes(60),
['id' => $user->id, 'hash' => sha1($user->email)]
);
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson($verificationUrl);
$response->assertStatus(200)
->assertJson([
'success' => true,
'message' => 'Email verified successfully',
]);
$this->assertNotNull($user->fresh()->email_verified_at);
Event::assertDispatched(Verified::class);
});
it('returns success if email is already verified', function (): void {
$user = User::factory()->create([
'email_verified_at' => now(),
]);
$token = $user->createToken('test-token')->plainTextToken;
$verificationUrl = URL::temporarySignedRoute(
'verification.verify',
now()->addMinutes(60),
['id' => $user->id, 'hash' => sha1($user->email)]
);
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson($verificationUrl);
$response->assertStatus(200)
->assertJson([
'success' => true,
'message' => 'Email already verified',
]);
});
it('fails verification without authentication', function (): void {
$user = User::factory()->create(['email_verified_at' => null]);
$verificationUrl = URL::temporarySignedRoute(
'verification.verify',
now()->addMinutes(60),
['id' => $user->id, 'hash' => sha1($user->email)]
);
$response = $this->postJson($verificationUrl);
$response->assertStatus(401);
});
it('fails verification with invalid signature', function (): void {
$user = User::factory()->create(['email_verified_at' => null]);
$token = $user->createToken('test-token')->plainTextToken;
// Invalid URL without signature
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson(sprintf('/api/v1/email/verify/%d/invalid-hash', $user->id));
$response->assertStatus(403);
});
});
describe('Resend Verification Email', function (): void {
it('resends verification email successfully', function (): void {
$user = User::factory()->create(['email_verified_at' => null]);
$token = $user->createToken('test-token')->plainTextToken;
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/v1/email/resend', [
'email' => $user->email,
]);
$response->assertStatus(200)
->assertJson([
'success' => true,
'message' => 'Verification email sent successfully',
]);
});
it('fails to resend if email is already verified', function (): void {
$user = User::factory()->create([
'email_verified_at' => now(),
]);
$token = $user->createToken('test-token')->plainTextToken;
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/v1/email/resend', [
'email' => $user->email,
]);
$response->assertStatus(400)
->assertJson([
'success' => false,
'message' => 'Email already verified',
]);
});
it('fails with invalid email', function (): void {
$user = User::factory()->create();
$token = $user->createToken('test-token')->plainTextToken;
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/v1/email/resend', [
'email' => 'nonexistent@example.com',
]);
$response->assertStatus(422);
});
it('requires authentication', function (): void {
$user = User::factory()->create(['email_verified_at' => null]);
$response = $this->postJson('/api/v1/email/resend', [
'email' => $user->email,
]);
$response->assertStatus(401);
});
it('respects rate limiting', function (): void {
$user = User::factory()->create(['email_verified_at' => null]);
$token = $user->createToken('test-token')->plainTextToken;
// Make 7 requests (limit is 6 per minute)
for ($i = 0; $i < 7; $i++) {
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/v1/email/resend', [
'email' => $user->email,
]);
}
// Last request should be rate limited
$response->assertStatus(429);
});
});