<?php
/**
 * Yii RESTful API
 *
 * @link      https://github.com/paysio/yii-rest-api
 * @copyright Copyright (c) 2012 Pays I/O Ltd. (http://pays.io)
 * @license   http://www.opensource.org/licenses/mit-license.php MIT license
 * @package   REST_Service
 */

namespace rest\service\auth\adapters;

use rest\service\auth\AdapterInterface;

class Basic implements AdapterInterface
{
    /**
     * @var string
     */
    public $realm = 'REST API';

    /**
     * @var string
     */
    public $identityClass = 'application.modules.api.components.UserIdentityRestApi';

    /**
     * @throws \CHttpException
     */
    public function authenticate()
    {
        header('WWW-Authenticate: Basic realm="' . $this->realm . '"');

        if (!isset($_SERVER['PHP_AUTH_USER'])) {
            throw new \CHttpException(401, \Yii::t('common', 'Undefined auth user. Please send PHP_AUTH_USER'));
        }
        if (!isset($_SERVER['PHP_AUTH_PW'])) {
            throw new \CHttpException(401, \Yii::t('common', 'Undefined auth user. Please send PHP_AUTH_PW'));
        }

        $user = filter_var($_SERVER['PHP_AUTH_USER'], FILTER_SANITIZE_STRING);
        $token = filter_var($_SERVER['PHP_AUTH_PW'], FILTER_SANITIZE_STRING);

        $identityClass = \Yii::import($this->identityClass);
        $identity = new $identityClass($user, $token);
        if (!$identity->authenticate()) {
            throw new \CHttpException(401, $identity->errorMessage);
        }

        \Yii::app()->user->login($identity);
    }
}