Реализация Kohana rest API: как начать с SupersonicAds/kohana-restful-api?

Я новичок в kohana framework. Мне нужно реализовать API отдыха для моего приложения. Я скачал rest API с https://github.com/SupersonicAds/kohana-restful-api и помещен в мой локальный хост. Под модули. теперь структура файла введите здесь описание изображения Я включил модуль в bootstrap.php как

Kohana::modules(array(
'auth'             => MODPATH.'auth',       // Basic authentication
'rest'              => MODPATH.'rest',    // Basic Rest example
// 'cache'      => MODPATH.'cache',      // Caching with multiple backends
// 'codebench'  => MODPATH.'codebench',  // Benchmarking tool
 'database'   => MODPATH.'database',   // Database access
// 'image'      => MODPATH.'image',      // Image manipulation
// 'minion'     => MODPATH.'minion',     // CLI Tasks
 'orm'        => MODPATH.'orm',        // Object Relationship Mapping
// 'unittest'   => MODPATH.'unittest',   // Unit testing
// 'userguide'  => MODPATH.'userguide',  // User guide and API documentation
));

я создал контроллер, расширив «Controller_Rest». Теперь согласно wiki я должен иметь доступ к переменным "$this->_user, $this->_auth_type и $this->_auth_source", но в моем случае этого не происходит, что я делаю неправильно ? И я проверил в сети консоли, он всегда показывает статус «401 Unauthorized».


person Shridhar    schedule 02.02.2017    source источник
comment
Я думаю, что проблема с вышеуказанной проблемой заключается в размещении папок. Любая помощь?   -  person Shridhar    schedule 02.02.2017
comment
Для использования авторизации вам необходимо расширить класс Kohana_RestUser. github.com/SupersonicAds/ kohana-restful-api/blob/master/classes/   -  person bato3    schedule 14.03.2017


Ответы (1)


Для использования авторизации вам необходимо расширить класс Kohana_RestUser

Используемый вами модуль поставляется с абстрактным классом Kohana_RestUser, который вы должны расширить в своем приложении. Единственная функция, требующая реализации, это защищенная функция _find(). Ожидается, что реализация функции будет загружать любые данные, связанные с пользователем, на основе ключа API.

Я объясню вам на примере

<?php
// Model/RestUser.php
class RestUser extends Kohana_RestUser {
    protected $user='';
    protected function _find()
    {

    //generally these are stored in databases 
    $api_keys=array('abc','123','testkey');

    $users['abc']['name']='Harold Finch';
    $users['abc']['roles']=array('admin','login');

    $users['123']['name']='John Reese';
    $users['123']['roles']=array('login');

    $users['testkey']['name']='Fusco';
    $users['testkey']['roles']=array('login');

    foreach ($api_keys as $key => $value) {
        if($value==$this->_api_key){
            //the key is validated which is authorized key
            $this->_id = $key;//if this not null then controller thinks it is validated
            //$this->_id must be set if key is valid.
            //setting name
            $this->user = $users[$value];
            $this->_roles = $users[$value]['roles']; 
            break;

        }
    }


    }//end of _find
    public function get_user()
    {
        return $this->name;
    }
}//end of RestUser

Теперь тестовый контроллер

<?php defined('SYSPATH') or die('No direct script access.');
//Controller/Test.php
class Controller_Test extends Controller_Rest
{
    protected $_rest;
    // saying the user must pass an API key.It is set according to the your requirement
    protected $_auth_type = RestUser::AUTH_TYPE_APIKEY;
    // saying the authorization data is expected to be found in the request's query parameters.
    protected $_auth_source = RestUser::AUTH_SOURCE_GET;//depends on requirement/coding style
    //note $this->_user is current Instance of RestUser Class

    public function before()
    {
        parent::before();
        //An extension of the base model class with user and ACL integration.
        $this->_rest = Model_RestAPI::factory('RestUserData', $this->_user);

    }
    //Get API Request
    public function action_index()
    {

        try
        {

                $user = $this->_user->get_name();
                if ($user)
                {
                    $this->rest_output( array(
                        'user'=>$user,

                    ) );
                }
                else
                {
                    return array(
                        'error'
                    );
                }
        }
        catch (Kohana_HTTP_Exception $khe)
        {
            $this->_error($khe);
            return;
        }
        catch (Kohana_Exception $e)
        {
            $this->_error('An internal error has occurred', 500);
            throw $e;
        }

    }
    //POST API Request
    public function action_create()
    {
        //logic to create 
        try
        {
            //create is a method in RestUserData Model
            $this->rest_output( $this->_rest->create( $this->_params ) );
        }
        catch (Kohana_HTTP_Exception $khe)
        {
            $this->_error($khe);
            return;
        }
        catch (Kohana_Exception $e)
        {
            $this->_error('An internal error has occurred', 500);
            throw $e;
        }
    }
    //PUT API Request
    public function action_update()
    {
        //logic to create
    }
    //DELETE API Request
    public function action_delete()
    {
        //logic to create
    }

}

Теперь модель RestUserData

<?php
//Model/RestUserData.php
class Model_RestUserData extends Model_RestAPI {

        public function create($params)
        {
            //logic to store data in db
            //You can access $this->_user here
        }

}

Итак, index.php/test?apiKey=abc возвращает

{
     "user": {
        "name": "Harold Finch",
        "roles": [
            "admin",
            "login"
        ]
    }
   }

Примечание. K в ключе apiKey – это заглавная/верхняя буква.

Я надеюсь, что это поможет счастливому кодированию :)

person Gireesh Kudipudi    schedule 21.07.2017