Skip to content

Commit

Permalink
feat(auth): add /logout endpoint for user logout (#58)
Browse files Browse the repository at this point in the history
This implements the `/logout` endpoint, providing users with the ability
to initiate a logout process. The addition of this feature enhances the
overall user experience and aligns with expected functionality for
session management in the application.

Depends-on: #59 
Closes  #21

---------

Signed-off-by: Valentin Sickert <[email protected]>
  • Loading branch information
Lapotor authored Dec 11, 2023
1 parent 38beae2 commit fcb87c7
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
19 changes: 19 additions & 0 deletions app/Http/Controllers/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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');
}
}
1 change: 1 addition & 0 deletions routes/api/v1/auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@
use Illuminate\Support\Facades\Route;

Route::post('/login', [AuthController::class, 'login']);
Route::post('/logout', [AuthController::class, 'logout'])->middleware('auth:sanctum');
24 changes: 24 additions & 0 deletions tests/Feature/AuthControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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',
]);
}
}

0 comments on commit fcb87c7

Please sign in to comment.