From 8bbe6bc2794776399adabac092b876d71d5dd51b Mon Sep 17 00:00:00 2001 From: Dane Everitt Date: Sat, 14 Jul 2018 22:58:33 -0700 Subject: [PATCH] Add test, fix behavior of model creation --- app/Http/Middleware/Api/AuthenticateKey.php | 4 ++-- .../Middleware/API/AuthenticateKeyTest.php | 21 +++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/app/Http/Middleware/Api/AuthenticateKey.php b/app/Http/Middleware/Api/AuthenticateKey.php index 591aeef94..429c26f90 100644 --- a/app/Http/Middleware/Api/AuthenticateKey.php +++ b/app/Http/Middleware/Api/AuthenticateKey.php @@ -68,15 +68,15 @@ class AuthenticateKey // This is a request coming through using cookies, we have an authenticated user not using // an API key. Make some fake API key models and continue on through the process. if (empty($raw) && $request->user() instanceof User) { - $model = new ApiKey([ + $model = (new ApiKey())->forceFill([ 'user_id' => $request->user()->id, 'key_type' => ApiKey::TYPE_ACCOUNT, ]); } else { $model = $this->authenticateApiKey($raw, $keyType); + $this->auth->guard()->loginUsingId($model->user_id); } - $this->auth->guard()->loginUsingId($model->user_id); $request->attributes->set('api_key', $model); return $next($request); diff --git a/tests/Unit/Http/Middleware/API/AuthenticateKeyTest.php b/tests/Unit/Http/Middleware/API/AuthenticateKeyTest.php index 075124e2b..0d68b2642 100644 --- a/tests/Unit/Http/Middleware/API/AuthenticateKeyTest.php +++ b/tests/Unit/Http/Middleware/API/AuthenticateKeyTest.php @@ -4,6 +4,7 @@ namespace Tests\Unit\Http\Middleware\API; use Mockery as m; use Cake\Chronos\Chronos; +use Pterodactyl\Models\User; use Pterodactyl\Models\ApiKey; use Illuminate\Auth\AuthManager; use Illuminate\Contracts\Encryption\Encrypter; @@ -48,6 +49,7 @@ class AuthenticateKeyTest extends MiddlewareTestCase */ public function testMissingBearerTokenThrowsException() { + $this->request->shouldReceive('user')->andReturnNull(); $this->request->shouldReceive('bearerToken')->withNoArgs()->once()->andReturnNull(); try { @@ -117,6 +119,25 @@ class AuthenticateKeyTest extends MiddlewareTestCase $this->assertEquals($model, $this->request->attributes->get('api_key')); } + /** + * Test that we can still make it though this middleware if the user is logged in and passing + * through a cookie. + */ + public function testAccessWithoutToken() + { + $user = factory(User::class)->make(['id' => 123]); + + $this->request->shouldReceive('user')->andReturn($user); + $this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturnNull(); + + $this->getMiddleware()->handle($this->request, $this->getClosureAssertions(), ApiKey::TYPE_ACCOUNT); + $model = $this->request->attributes->get('api_key'); + + $this->assertSame(ApiKey::TYPE_ACCOUNT, $model->key_type); + $this->assertSame(123, $model->user_id); + $this->assertNull($model->identifier); + } + /** * Test that a valid token identifier with an invalid token attached to it * triggers an exception.