Files
laravel-api-kit/app/Http/Controllers/Api/V1/AuthController.php

148 lines
4.4 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Api\ApiController;
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
use App\Http\Requests\Api\V1\ForgotPasswordRequest;
use App\Http\Requests\Api\V1\LoginRequest;
use App\Http\Requests\Api\V1\RegisterRequest;
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
use App\Http\Requests\Api\V1\ResendVerificationRequest;
use App\Http\Requests\Api\V1\ResetPasswordRequest;
use App\Http\Requests\Api\V1\VerifyEmailRequest;
use App\Http\Resources\UserResource;
use App\Models\User;
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
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Auth\Events\Verified;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
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
use Illuminate\Support\Facades\Password;
final class AuthController extends ApiController
{
public function register(RegisterRequest $request): JsonResponse
{
$user = User::query()->create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
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
$user->sendEmailVerificationNotification();
$token = $user->createToken('auth-token')->plainTextToken;
return $this->created([
'user' => new UserResource($user),
'token' => $token,
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
], 'User registered successfully. Please check your email to verify your account.');
}
public function login(LoginRequest $request): JsonResponse
{
$user = User::query()->where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
return $this->unauthorized('Invalid credentials');
}
$token = $user->createToken('auth-token')->plainTextToken;
return $this->success([
'user' => new UserResource($user),
'token' => $token,
], 'Login successful');
}
public function logout(Request $request): JsonResponse
{
/** @var User $user */
$user = $request->user();
$user->currentAccessToken()->delete();
return $this->success(message: 'Logged out successfully');
}
public function me(Request $request): JsonResponse
{
return $this->success(new UserResource($request->user()));
}
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
public function verifyEmail(VerifyEmailRequest $request): JsonResponse
{
/** @var User $user */
$user = $request->user();
if ($user->hasVerifiedEmail()) {
return $this->success(message: 'Email already verified');
}
if ($user->markEmailAsVerified()) {
event(new Verified($user));
}
return $this->success(message: 'Email verified successfully');
}
public function resendVerificationEmail(ResendVerificationRequest $request): JsonResponse
{
$user = User::query()->where('email', $request->email)->first();
if (! $user) {
return $this->notFound('User not found');
}
if ($user->hasVerifiedEmail()) {
return $this->error('Email already verified', 400);
}
$user->sendEmailVerificationNotification();
return $this->success(message: 'Verification email sent successfully');
}
public function forgotPassword(ForgotPasswordRequest $request): JsonResponse
{
$status = Password::sendResetLink(
$request->only('email')
);
if ($status === Password::RESET_LINK_SENT) {
return $this->success(message: 'Password reset link sent to your email');
}
return $this->error('Unable to send reset link', 500);
}
public function resetPassword(ResetPasswordRequest $request): JsonResponse
{
$status = Password::reset(
$request->only('email', 'password', 'password_confirmation', 'token'),
function (User $user, string $password): void {
$user->forceFill([
'password' => Hash::make($password),
])->save();
$user->tokens()->delete();
event(new PasswordReset($user));
}
);
if ($status === Password::PASSWORD_RESET) {
return $this->success(message: 'Password reset successfully');
}
return $this->error(
match ($status) {
Password::INVALID_TOKEN => 'Invalid or expired reset token',
Password::INVALID_USER => 'User not found',
default => 'Unable to reset password',
},
400
);
}
}