pflorek /
php-basic-auth
| 1 | <?php |
||
| 2 | |||
| 3 | namespace PFlorek\BasicAuth; |
||
| 4 | |||
| 5 | use Psr\Http\Message\MessageInterface; |
||
| 6 | use Psr\Http\Message\RequestInterface; |
||
| 7 | use Psr\Http\Message\ResponseInterface; |
||
| 8 | |||
| 9 | class BasicAuth |
||
| 10 | { |
||
| 11 | /** |
||
| 12 | * Obtain username and password |
||
| 13 | * |
||
| 14 | * @param RequestInterface $request |
||
| 15 | * @return CredentialsInterface|null |
||
| 16 | */ |
||
| 17 | public function obtainCredentials($request) |
||
| 18 | { |
||
| 19 | $header = $request->getHeader('Authorization'); |
||
| 20 | |||
| 21 | if (!$header) { |
||
|
0 ignored issues
–
show
|
|||
| 22 | return null; |
||
| 23 | } |
||
| 24 | |||
| 25 | $header = array_shift($header); |
||
| 26 | |||
| 27 | $matches = []; |
||
| 28 | if (!preg_match('/Basic (.*)$/', $header, $matches)) { |
||
| 29 | return null; |
||
| 30 | } |
||
| 31 | |||
| 32 | list($username, $password) = \PFlorek\BasicAuth\retrieve_username_and_password($matches[1]); |
||
| 33 | |||
| 34 | return new Credentials($username, $password); |
||
| 35 | } |
||
| 36 | |||
| 37 | /** |
||
| 38 | * Add WWW-Authenticate header field to receive authorization. |
||
| 39 | * |
||
| 40 | * @param RequestInterface $request |
||
| 41 | * @param CredentialsInterface $credentials |
||
| 42 | * @return ResponseInterface|MessageInterface |
||
| 43 | */ |
||
| 44 | public function addCredentials($request, $credentials) |
||
| 45 | { |
||
| 46 | $basicCredentials = \PFlorek\BasicAuth\create_basic_credentials($credentials->getUsername(), $credentials->getPassword()); |
||
| 47 | |||
| 48 | return $request->withHeader('WWW-Authenticate', "Basic {$basicCredentials}"); |
||
| 49 | } |
||
| 50 | |||
| 51 | /** |
||
| 52 | * Add 401 (Unauthorized) status code and WWW-Authenticate header field to reply with a challenge. |
||
| 53 | * |
||
| 54 | * @param ResponseInterface $response |
||
| 55 | * @param string $realm |
||
| 56 | * @return ResponseInterface|MessageInterface |
||
| 57 | */ |
||
| 58 | public function addChallenge($response, $realm) { |
||
| 59 | return $response |
||
| 60 | ->withStatus(401) |
||
| 61 | ->withHeader('WWW-Authenticate', "Basic realm=\"{$realm}\""); |
||
| 62 | } |
||
| 63 | } |
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)or! empty(...)instead.