Merge branch 'feature/logout'
This commit is contained in:
commit
d737c07f42
9 changed files with 303 additions and 0 deletions
17
backend/app/Auth/UseCases/Logout/Logout.php
Normal file
17
backend/app/Auth/UseCases/Logout/Logout.php
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
|
||||
namespace App\Auth\UseCases\Logout;
|
||||
|
||||
use App\Auth\SessionRepository;
|
||||
|
||||
class Logout
|
||||
{
|
||||
public function __construct(
|
||||
private SessionRepository $sessionRepository,
|
||||
) {}
|
||||
|
||||
public function execute(string $token): void
|
||||
{
|
||||
$this->sessionRepository->deleteByToken($token);
|
||||
}
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ namespace App\Http\Controllers;
|
|||
use App\Auth\UseCases\AuthenticateUser\AuthenticateUser;
|
||||
use App\Auth\UseCases\AuthenticateUser\AuthenticateUserRequest;
|
||||
use App\Auth\UseCases\CreateSession\CreateSession;
|
||||
use App\Auth\UseCases\Logout\Logout;
|
||||
use App\Exceptions\BadRequestException;
|
||||
use App\Exceptions\UnauthorizedException;
|
||||
use App\Http\Middleware\AuthMiddleware;
|
||||
|
|
@ -19,6 +20,7 @@ class AuthController extends Controller
|
|||
public function __construct(
|
||||
private AuthenticateUser $authenticateUser,
|
||||
private CreateSession $createSession,
|
||||
private Logout $logout,
|
||||
) {}
|
||||
|
||||
public function login(Request $request): JsonResponse
|
||||
|
|
@ -71,6 +73,28 @@ class AuthController extends Controller
|
|||
]);
|
||||
}
|
||||
|
||||
public function logout(Request $request): JsonResponse
|
||||
{
|
||||
$token = $request->cookie(AuthMiddleware::COOKIE_NAME);
|
||||
if (is_string($token) && $token !== '') {
|
||||
$this->logout->execute($token);
|
||||
}
|
||||
|
||||
$response = new JsonResponse(null, 204);
|
||||
|
||||
return $response->withCookie(Cookie::create(
|
||||
name: AuthMiddleware::COOKIE_NAME,
|
||||
value: '',
|
||||
expire: 1,
|
||||
path: '/',
|
||||
domain: null,
|
||||
secure: false,
|
||||
httpOnly: true,
|
||||
raw: false,
|
||||
sameSite: Cookie::SAMESITE_LAX,
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{id: int, email: string}
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -8,4 +8,5 @@ Route::post('/login', [AuthController::class, 'login']);
|
|||
|
||||
Route::middleware(AuthMiddleware::class)->group(function (): void {
|
||||
Route::get('/me', [AuthController::class, 'me']);
|
||||
Route::post('/logout', [AuthController::class, 'logout']);
|
||||
});
|
||||
|
|
|
|||
58
backend/tests/Feature/Auth/LogoutEndpointTest.php
Normal file
58
backend/tests/Feature/Auth/LogoutEndpointTest.php
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
<?php
|
||||
|
||||
namespace Tests\Feature\Auth;
|
||||
|
||||
use App\Auth\CreateSessionDto;
|
||||
use App\Auth\SessionRepository;
|
||||
use App\Http\Middleware\AuthMiddleware;
|
||||
use App\Shared\ValueObject\EmailAddress;
|
||||
use App\User\CreateUserDto;
|
||||
use App\User\UserRepository;
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class LogoutEndpointTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_logout_deletes_session_and_clears_cookie(): void
|
||||
{
|
||||
$now = new DateTimeImmutable(
|
||||
'2026-07-31T12:00:00',
|
||||
new DateTimeZone('UTC'),
|
||||
);
|
||||
$user = app(UserRepository::class)->create(new CreateUserDto(
|
||||
email: new EmailAddress('user@example.com'),
|
||||
passwordHash: 'hashed-password',
|
||||
));
|
||||
app(SessionRepository::class)->create(new CreateSessionDto(
|
||||
token: 'session-token',
|
||||
user: $user,
|
||||
createdAt: $now,
|
||||
expiresAt: $now->modify('+7 days'),
|
||||
));
|
||||
|
||||
$response = $this->withCredentials()
|
||||
->withUnencryptedCookie(
|
||||
AuthMiddleware::COOKIE_NAME,
|
||||
'session-token',
|
||||
)->postJson('/api/logout');
|
||||
|
||||
$response->assertNoContent();
|
||||
$response->assertCookieExpired(AuthMiddleware::COOKIE_NAME);
|
||||
$this->assertNull(
|
||||
app(SessionRepository::class)->findByToken('session-token'),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_logout_rejects_a_request_without_a_cookie(): void
|
||||
{
|
||||
$response = $this->postJson('/api/logout');
|
||||
|
||||
$response
|
||||
->assertStatus(401)
|
||||
->assertExactJson(['error' => 'unauthenticated']);
|
||||
}
|
||||
}
|
||||
58
backend/tests/Unit/Auth/UseCases/LogoutTest.php
Normal file
58
backend/tests/Unit/Auth/UseCases/LogoutTest.php
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
<?php
|
||||
|
||||
namespace Tests\Unit\Auth\UseCases;
|
||||
|
||||
use App\Auth\CreateSessionDto;
|
||||
use App\Auth\UseCases\Logout\Logout;
|
||||
use App\Shared\ValueObject\EmailAddress;
|
||||
use App\User\User;
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Tests\Fakes\FakeSessionRepository;
|
||||
|
||||
class LogoutTest extends TestCase
|
||||
{
|
||||
private FakeSessionRepository $sessionRepository;
|
||||
|
||||
private Logout $useCase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
$this->sessionRepository = new FakeSessionRepository;
|
||||
$this->useCase = new Logout($this->sessionRepository);
|
||||
}
|
||||
|
||||
public function test_existing_token_session_is_removed(): void
|
||||
{
|
||||
$now = new DateTimeImmutable(
|
||||
'2026-07-31T12:00:00',
|
||||
new DateTimeZone('UTC'),
|
||||
);
|
||||
$this->sessionRepository->create(new CreateSessionDto(
|
||||
token: 'session-token',
|
||||
user: new User(
|
||||
id: 7,
|
||||
email: new EmailAddress('user@example.com'),
|
||||
passwordHash: 'hashed-password',
|
||||
),
|
||||
createdAt: $now,
|
||||
expiresAt: $now->modify('+7 days'),
|
||||
));
|
||||
|
||||
$this->useCase->execute('session-token');
|
||||
|
||||
$this->assertNull(
|
||||
$this->sessionRepository->findByToken('session-token'),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_unknown_token_does_not_throw(): void
|
||||
{
|
||||
$this->useCase->execute('unknown-token');
|
||||
|
||||
$this->assertNull(
|
||||
$this->sessionRepository->findByToken('unknown-token'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ namespace Tests\Unit\Http\Controllers;
|
|||
|
||||
use App\Auth\UseCases\AuthenticateUser\AuthenticateUser;
|
||||
use App\Auth\UseCases\CreateSession\CreateSession;
|
||||
use App\Auth\UseCases\Logout\Logout;
|
||||
use App\Http\Controllers\AuthController;
|
||||
use App\Http\Middleware\AuthMiddleware;
|
||||
use App\Shared\ValueObject\EmailAddress;
|
||||
|
|
@ -45,9 +46,11 @@ class AuthControllerTest extends TestCase
|
|||
new DateTimeZone('UTC'),
|
||||
)),
|
||||
);
|
||||
$logout = new Logout($this->sessionRepository);
|
||||
$this->controller = new AuthController(
|
||||
$authenticateUser,
|
||||
$createSession,
|
||||
$logout,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -117,6 +120,37 @@ class AuthControllerTest extends TestCase
|
|||
);
|
||||
}
|
||||
|
||||
public function test_logout_deletes_session_and_clears_cookie(): void
|
||||
{
|
||||
$this->createUser('correct-password');
|
||||
$this->controller->login(new Request([
|
||||
'email' => 'user@example.com',
|
||||
'password' => 'correct-password',
|
||||
]));
|
||||
$request = new Request;
|
||||
$request->cookies->set(
|
||||
AuthMiddleware::COOKIE_NAME,
|
||||
'session-token',
|
||||
);
|
||||
|
||||
$response = $this->controller->logout($request);
|
||||
|
||||
$this->assertSame(204, $response->getStatusCode());
|
||||
$this->assertNull(
|
||||
$this->sessionRepository->findByToken('session-token'),
|
||||
);
|
||||
$cookies = $response->headers->getCookies();
|
||||
$this->assertCount(1, $cookies);
|
||||
$this->assertSame(
|
||||
AuthMiddleware::COOKIE_NAME,
|
||||
$cookies[0]->getName(),
|
||||
);
|
||||
$this->assertSame('', $cookies[0]->getValue());
|
||||
$this->assertSame(1, $cookies[0]->getExpiresTime());
|
||||
$this->assertTrue($cookies[0]->isHttpOnly());
|
||||
$this->assertSame('lax', $cookies[0]->getSameSite());
|
||||
}
|
||||
|
||||
private function createUser(string $password): void
|
||||
{
|
||||
$this->userRepository->create(new CreateUserDto(
|
||||
|
|
|
|||
|
|
@ -3,6 +3,40 @@ const authenticatedUser = {
|
|||
email: 'user@example.com',
|
||||
}
|
||||
|
||||
function interceptLogoutFlow(): void {
|
||||
let authenticated = true
|
||||
|
||||
cy.intercept('GET', '**/api/me', (request) => {
|
||||
if (authenticated) {
|
||||
request.alias = 'me'
|
||||
request.reply({
|
||||
statusCode: 200,
|
||||
body: { user: authenticatedUser },
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
request.alias = 'loggedOutMe'
|
||||
request.reply({
|
||||
statusCode: 401,
|
||||
body: { error: 'unauthenticated' },
|
||||
})
|
||||
})
|
||||
cy.intercept('POST', '**/api/logout', (request) => {
|
||||
expect(request.headers.accept).to.equal('application/json')
|
||||
authenticated = false
|
||||
request.reply({ statusCode: 204 })
|
||||
}).as('logout')
|
||||
}
|
||||
|
||||
function visitDashboardAndLogout(): void {
|
||||
cy.visit('/dashboard')
|
||||
cy.wait('@me')
|
||||
cy.contains('button', 'Log out').click()
|
||||
cy.wait('@logout')
|
||||
cy.wait('@loggedOutMe')
|
||||
}
|
||||
|
||||
describe('session authentication', () => {
|
||||
it('restores an authenticated session on a protected route', () => {
|
||||
cy.intercept('GET', '**/api/me', {
|
||||
|
|
@ -53,4 +87,23 @@ describe('session authentication', () => {
|
|||
|
||||
cy.location('pathname').should('equal', '/login')
|
||||
})
|
||||
|
||||
it('logs out and redirects to login', () => {
|
||||
interceptLogoutFlow()
|
||||
|
||||
visitDashboardAndLogout()
|
||||
|
||||
cy.location('pathname').should('equal', '/login')
|
||||
})
|
||||
|
||||
it('keeps protected routes inaccessible after logout', () => {
|
||||
interceptLogoutFlow()
|
||||
visitDashboardAndLogout()
|
||||
|
||||
cy.visit('/dashboard')
|
||||
cy.wait('@loggedOutMe')
|
||||
|
||||
cy.location('pathname').should('equal', '/login')
|
||||
cy.location('search').should('include', 'redirect=/dashboard')
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -101,6 +101,20 @@ export const useAuthStore = defineStore('auth', () => {
|
|||
}
|
||||
}
|
||||
|
||||
async function logout(): Promise<void> {
|
||||
try {
|
||||
await fetch(`${API_BASE}/api/logout`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
},
|
||||
})
|
||||
} finally {
|
||||
user.value = null
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
user,
|
||||
loading,
|
||||
|
|
@ -108,5 +122,6 @@ export const useAuthStore = defineStore('auth', () => {
|
|||
isAuthenticated,
|
||||
fetchMe,
|
||||
login,
|
||||
logout,
|
||||
}
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,11 +1,23 @@
|
|||
<script setup lang="ts">
|
||||
import { useRouter } from 'vue-router'
|
||||
|
||||
import BrandWordmark from '@/components/BrandWordmark.vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
|
||||
const authStore = useAuthStore()
|
||||
const router = useRouter()
|
||||
|
||||
async function handleLogout(): Promise<void> {
|
||||
await authStore.logout()
|
||||
await router.push({ name: 'login' })
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="dashboard-page">
|
||||
<header>
|
||||
<BrandWordmark theme="dark" />
|
||||
<button type="button" class="logout-button" @click="handleLogout">Log out</button>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
|
|
@ -29,10 +41,41 @@ import BrandWordmark from '@/components/BrandWordmark.vue'
|
|||
}
|
||||
|
||||
header {
|
||||
display: flex;
|
||||
width: min(100%, 76rem);
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.logout-button {
|
||||
min-height: 2.75rem;
|
||||
padding: 0.7rem 1.1rem;
|
||||
border: 0;
|
||||
border-radius: 0.7rem;
|
||||
color: #fffdf7;
|
||||
background: #183a31;
|
||||
box-shadow: 0 0.55rem 1.2rem rgb(24 58 49 / 14%);
|
||||
font-size: 0.82rem;
|
||||
font-weight: 750;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background-color 160ms ease,
|
||||
transform 160ms ease,
|
||||
box-shadow 160ms ease;
|
||||
}
|
||||
|
||||
.logout-button:hover {
|
||||
background: #285c4e;
|
||||
box-shadow: 0 0.7rem 1.4rem rgb(24 58 49 / 18%);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.logout-button:focus-visible {
|
||||
outline: 3px solid rgb(86 127 112 / 34%);
|
||||
outline-offset: 0.25rem;
|
||||
}
|
||||
|
||||
section {
|
||||
width: min(100%, 42rem);
|
||||
margin: clamp(6rem, 18vh, 12rem) auto 0;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue