Skip to content

Commit

Permalink
Merge pull request #17 from givebutter/fix/prefixed-key-with-compatib…
Browse files Browse the repository at this point in the history
…ility-mode-on
  • Loading branch information
jhoff authored Nov 16, 2023
2 parents fe26657 + e1b39c2 commit 002c132
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 10 deletions.
3 changes: 1 addition & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@
"minimum-stability": "dev",
"prefer-stable": true,
"require": {
"php": "^7.0|^8.0",
"doctrine/dbal": "^3.7"
"php": "^7.0|^8.0"
},
"autoload": {
"psr-4": {
Expand Down
23 changes: 19 additions & 4 deletions src/Models/ApiKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,17 +105,32 @@ public function scopeOfKey(Builder $query, string $key): Builder

if ($compatibilityMode) {
return $query->where(function (Builder $query) use ($key) {
return $query->where('key', $key)
->orWhere('key', hash('sha256', $key));
if (! str_contains($key, '|')) {
return $query->where('key', $key)
->orWhere('key', hash('sha256', $key));
}

[$id, $key] = explode('|', $key, 2);

return $query
->where(function (Builder $query) use ($key, $id) {
return $query->where('key', $key)
->where('id', $id);
})
->orWhere(function (Builder $query) use ($key, $id) {
return $query->where('key', hash('sha256', $key))
->where('id', $id);
});
});
}

if (strpos($key, '|') === false) {
if (! str_contains($key, '|')) {
return $query->where('key', hash('sha256', $key));
}

[$id, $key] = explode('|', $key, 2);

return $query->where('id', $id)->where('key', hash('sha256', $key));
return $query->where('id', $id)
->where('key', hash('sha256', $key));
}
}
18 changes: 14 additions & 4 deletions tests/Feature/CompatibilityMode.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,24 @@ public function accepts_both_hashed_and_non_hashed_api_keys_when_compatibility_m
'key' => $apiKey2->fresh()->key,
]);

// Assert the non hashed api keys works
// Assert that non hashed api keys works
$this->withHeaders([
'Authorization' => 'Bearer ' . $plainTextApiKey1,
'Authorization' => "Bearer {$plainTextApiKey1}",
])->get("/api/posts/{$post->id}")->assertOk();

// Assert the hashed api keys works
// Assert that non hashed api keys with ID prefix works
$this->withHeaders([
'Authorization' => 'Bearer ' . $plainTextApiKey2,
'Authorization' => "Bearer {$apiKey1->id}|{$plainTextApiKey1}",
])->get("/api/posts/{$post->id}")->assertOk();

// Assert that hashed api keys works
$this->withHeaders([
'Authorization' => "Bearer {$plainTextApiKey2}",
])->get("/api/posts/{$post->id}")->assertOk();

// Assert that hashed api keys with ID prefix works
$this->withHeaders([
'Authorization' => "Bearer {$apiKey2->id}|{$plainTextApiKey2}",
])->get("/api/posts/{$post->id}")->assertOk();
}
}

0 comments on commit 002c132

Please sign in to comment.