Respond with json in CakePHP controller - cakephp

My code looks something like this:
if ($this->request->is('ajax')) {
$this->Comment->Save();
$this->set('comment', $this->Comment->read());
$this->set('_serialize', array('comment');
}
Instead of responding with Ajax, I get an error that a view is missing. Is there something else that's needed to respond with json? I thought this was handled "automagically" with the response helper.

By enabling RequestHandlerComponent in your application, and enabling support for the xml
and or json extensions, you can automatically leverage the new view classes.
So you still need to enable a few things:
Add
public $components = array('RequestHandler');
and in routes.php
Router::parseExtensions(array('json'));
You may have to have your url look like controller/action.json for the automagic to work. You could just add $this->viewClass = 'Json' in the controller, though (not 100% sure on this).

Related

How can CakePHP Authorization plugin authorize access to indexes?

I'm converting my app to CakePHP 3.6, and working now on using the new Authorization plugin. I'm not sure how to check authorization for things like indexes or other reports, where there is no "resource" to pass to the can() or authorize() functions.
For now, I've built a ControllerResolver, loosely copied from the ORMResolver, which accepts controller objects and finds policies based on the singularized controller name, so that they're named the same as the Entity policies I'm building. (That is, my UserPolicy can have canIndex and canEdit functions, the former found via the controller and the latter via the entity.)
This works fine in controller actions where I can call $this->Authorize->authorize($this);, but it doesn't work in views, where I'd like to be able to do things like:
if ($this->Identity->can('index', *something*)) {
echo $this->Html->link('List', ['action' => 'index']);
}
so as to only show links to people who are allowed to run those actions.
Anyone know if there's a reason why the system implicitly requires that the "resource" passed into authorization functions be an object? (For example, the plugin component calls get_class($resource) in the case of a failed authorization, without first checking that the provided resource is in fact an object.) Allowing a string (e.g. \App\Controller\UsersController::class) would make my life easy. Very happy to put together a PR for this if it's just an oversight.
But authorizing indexes seems like a pretty obvious function, so I wonder if I've missed something. Maybe I'm supposed to pass the table object, and split the authorization between an entity policy and a table policy? But using table objects in views just for this purpose seems like a violation of separation of concerns. Maybe uses of the plugin to date have been things where indexes are always public?
to do this you can use the authorizeModel, as stated in the documentation https://github.com/cakephp/authorization/blob/master/docs/Component.md#automatic-authorization-checks. Basically is adding the auhtorizeModel parameters when you load the component at AppController.php
$this->loadComponent('Authorization.Authorization', [
'skipAuthorization' => ['login','token'],
'authorizeModel' => ['index','add'],
]);
When you configure an action to be authorized by model the authorization service uses the TablePolicy, so if you want to authorize the index action for Books you need to create the BooksTablePolicy and implement the method
<?php
namespace App\Policy;
use App\Model\Table\BooksTable;
use Authorization\IdentityInterface;
/**
* Books policy
*/
class BooksTablePolicy
{
public function scopeIndex($user, $query)
{
return $query->where(['Books.user_id' => $user->id]);
}
public function canIndex(IdentityInterface $identity)
{
// here you can resolve true or false depending of the identity required characteristics
$identity['can_index']=true;
return $identity['can_index'];
}
}
This will be validated before the request reaches your controller so you do not need to authorize anything there. Nevertheless if you want to apply an scope policy as you can see in this example:
public function index()
{
$user = $this->request->getAttribute('identity');
$query = $user->applyScope('index', $this->Books->find()->contain('Users'));
$this->set('books', $this->paginate($query));
}

Setting a header in CakePHP (MVC)

I'm trying to integrate PayPal's IPN code into CakePHP 3.
namespace App\Controller;
use PayPal\Api\PaypalIPN;
class IpnController extends AppController
{
public function index()
{
$this->autoRender = false;
$ipn = new PayPalIPN();
// Use the sandbox endpoint during testing.
$ipn->useSandbox();
$verified = $ipn->verifyIPN();
if ($verified) {
/*
* Process IPN
* A list of variables is available here:
* https://developer.paypal.com/webapps/developer/docs/classic/ipn/integration-guide/IPNandPDTVariables/
*/
}
// Reply with an empty 200 response to indicate to paypal the IPN was received correctly.
header("HTTP/1.1 200 OK");
}
}
This is failing to validate on PayPal's end and I'm suspecting it has to do with setting the headers in the controller view.
Is there a way to set the header properly in CakePHP's controller.
I had this code running stand alone (in just a php file) and it seemed to work just fine.
You should not output any data in your controller action - that means you should not use echo, header() or any function or construct that would return anything to browser. If you do, you will encounter a "headers already sent" error.
If you want to set headers, you should use withHeader() or withAddedHeader() methods of Cake\Http\Response.
For status codes, you also have withStatus() method:
$response = $this->response;
$response = $response->withStatus(200,"OK");
return $response; // returning response will stop controller from rendering a view.
More about setting headers can be found in docs:
Setting response headers in CakePHP 3
Cake\Http\Response::withStatus()
Maybe that's not very Cakish, but actually one can send headers this way - it just have to be followed by die; or exit; to prevent app from further response processing.
Anyway, for sure your problem is not associated with headers. IPN seems to doesn't work properly with Paypal Sandbox. Maybe you should try it other way with ApiContext class?

CakePHP (2.4) routes json

I have this in my routes file:
CakePlugin::routes();
Router::mapResources('api');
Router::parseExtensions('json');
Currently if I call a controller I have Api with .json as an extension as long as it's a HTTP GET (not post) it outputs json which is fine, no matter the method/function name as long as it exists in my Api controller.
If I make a post, whilst I can decode the posted JSON whatever function/method I've called, it errors saying I'm missing xxx.ctp in app/Api/Views/json/
xxx.ctp = the name of any function I've called to post.
2 Questions/problems.
Ideally I want to parse any request to the Api controller as json, but without having to specify the .json extension in the url.
Secondly, how/why can't the HTTP POST output json like the HTTP GET, do I need to map something else somewhere?
Many thanks
If you want to render everything from a specific controller (in your case, ApiController.php) as JSON without requiring the user to append the .json extension on their request, you can use renderAs and setContent in your beforeFilter.
public function beforeFilter() {
parent::beforeFilter();
$this->RequestHandler->setContent('json');
$this->RequestHandler->renderAs($this, 'json');
}
renderAs and setContent are part of RequestHandler.
This does mean that this controller will never return anything other than json. If your happy with that, you can even remove extension catcher in your routes.php file...
Router::parseExtensions('json');
Remembering that if you remove the above line from your routes.php file, a request to your ApiController of any kind will result in a 404 being thrown (not as JSON).
Developing further using the beforeFilter you can actually render as different content-types depending on the type of request. For example..
public function beforeFilter() {
parent::beforeFilter();
if ($this->RequestHandler->isGet()) {
$this->RequestHandler->setContent('json');
$this->RequestHandler->renderAs($this, 'json');
}
}

CakePHP: Data sanitization while updating

I have a problem with sanitization. In AppController I'm using Sanitization utility but It doesn't work. When I want to call my update It fails because of ' slash in my input text. I'm using CakePHP 2.3.6.
function beforeFilter(){
if(!empty($this->data)){
App::uses('Sanitize', 'Utility');
$this->request->data = Sanitize::clean($this->data, array('remove_html'=>true,'encode'=>false,'unicode'=>false,'backslash'=>true, 'escape'=>false));
}
}
Controller code:
$this->ClientProfile->updateAll(
array('ClientProfile.location'=>"'".$this->User->data['ClientProfile']['location']."'"),
array('ClientProfile.user_id'=>$userdata['id'])
);
Any ideas?
Try using Sanitize::escape() instead of Sanitize::clean(). As it's written in the documentation,
Sanitize::escape()
Makes a string SQL-safe.
You may also move data sanitization directly to updateAll() method call. By doing this you will know that updateAll() method will get sanitized data, no matter what happened with this data in other parts of your script.

What's the proper way to serve JSONP with CakePHP?

I want to serve JSONP content with CakePHP and was wondering what's the proper way of doing it so.
Currently I'm able to serve JSON content automatically by following this CakePHP guide.
Ok, I found a solution on this site. Basically you override the afterFilter method with:
public function afterFilter() {
parent::afterFilter();
if (empty($this->request->query['callback']) || $this->response->type() != 'application/json') {
return;
}
// jsonp response
App::uses('Sanitize', 'Utility');
$callbackFuncName = Sanitize::clean($this->request->query['callback']);
$out = $this->response->body();
$out = sprintf("%s(%s)", $callbackFuncName, $out);
$this->response->body($out);
}
I hope it helps someone else as well.
I've as yet not found a complete example of how to correctly return JSONP using CakePHP 2, so I'm going to write it down. OP asks for the correct way, but his answer doesn't use the native options available now in 2.4. For 2.4+, this is the correct method, straight from their documentation:
Set up your views to accept/use JSON (documentation):
Add Router::parseExtensions('json'); to your routes.php config file. This tells Cake to accept .json URI extensions
Add RequestHandler to the list of components in the controller you're going to be using
Cake gets smart here, and now offers you different views for normal requests and JSON/XML etc. requests, allowing you flexibility in how to return those results, if needed. You should now be able to access an action in your controller by:
using the URI /controller/action (which would use the view in /view/controller/action.ctp), OR
using the URI /controller/action.json (which would use the view in /view/controller/json/action.ctp)
If you don't want to define those views i.e. you don't need to do any further processing, and the response is ready to go, you can tell CakePHP to ignore the views and return the data immediately using _serialize. Using _serialize will tell Cake to format your response in the correct format (XML, JSON etc.), set the headers and return it as needed without you needing to do anything else (documentation). To take advantage of this magic:
Set the variables you want to return as you would a view variable i.e. $this->set('post', $post);
Tell Cake to serialize it into XML, JSON etc. by calling $this->set('_serialize', array('posts'));, where the parameter is the view variable you just set in the previous line
And that's it. All headers and responses will be taken over by Cake. This just leaves the JSONP to get working (documentation):
Tell Cake to consider the request a JSONP request by setting $this->set('_jsonp', true);, and Cake will go find the callback function name parameter, and format the response to work with that callback function name. Literally, setting that one parameter does all the work for you.
So, assuming you've set up Cake to accept .json requests, this is what your typical action could look like to work with JSONP:
public function getTheFirstPost()
$post = $this->Post->find('first');
$this->set(array(
'post' => $post, <-- Set the post in the view
'_serialize' => array('post'), <-- Tell cake to use that post
'_jsonp' => true <-- And wrap it in the callback function
)
);
And the JS:
$.ajax({
url: "/controller/get-the-first-post.json",
context: document.body,
dataType: 'jsonp'
}).done(function (data) {
console.log(data);
});
For CakePHP 2.4 and above, you can do this instead.
http://book.cakephp.org/2.0/en/views/json-and-xml-views.html#jsonp-response
So you can simply write:
$this->set('_jsonp', true);
in the relevant action.
Or you can simply write:
/**
*
* beforeRender method
*
* #return void
*/
public function beforeRender() {
parent::beforeRender();
$this->set('_jsonp', true);
}

Resources