Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(auth): add /logout endpoint for user logout #58

Merged
merged 3 commits into from
Dec 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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',
]);
}
}