diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index 39dc4d6e..3ce61adf 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -2,8 +2,10 @@ namespace App\Http\Controllers; +use App\Http\Responses\ApiSuccessResponse; use Illuminate\Http\Request; use Illuminate\Http\Response; +use Illuminate\Support\Facades\Auth; class AuthController extends Controller { @@ -35,4 +37,21 @@ public function login(Request $request) 'access_token' => $token ], Response::HTTP_OK); } + + /** + * Logout the user. + * + * @param \Illuminate\Http\Request $request + * @return \App\Http\Responses\ApiSuccessResponse + */ + public function logout(Request $request) + { + if (!$request->user()) { + return new ApiSuccessResponse('No user found'); + } + + $request->user()->currentAccessToken()->delete(); + + return new ApiSuccessResponse('User logged out successfully'); + } } diff --git a/routes/api/v1/auth.php b/routes/api/v1/auth.php index 8ac55dfc..85f1effb 100644 --- a/routes/api/v1/auth.php +++ b/routes/api/v1/auth.php @@ -4,3 +4,4 @@ use Illuminate\Support\Facades\Route; Route::post('/login', [AuthController::class, 'login']); +Route::post('/logout', [AuthController::class, 'logout'])->middleware('auth:sanctum'); diff --git a/tests/Feature/AuthControllerTest.php b/tests/Feature/AuthControllerTest.php index 60394e6c..e9662830 100644 --- a/tests/Feature/AuthControllerTest.php +++ b/tests/Feature/AuthControllerTest.php @@ -6,8 +6,11 @@ use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Http\Response; +use Laravel\Sanctum\Sanctum; use Tests\TestCase; +use function Psy\debug; + class AuthControllerTest extends TestCase { use RefreshDatabase, WithFaker; @@ -67,4 +70,25 @@ public function test_login_with_invalid_credentials(): void $this->assertGuest(); } + + /** + * Test logout. + * + * @return void + */ + public function test_logout(): void + { + + Sanctum::actingAs( + User::factory()->create(), + ['*'] + ); + + $response = $this->postJson('/api/v1/logout'); + + $response->assertStatus(Response::HTTP_OK) + ->assertJson([ + 'data' => 'User logged out successfully', + ]); + } }