AJAX Json login implementation example?

Skip to first unread message


Jul 7, 2010, 8:04:01 AM7/7/10
to Devise
Anyone has a good implementation reference on this? I just want to
enable sessions controller to take json, so minimal customization is
preferred instead of overriding the whole thing, alternatively if I
can just in place override with a sessionscontroller instead of
creating a useless scope like users/sessions (I only have one and only
one login scope in the system which is user) would be great.

Nick Chistyakov

Jul 7, 2010, 10:55:45 PM7/7/10
to plataforma...@googlegroups.com
Hi William,

Some time ago asked the same question.
Got no responses so not sure that I implemented in a best canonical way.

I just reimplemented the users session controller like this:

class Users::SessionsController < Devise::SessionsController                
  # prepend_before_filter :require_no_authentication, :only => [:failure]          

  layout "login"                        

  # Have to reimplement :recall => "failure"
  # for warden to redirect to some action that will return what I want
  def create    
    logger.debug "Trying to create a new session..."
    resource = warden.authenticate!(:scope => resource_name, :recall => "failure")
    # set_flash_message :notice, :signed_in 
    sign_in_and_redirect(resource_name, resource)      
  # Mostly a copy of original source code.
  # Needed only call render :json => ... in the end
  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
    render :json => { :success => true, :redirect  => stored_location_for(scope) || after_sign_in_path_for(resource) } 
  def failure
    render :json => {:success => false, :errors => {:reason => "Login failed. Try again"}} 

And certainly added a string in routes.rb

devise_for :users,   :controllers => { :sessions => "users/sessions" } 

Hope that it helped,
Reply all
Reply to author
0 new messages