From eca288f525e1d584f6da37c60dbd3671d5f59816 Mon Sep 17 00:00:00 2001 From: Franz Liedke Date: Fri, 13 Sep 2019 14:38:06 +0200 Subject: [PATCH] Send a HTTP 401 for incorrect login credentials This fixes a regression from #1843 and #1854. Now, the frontend again shows the proper "Incorrect login details" message instead of "You do not have permission to do that". --- .../Api/Controller/CreateTokenController.php | 4 +-- .../api/authentication/WithTokenTest.php | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/framework/core/src/Api/Controller/CreateTokenController.php b/framework/core/src/Api/Controller/CreateTokenController.php index 2a5ae2c39..13a4cd19d 100644 --- a/framework/core/src/Api/Controller/CreateTokenController.php +++ b/framework/core/src/Api/Controller/CreateTokenController.php @@ -12,7 +12,7 @@ namespace Flarum\Api\Controller; use Flarum\Http\AccessToken; -use Flarum\User\Exception\PermissionDeniedException; +use Flarum\User\Exception\NotAuthenticatedException; use Flarum\User\UserRepository; use Illuminate\Contracts\Bus\Dispatcher as BusDispatcher; use Illuminate\Contracts\Events\Dispatcher as EventDispatcher; @@ -65,7 +65,7 @@ class CreateTokenController implements RequestHandlerInterface $user = $this->users->findByIdentification($identification); if (! $user || ! $user->checkPassword($password)) { - throw new PermissionDeniedException; + throw new NotAuthenticatedException; } $token = AccessToken::generate($user->id, $lifetime); diff --git a/framework/core/tests/integration/api/authentication/WithTokenTest.php b/framework/core/tests/integration/api/authentication/WithTokenTest.php index fe24584bf..b86795372 100644 --- a/framework/core/tests/integration/api/authentication/WithTokenTest.php +++ b/framework/core/tests/integration/api/authentication/WithTokenTest.php @@ -60,4 +60,33 @@ class WithTokenTest extends TestCase $token = $data['token']; $this->assertEquals(2, AccessToken::findOrFail($token)->user_id); } + + /** + * @test + */ + public function failure_with_invalid_credentials() + { + $response = $this->send( + $this->request( + 'POST', '/api/token', + [ + 'json' => [ + 'identification' => 'normal', + 'password' => 'too-incorrect' + ], + ] + )->withAttribute('bypassCsrfToken', true) + ); + + // HTTP 401 signals an authentication problem + $this->assertEquals(401, $response->getStatusCode()); + + // The response body should contain an error code + $body = (string) $response->getBody(); + $this->assertJson($body); + + $data = json_decode($body, true); + $this->assertCount(1, $data['errors']); + $this->assertEquals('not_authenticated', $data['errors'][0]['code']); + } }