I want to build a website that respond both to normal browser request, and mobile request using JSON from an Android app.
I use devise for authentication. Web users will login normally, but for mobile use, I want them to send login/password only once, and then work with the authentication token.
To do that, I overrided the devise session controller:
class SessionsController < Devise::SessionsController
skip_before_filter :verify_authenticity_token
respond_to :html, :json
def create
resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
set_flash_message(:notice, :signed_in) if is_navigational_format?
sign_in(resource_name, resource)
obj1 = MyModel.find(21)
obj2 = MyModel.find(22)
respond_to do |format|
format.html do
render :json => obj1
end
format.json do
render :json => obj2
end
end
end
def destroy
super
end
end
This is actually a dummy code, just to know which case gets executed in the respond_to.
If a create a post request, passing login details, like this:
curl -v -X POST -d '{"user" : { "email" : "myemail@gmail.com", "password" : "123456"}}' -H "Content-Type:application/json" http://localhost:3000/users/sign_in
The response is the JSON representation of obj1. In other words, in the respond_to it always get executed the format.html entry.
What is wrong with this code? Why I get that response if I specify in the header that this is a JSON formatted request?
I made it work adding: -H “Accept:application/json”