Kohana rest api implementaion: how to start with SupersonicAds/kohana-restful-api?

845 views Asked by At

I am new to kohana framework. I need to implement rest api for my application. I have downloded rest api from https://github.com/SupersonicAds/kohana-restful-api and placed in my localhost. Under modules. now the file structre is enter image description here I have enabled module in bootstrap.php as

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
));

i have created a controller by extending "Controller_Rest" Now according to wiki i should be able to access "$this->_user, $this->_auth_type and $this->_auth_source" variables but in my case its not happening what i am doing wrong? And i checked in console network it always showing status as "401 Unauthorised"

1

There are 1 answers

0
Gireesh On

For using Authorization,you need to extend Kohana_RestUser Class

The module you are using comes with an abstract Kohana_RestUser class, which you must extend in your app. The only function that requires implementation is the protected function _find(). The function's implementation is expected to load any user related data, based on an API key.

I will explain you with an example

<?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

Now Test Controller

<?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
    }

}

Now RestUserData Model

<?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/test?apiKey=abc returns

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

Note: K in apiKey is Capital/UpperCase

I Hope this Helps Happy Coding :)