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

[3.x] Ensure device has not been logged out #467

Merged
merged 30 commits into from
Aug 30, 2023
Merged
Show file tree
Hide file tree
Changes from 8 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
94 changes: 94 additions & 0 deletions src/Http/Middleware/EnsureDeviceHasNotBeenLoggedOut.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php

namespace Laravel\Sanctum\Http\Middleware;

use Closure;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Auth\SessionGuard;
use Illuminate\Contracts\Auth\Factory as AuthFactory;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Symfony\Component\HttpFoundation\Response;

class EnsureDeviceHasNotBeenLoggedOut
{
/**
* The authentication factory implementation.
*
* @var \Illuminate\Contracts\Auth\Factory
*/
protected $auth;

/**
* Create a new middleware instance.
*
* @param \Illuminate\Contracts\Auth\Factory $auth
* @return void
*/
public function __construct(AuthFactory $auth)
{
$this->auth = $auth;
}

/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*
* @throws \Illuminate\Auth\AuthenticationException
*/
public function handle(Request $request, Closure $next): Response
{
if ($request->hasSession()) {
if ($request->session()->has($key = 'password_hash_'.$this->auth->getDefaultDriver())) {
crynobone marked this conversation as resolved.
Show resolved Hide resolved
if ($request->session()->get($key) !== $request->user()->getAuthPassword()) {
$this->logout($request);
}
} else {
$this->storePasswordHashInSession($request);
}
}

return $next($request);
crynobone marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* Log the user out of the application.
*
* @param \Illuminate\Http\Request $request
* @return void
*
* @throws \Illuminate\Auth\AuthenticationException
*/
protected function logout(Request $request)
{
foreach (Arr::wrap(config('sanctum.guard')) as $guard) {
tap($this->auth->guard($guard), function ($guard) {
if ($guard instanceof SessionGuard) {
$guard->logoutCurrentDevice();
}
});
}

$request->session()->flush();

throw new AuthenticationException('Unauthenticated.', [$this->auth->getDefaultDriver()]);
}

/**
* Store the user's current password hash in the session.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function storePasswordHashInSession($request)
{
if (! $request->user()) {
return;
}

$request->session()->put([
'password_hash_'.$this->auth->getDefaultDriver() => $request->user()->getAuthPassword(),
]);
}
}
1 change: 1 addition & 0 deletions src/Http/Middleware/EnsureFrontendRequestsAreStateful.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ protected function frontendMiddleware()
\Illuminate\Session\Middleware\StartSession::class,
config('sanctum.middleware.validate_csrf_token'),
config('sanctum.middleware.verify_csrf_token', \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class),
config('sanctum.middleware.ensure_not_logged_out', EnsureDeviceHasNotBeenLoggedOut::class),
crynobone marked this conversation as resolved.
Show resolved Hide resolved
])));

array_unshift($middleware, function ($request, $next) {
Expand Down
80 changes: 80 additions & 0 deletions tests/Feature/Middleware/EnsureDeviceHasNotLoggedOutTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php

namespace Laravel\Sanctum\Tests\Feature\Middleware;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;
use Laravel\Sanctum\Http\Middleware\EnsureDeviceHasNotBeenLoggedOut;
use Laravel\Sanctum\Sanctum;
use Orchestra\Testbench\Concerns\WithWorkbench;
use Orchestra\Testbench\TestCase;
use Workbench\App\Models\User;
use Workbench\Database\Factories\PersonalAccessTokenFactory;
use Workbench\Database\Factories\UserFactory;

class EnsureDeviceHasNotLoggedOutTest extends TestCase
{
use RefreshDatabase, WithWorkbench;

protected function defineEnvironment($app)
{
$app['config']->set([
'app.key' => 'AckfSECXIvnK5r28GVIWUAxmbBSjTsmF',
'auth.guards.sanctum.provider' => 'users',
'auth.providers.users.model' => User::class,
'database.default' => 'testing',
]);
}

protected function defineRoutes($router)
{
$router->get('/sanctum/api/user', function (Request $request) {
abort_if(is_null($request->user()), 401);

return $request->user()->email;
})->middleware('auth:sanctum', EnsureDeviceHasNotBeenLoggedOut::class);

$router->get('/sanctum/web/user', function (Request $request) {
abort_if(is_null($request->user()), 401);

return $request->user()->email;
})->middleware('web', 'auth:sanctum', EnsureDeviceHasNotBeenLoggedOut::class);
}

public function test_middleware_can_authorize_valid_user_using_header()
{
PersonalAccessTokenFactory::new()->for(
$user = UserFactory::new()->create(), 'tokenable')
->create();

$this->getJson('/sanctum/api/user', [
'Authorization' => 'Bearer test',
])->assertOk()
->assertSee($user->email);

$user->password = bcrypt('laravel');
$user->save();

$this->getJson('/sanctum/api/user', [
'Authorization' => 'Bearer test',
])->assertOk()
->assertSee($user->email);
}

public function test_middleware_can_deauthorize_valid_user_using_acting_as_after_password_change()
{
$user = UserFactory::new()->create();

Sanctum::actingAs($user);

$this->getJson('/sanctum/web/user')
->assertOk()
->assertSee($user->email);

$user->password = bcrypt('laravel');
$user->save();

$this->getJson('/sanctum/web/user')
->assertStatus(401);
}
}