Zend Framework 1.12 plugin for checking "Authorization" header - rest

I'm writing REST api using Zend Framework 1.12. I want to check "Authorization" header in controller plugin.
I put code in the preDispatch action of the plugin
$authorizationHeader = $request->getHeader('Authorization');
if(empty($authorizationHeader)) {
$this->getResponse()->setHttpResponseCode(400);
$this->getResponse()->setBody('Hello');
die(); //It doesn't work
}
The problem is that after it controller's action is still being called. I tried 'die()', 'exit'. My question is how to return response from plugin and do not call controller's action.

Did a similar REST API with Zend several weeks ago with this approach:
Class Vars/Consts:
protected $_hasError = false;
const HEADER_APIKEY = 'Authorization';
My preDispatch:
public function preDispatch()
{
$this->_apiKey = ($this->getRequest()->getHeader(self::HEADER_APIKEY) ? $this->getRequest()->getHeader(self::HEADER_APIKEY) : null);
if (empty($this->_apiKey)) {
return $this->setError(sprintf('Authentication required!'), 401);
}
[...]
}
My custom setError Function:
private function setError($msg, $code) {
$this->getResponse()->setHttpResponseCode($code);
$this->view->error = array('code' => $code, 'message' => $msg);
$this->_hasError = true;
return false;
}
Then simply check if a error has been set inside your functions:
public function yourAction()
{
if(!$this->_hasError) {
//do stuff
}
}
If you're using contextSwitch and JSON, then your array with errors will be automatically returned & displayed, if an error occours:
public function init()
{
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$this->_helper->contextSwitch()->initContext('json');
[...]
}
Hope this helps

Since checking headers is typically a low level request operation, you could do the header verification and then throw an exception if not valid in dispatchLoopStartup of the plugin. Then in your error controller, return the appropriate response. This would prevent the action from being dispatched/run and could be applied to any controller/action without modifying any controller code.
Controller plugin:
class AuthHeader extends Zend_Controller_Plugin_Abstract
{
public function dispatchLoopStartup(\Zend_Controller_Request_Abstract $request)
{
// Validate the header.
$authorizationHeader = $request->getHeader('Authorization');
if ($invalid) {
throw new Zend_Exception($error_message, $error_code);
}
}
}
Error handler:
class ErrorController extends Zend_Controller_Action
{
public function init()
{
// Enable JSON output for API originating errors.
if ($this->isApiRequest($this->getRequest())) {
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('error', 'json')
->setAutoJsonSerialization(true)
->initContext('json');
}
}
public function errorAction()
{
// Handle authorization header errors
// ...
// Handle errors
// ...
}
public function isApiRequest($request)
{
// Determine if request is an API request.
// ...
}
}

Related

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

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
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"
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 :)

Laravel redirect to post method

To stay basic I would like to create a bookmark app
I have a simple bookmarklet
javascript:location.href='http://zas.dev/add?url='+encodeURIComponent(location.href)
I created a rest controller
<?php
use zas\Repositories\DbLinkRepository;
class LinksController extends BaseController {
protected $link;
function __construct(DbLinkRepository $link) {
$this->link=$link;
// ...
//$this->beforeFilter('auth.basic', array('except' => array('index', 'show', 'store')));
// ...
}
public function index()
{
//return Redirect::to('home');
}
public function create()
{
}
public function store()
{
return 'hello';
//$this->link->addLink(Input::get('url'));
//return Redirect::to(Input::get('url'));
}
public function show($id)
{
//$url = $this->link->getUrl($id);
//return Redirect::to($url);
}
public function edit($id)
{
}
public function update($id){
}
public function destroy($id){
}
}
in the routes.php, I created a ressource
Route::resource('links','LinksController');
and as I want to redirect /add to the store method I added
Route::get('/add',function(){
return Redirect::action('LinksController#store');
});
but it never display the hello message, in place it redirects me to
http://zas.dev/links
I also tried with
return Redirect::route('links.store');
without much success
thanks for your help
Ok I now get what you are trying to do. This will work:
Route::get('add', 'LinksController#store');
Remove:
Route::resource('links','LinksController');
and remove:
Route::get('/add',function(){
return Redirect::action('LinksController#store');
});
Sorry it took so long!
The problem is that once you Redirect::, you loose all the Input values, so you should manually give them to your controller when you do the redirect, like so :
Redirect::route('links.store', ["url" => Input::get("url")]);
Finally add an $url parameter to your store method to receive the value we give it in the previous method, like this :
public function store($url) {
$this->link->addLink($url);
return Redirect::to($url);
}

Passing the Ajax request data parameter through Zend Framework Controller to model class

I am Using the Zend Framework.
As a design pattern i am using the state design pattern.
Now as you may know, Zend Framework let's you create custom controllers, which can be used to respond to Ajax requests.
In my example i have the following ajax request
function getResponse(name){
$.ajax({
dataType: 'json',
data: {button: name},
url: 'motor/ajaxtest',
type: 'post',
success: function(response)
{
}
});
}
The function getResponse is called every time a specific button is pressed.
public function ajaxtestAction()
{
$input_in = $this->getRequest()->getParam('button');
$Lok = new Lok();
$this->_helper->viewRenderer->setNoRender();
$text = array($Lok->getMotorState());
$phpNative = Zend_Json::encode($text);
echo $phpNative;
}
The Code above is my custom response to the ajax request. I want to pass on the name of the pressed button to $Lok = new Lok(); so i can use it in the "Lok" model Class without creating a new instance of The controller in the "Lok" class
Is there anyone who might be able to help me ?
EDIT-----------------------------------
Here's my Controller :
class MotorController extends Zend_Controller_Action
{
public function init()
{
}
public function indexAction()
{
}
public function ajaxtestAction()
{
$input_in = array($this->getRequest()->getParam('button'));
$phpNativ1 = Zend_Json::encode($input_in);
echo $phpNativ1;
$Lok = new Lok();
echo $input_in;
$this->_helper->viewRenderer->setNoRender();
$text = array($Lok->getMotorState());
$phpNative = Zend_Json::encode($text);
echo $phpNative;
}
}
Here are my Jquery functions :
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
$("input[name=State]").val('Forwards');
});
function getResponse(name){
$.ajax({
dataType: 'json',
data: {button: name},
url: 'motor/ajaxtest',
type: 'post',
success: function(response)
{
}
});
}
$("button[name=on]").click(function() {
var d_response = getResponse('on');
});
});
And this is my Lok.php file :
class Lok
{
private $newMotor;
private $newTimer;
private $newSpeaker;
private $mySession;
private $motorState;
private $input;
public function __construct()
{
//Method instances
$newMotor = new Motor();
$newTimer = new Timer();
$newSpeaker = new Speaker();
$this->motorState = $newMotor->getMotorState();
// Declaring the Session
$mySession = new Zend_Session_Namespace();
$mySession->s_motorState = $this->motorState;
}
public function __get($mySession)
{
return $this->mySession;
}
public function __set($motorState, $mySession)
{
$this->$mySession->s_motorState = $motorState;
}
public function getMotorState()
{
return $this->motorState;
}
public function playSound($soundNumber)
{
echo "Playing sound";
}
public function resetTimer()
{
echo "Resetting timer";
}
public function setInput($input_in)
{
$this->input=$input_in;
}
}
As i've stated previously you should get the button name by calling the requests post data, this is done by $postData = $this->getRequest()->getPost()
Then, to get the output into your Model, inside your model class you would create a property as well as setter and getter method for it.
class Lok {
protected $button;
public function setButton($btn){}
public function getButton(){}
}
And then it becomes as easy as doing something like
$lokModel->setButton($postData['button'])
First of all, thanks for posting your solution.
I tried to implement your solution but unfortunaly it didnt work.
So after a good night sleep, i looked at the problem again. I think the problem is, that
$postData = $this->getRequest()->getPost() or $postData = $this->getRequest()->getParam('button')
is executed in the response itelfe.
<pre>string(2) "sr"
</pre>["Not Moving"]
This is what the JSON response looks like in The Google Chrom debugger. If you'r familliar with this Google Chrome debugger you know what i mean.
Now the button name that i want is in between the &quot tags the only problem is, getting it out of there. and being able to use it before the response is triggerd. I also tried getPost() and getParam('button') in the init() and indexAktion() Methods in the Controller but it still didn't work
public function init()
{
postData = $this->getRequest()->getPost()
$lokModel->setButton($postData['button'])
}
public function indexAction()
{
postData = $this->getRequest()->getPost()
$lokModel->setButton($postData['button'])
}
Any other ideas ?

CakePHP and Facebook with Security Component turned on

I want the Security Component turned on.
BUT when you load a CakePHP app inside a Facebook tab, FB posts $_REQUEST['signed_request'] to my form - the problem with this is that the Security Component "reacts" to this "post" and gives me validation errors, black-hole, etc.
How do I go around this?
I could not find anything on the documentation to go around this problem.
What I wanted was to somehow run the Security Component "manually" so that it only "reacts" when I actually submit my form and not when Facebook posts the $_REQUEST['signed_request'] to my form.
UPDATE:
<?php
App::uses('CakeEmail', 'Network/Email');
class PagesController extends AppController {
public $helpers = array('Html','Form');
public $components = array('RequestHandler');
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('*');
$this->Security->validatePost = true;
$this->Security->csrfCheck = true;
$this->Security->unlockedFields[] = 'signed_request';
}
public function home() {
$this->loadModel('Memberx');
if($this->request->is('post') && isset($this->request->data['Memberx']['name'])) {
//...save here, etc. ...
}
}
FYI: I get a "black hole" error.
FINAL UPDATE (After #tigrang's answer):
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('*');
$this->set('hasLiked', false);
if(isset($this->request->data['signed_request'])){
$this->set('hasLiked', $this->hasLiked($this->request->data['signed_request']));
}
if(isset($this->request->data['Memberx']['signed_request'])) {
$this->set('hasLiked', $this->hasLiked($this->request->data['Memberx']['signed_request']));
}
/*
To go around Facebook's post $_REQUEST['signed_request'],
we unset the $_REQUEST['signed_request'] and disable the csrfCheck
ONLY after we have set the hasLiked view variable
*/
unset($this->request->data['signed_request']);
if (empty($this->request->data)) {
$this->Security->csrfCheck = false;
}
}
Then, I do something like below in my views:
<?php
if($hasLiked) {
?>
You have liked this page!
<?php
}
?>
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('*');
$this->_validateFbRequest();
}
protected function _valdiateFbRequest() {
if (!isset($this->request->data['signed_request'])) {
// not a valid request from fb
// throw exception or handle however you want
return;
}
$signedRequest = $this->request->data['signed_request'];
unset($this->request->data['signed_request']);
if (empty($this->request->data)) {
$this->Security->csrfCheck = false;
}
// validate the request
}

ZF using placeholders inside plugins

I'm trying to implement a plugin that handles responses to the user on success or failure in a persistance transaction. When the response is false I use a _forward to the action that performed the form's submit and get my placeholder message shown but when the response is true I use a _redirect to the browse with the new record shown.
My problem is that when I use _redirect the browser doesn't show the placeholder message. I'll show the code here:
/**
* Plugin
*/
class Application_Plugin_PostMessage extends Zend_Controller_Plugin_Abstract
{
public function postDispatch(Zend_Controller_Request_Abstract $request)
{
$message = $request->getParam('message');
$error = $request->getParam('error');
if (null !== $message || null !== $error) {
$layout = Zend_Layout::getMvcInstance();
$view = $layout->getView();
$placeHolder = $view->placeholder('message');
$placeHolder->setPostfix('</div>');
if (null !== $error) {
$placeHolder->setPrefix('<div class="errorMessage">')
->append($error);
}
elseif (null !== $message) {
$placeHolder->setPrefix('<div class="infoMessage">')
->append($message);
}
}
}
}
/**
* Controller
*/
class My_FooController extends Zend_Controller_Action
{
public function init()
{
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Application_Plugin_PostMessage());
}
...
public function browseAction()
{
...
// No message is shown here on redirect
...
}
public function newAction()
{
...
// This code shows the placeholder on _forward call
...
}
public function insertAction()
{
if(true) {
return $this->_redirect('/my/foo/browse?message='
. urlencode("success message"));
}
else {
return $this->_forward('new', null, null, array(
'error' => 'error messsage'
));
}
}
}
I can't use _forward on success because I don't want the use of [F5] key repeats the insert action
Thanks in advance
This is what Flash Messenger is for:
http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelper.flashmessenger.basicusage
It stores messages in your session removing the need for passing messages as you are.