| 1 |
<?php |
| 2 |
|
| 3 |
namespace Intervention\HttpAuth\Vault; |
| 4 |
|
| 5 |
use Intervention\HttpAuth\AbstractVault; |
| 6 |
use Intervention\HttpAuth\Directive; |
| 7 |
use Intervention\HttpAuth\Key; |
| 8 |
|
| 9 |
class DigestVault extends AbstractVault |
| 10 |
{ |
| 11 |
/** |
| 12 |
* Determine if given key is able to unlock (access) vault. |
| 13 |
* |
| 14 |
* @param Key $key |
| 15 |
* @return bool |
| 16 |
*/ |
| 17 |
public function unlocksWithKey(Key $key): bool |
| 18 |
{ |
| 19 |
$username_match = $key->getUsername() == $this->getUsername(); |
| 20 |
$hash_match = $key->getResponse() == $this->getKeyHash($key); |
| 21 |
|
| 22 |
return $username_match && $hash_match; |
| 23 |
} |
| 24 |
|
| 25 |
/** |
| 26 |
* Build and return hash from given key/vault |
| 27 |
* |
| 28 |
* @param Key $key |
| 29 |
* @return string |
| 30 |
*/ |
| 31 |
private function getKeyHash(Key $key): string |
| 32 |
{ |
| 33 |
return md5(implode(':', [ |
| 34 |
md5(sprintf('%s:%s:%s', $key->getUsername(), $this->getRealm(), $this->getPassword())), |
| 35 |
$key->getNonce(), |
| 36 |
$key->getNc(), |
| 37 |
$key->getCnonce(), |
| 38 |
$key->getQop(), |
| 39 |
md5(sprintf('%s:%s', $this->getRequestMethod(), $key->getUri())), |
| 40 |
])); |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Return HTTP request method |
| 45 |
* |
| 46 |
* @return string |
| 47 |
*/ |
| 48 |
private function getRequestMethod() |
| 49 |
{ |
| 50 |
return isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET'; |
| 51 |
} |
| 52 |
|
| 53 |
/** |
| 54 |
* Return auth directive |
| 55 |
* |
| 56 |
* @return Directive |
| 57 |
*/ |
| 58 |
public function getDirective(): Directive |
| 59 |
{ |
| 60 |
return new Directive('digest', [ |
| 61 |
'realm' => $this->getRealm(), |
| 62 |
'qop' => 'auth', |
| 63 |
'nonce' => uniqid(), |
| 64 |
'opaque' => md5($this->getRealm()), |
| 65 |
]); |
| 66 |
} |
| 67 |
} |
| 68 |
|