I am building a simple app built in PhoneGap that uses a REST API to load in data from my website on the server (because you can't run PHP inside PhoneGap).
An example for listing some data might be:
$.ajax({
url: 'http://myserver.com/posts/index.json',
dataType: 'jsonp',
success: function(data) {
for (var i=0,total=data.length; i<total; i++)
{
console.log(data.Post.title[i]);
}
}
});
This is fine and the returned data can be used in my PhoneGap app. However let's say that the post list requires you to be logged in...
How would I handle this? Because unlike a normal authentication request whereby it redirects to the login form, in my JSON world this would not happen. In fact what happens is the actual HTML login form gets returned which then causes an error because my JavaScript is expecting JSON and not HTML.
Is there a best practice for handling this, such as if authentication requested then load the login form view in the PhoneGap app instead of returning the HTML login form from the app as it's currently doing? Perhaps sending a auth request via JSON?
As an example a simple JSONized method looks like:
public function index() {
$this->set('posts', $this->paginate());
$this->set('_serialize', array('posts'));
}
And as stated earlier I can protect this method in the beforeFilter by not passing the method name into the $this->Auth->allow(). So I'm presuming I would need to do something clever in the beforeFilter to know if the request is JSON and if so then check if the method requires authorisation and then if so either send back an error (instead of the HTML form as Cake usually does via the AuthComponent) in JSON or allow access.
UPDATE: 13th Jan 2012
After doing some research on this subject