2017-02-02 10 views
0

Я новичок в дизайне Kohana. Мне нужно реализовать rest api для моего приложения. У меня есть downloded rest api от https://github.com/SupersonicAds/kohana-restful-api и помещен в мой localhost. Под модулями. Теперь файл structre является enter image description here Я включил модуль в bootstrap.php вKohana rest api implementaion: как начать работу с SupersonicAds/kohana-restful-api?

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 я должен быть в состоянии получить доступ к "$ это -> _ user, $ this -> _ auth_type и $ this -> _ auth_source "переменные, но в моем случае его не происходит, что я делаю неправильно? И я проверил в консоли сети всегда показывать статус «401 Несанкционированное»

+0

я думаю, что проблема с вышеуказанной проблемой является размещение папок. Любая помощь? – Shridhar

+0

Для использования авторизации необходимо расширить класс Kohana_RestUser. https://github.com/SupersonicAds/kohana-restful-api/blob/master/classes/Kohana/Controller/Rest.php#L372 – bato3

ответ

0

Для использования авторизации, необходимо расширить 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 
     } 

} 

So index.php/тест? ApiKey = а возвращают

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

Примечание: K в apiKey является Capital/UpperCase

Я надеюсь, что это помогает Счастливый Coding :)

 Смежные вопросы

  • Нет связанных вопросов^_^