Skip to content

Commit 8bbe6bc

Browse files
committed
Add test, fix behavior of model creation
1 parent 550c622 commit 8bbe6bc

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

app/Http/Middleware/Api/AuthenticateKey.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,15 +68,15 @@ public function handle(Request $request, Closure $next, int $keyType)
6868
// This is a request coming through using cookies, we have an authenticated user not using
6969
// an API key. Make some fake API key models and continue on through the process.
7070
if (empty($raw) && $request->user() instanceof User) {
71-
$model = new ApiKey([
71+
$model = (new ApiKey())->forceFill([
7272
'user_id' => $request->user()->id,
7373
'key_type' => ApiKey::TYPE_ACCOUNT,
7474
]);
7575
} else {
7676
$model = $this->authenticateApiKey($raw, $keyType);
77+
$this->auth->guard()->loginUsingId($model->user_id);
7778
}
7879

79-
$this->auth->guard()->loginUsingId($model->user_id);
8080
$request->attributes->set('api_key', $model);
8181

8282
return $next($request);

tests/Unit/Http/Middleware/API/AuthenticateKeyTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Mockery as m;
66
use Cake\Chronos\Chronos;
7+
use Pterodactyl\Models\User;
78
use Pterodactyl\Models\ApiKey;
89
use Illuminate\Auth\AuthManager;
910
use Illuminate\Contracts\Encryption\Encrypter;
@@ -48,6 +49,7 @@ public function setUp()
4849
*/
4950
public function testMissingBearerTokenThrowsException()
5051
{
52+
$this->request->shouldReceive('user')->andReturnNull();
5153
$this->request->shouldReceive('bearerToken')->withNoArgs()->once()->andReturnNull();
5254

5355
try {
@@ -117,6 +119,25 @@ public function testValidTokenWithUserKey()
117119
$this->assertEquals($model, $this->request->attributes->get('api_key'));
118120
}
119121

122+
/**
123+
* Test that we can still make it though this middleware if the user is logged in and passing
124+
* through a cookie.
125+
*/
126+
public function testAccessWithoutToken()
127+
{
128+
$user = factory(User::class)->make(['id' => 123]);
129+
130+
$this->request->shouldReceive('user')->andReturn($user);
131+
$this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturnNull();
132+
133+
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions(), ApiKey::TYPE_ACCOUNT);
134+
$model = $this->request->attributes->get('api_key');
135+
136+
$this->assertSame(ApiKey::TYPE_ACCOUNT, $model->key_type);
137+
$this->assertSame(123, $model->user_id);
138+
$this->assertNull($model->identifier);
139+
}
140+
120141
/**
121142
* Test that a valid token identifier with an invalid token attached to it
122143
* triggers an exception.

0 commit comments

Comments
 (0)