<commit_before><?php

/**
 * Copyright 2015 <NAME> <<EMAIL>>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace fkooman\Rest\Plugin\Basic;

use fkooman\Http\Exception\BadRequestException;
use fkooman\Http\Exception\UnauthorizedException;
use fkooman\Http\Request;
use fkooman\Rest\Plugin\Authentication\AuthenticationPluginInterface;
use InvalidArgumentException;

class BasicAuthentication implements AuthenticationPluginInterface
{
    /** @var callable */
    private $retrieveHash;

    /** @var string */
    private $realm;

    public function __construct($retrieveHash, $realm = 'Protected Resource')
    {
        // type hint 'callable' works only in >= PHP 5.4
        if (!is_callable($retrieveHash)) {
            throw new InvalidArgumentException('provided parameter is not callable');
        }
        $this->retrieveHash = $retrieveHash;
        $this->realm = $realm;
    }

    public function getRealm()
    {
        return $this->realm;
    }

    public function getScheme()
    {
        return 'Basic';
    }

    public function isAttempt(Request $request)
    {
        $authHeader = $request->getHeader('Authorization');
        if (null === $authHeader) {
            return false;
        }
        if (0 !== strpos($authHeader, 'Basic ')) {
            return false;
        }

        return true;
    }

    public function execute(Request $request, array $routeConfig)
    {
        if ($this->isAttempt($request)) {
            // if there is an attempt, it MUST succeed
            $authHeader = $request->getHeader('Authorization');
            $authUserPass = self::extractUserPass(substr($authHeader, 6));
            if (false === $authUserPass) {
                // problem in getting the authUser and authPass
                throw new BadRequestException('unable to decode authUser and/or authPass');
            }
            list($authUser, $authPass) = $authUserPass;

            // retrieve the hashed password for given user
            $passHash = call_user_func($this->retrieveHash, $authUser);

            if (!password_verify($authPass, $passHash)) {
                throw new UnauthorizedException(
                    'invalid_credentials',
                    'provided credentials not valid',
                    'Basic',
                    array(
                        'realm' => $this->realm,
                    )
                );
            }

            return new BasicUserInfo($authUser);
        } else {
            // if there is no attempt, and authentication is not required,
            // then we can let it go :)
            if (array_key_exists('requireAuth', $routeConfig)) {<commit_msg>fix case where user does not exists and callback returns false<commit_after><?php

/**
 * Copyright 2015 <NAME> <<EMAIL>>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace fkooman\Rest\Plugin\Basic;

use fkooman\Http\Exception\BadRequestException;
use fkooman\Http\Exception\UnauthorizedException;
use fkooman\Http\Request;
use fkooman\Rest\Plugin\Authentication\AuthenticationPluginInterface;
use InvalidArgumentException;

class BasicAuthentication implements AuthenticationPluginInterface
{
    /** @var callable */
    private $retrieveHash;

    /** @var string */
    private $realm;

    public function __construct($retrieveHash, $realm = 'Protected Resource')
    {
        // type hint 'callable' works only in >= PHP 5.4
        if (!is_callable($retrieveHash)) {
            throw new InvalidArgumentException('provided parameter is not callable');
        }
        $this->retrieveHash = $retrieveHash;
        $this->realm = $realm;
    }

    public function getRealm()
    {
        return $this->realm;
    }

    public function getScheme()
    {
        return 'Basic';
    }

    public function isAttempt(Request $request)
    {
        $authHeader = $request->getHeader('Authorization');
        if (null === $authHeader) {
            return false;
        }
        if (0 !== strpos($authHeader, 'Basic ')) {
            return false;
        }

        return true;
    }

    public function execute(Request $request, array $routeConfig)
    {
        if ($this->isAttempt($request)) {
            // if there is an attempt, it MUST succeed
            $authHeader = $request->getHeader('Authorization');
            $authUserPass = self::extractUserPass(substr($authHeader, 6));
            if (false === $authUserPass) {
                // problem in getting the authUser and authPass
                throw new BadRequestException('unable to decode authUser and/or authPass');
            }
            list($authUser, $authPass) = $authUserPass;

            // retrieve the hashed password for given user
            $passHash = call_user_func($this->retrieveHash, $authUser);
            if (false === $passHash || !password_verify($authPass, $passHash)) {
                throw new UnauthorizedException(
                    'invalid_credentials',
                    'provided credentials not valid',
                    'Basic',
                    array(
                        'realm' => $this->realm,
                    )
                );
            }

            return new BasicUserInfo($authUser);
        } else {
            // if there is no attempt, and authentication is not required,
            // then we can let it go :)
            if (array_key_exists('requireAuth', $routeConfig)) {
{'fraction_non_alphanumeric': 0.09958120055839925, 'fraction_numerical': 0.0037226617031177293, 'mean_word_length': 2.25, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4819099', 'n_tokens_mistral': 1675, 'n_tokens_neox': 1611, 'n_words': 518}