Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 + devise - How to get devise to respond with JSON

My environment is Rails 3.0.1 with Devise 1.1. I am developing a mobile web application, mostly with javascript, and would like to keep as much of the communication JSON-based as possible.

Is there a way for devise to respond with a success/fail message with JSON, rather than having to follow a 302 redirect and parse the HTML?

Looked at using this.

...but don't have it working.

like image 595
coreyt Avatar asked Dec 23 '10 20:12

coreyt


1 Answers

You can redefine the sign_in_and_redirect and sign_out_and_redirect devise helpers, to render json instead of redirecting the user.

I couldn't redefine them in an initializer, so the closest solution I found is adding this to application_controller.rb :

private

# Override the default devise signin/signout process
def sign_in_and_redirect(resource_or_scope, resource=nil)
  scope      = Devise::Mapping.find_scope!(resource_or_scope)
  resource ||= resource_or_scope
  sign_in(scope, resource) unless warden.user(scope) == resource
  # redirect_to stored_location_for(scope) || after_sign_in_path_for(resource)
  render :json => {:status => :signed_in}
end


def sign_out_and_redirect(resource_or_scope)
  scope = Devise::Mapping.find_scope!(resource_or_scope)
  if Devise.sign_out_all_scopes
    sign_out_all_scopes
  else
    sign_out(scope)
  end
  #redirect_to after_sign_out_path_for(scope)
  render :json => {:status => :signed_out}
end

If anyone has a cleaner solution, I'm also interested

like image 130
MrRuru Avatar answered Nov 16 '22 16:11

MrRuru