Ajax login and detecting when an account's locked

125 views
Skip to first unread message

Nick Hoffman

unread,
Sep 26, 2011, 7:03:42 PM9/26/11
to plataforma...@googlegroups.com
Hi guys. How can we determine that authentication failed because the user's account is locked?

I've created a custom failure app and session controller, and configured Warden to use my custom failure app. Logging-in via Ajax works beautifully. However, if the user's account is (or becomes) locked, how can I detect that, and send a different JSON response?

Here's the custom failure app and custom session controller:

Thanks for your help with this. I really appreciate it.
Nick

Nick Hoffman

unread,
Sep 27, 2011, 8:02:55 AM9/27/11
to plataforma...@googlegroups.com
So I dug through Devise's and Warden's code, followed the output from using "caller" at the beginning of my custom failure app, and figured it out.

Devise asks the Lockable strategy if the resource is valid for authentication (via Lockable#valid_for_authentication?). Lockable returns :locked if the resource is locked. Devise stores that result in Warden. To access that result, you just need to check the value of warden.message .

Here's how I did it:

class SessionFailure < Devise::FailureApp
  def respond
    return super unless request.xhr?

    message = I18n.t 'devise.failure.invalid'
    cause   = 'invalid'

    if warden.message == :locked
      message = I18n.t 'devise.failure.locked'
      cause   = 'account_locked'
    end

    self.status         = 200
    self.content_type   = 'json'
    self.response_body  = {
      :status => 'fail',
      :data   => { :message  => message, :cause => cause },
    }.to_json
  end
end

Nick Hoffman

unread,
May 10, 2012, 2:57:10 PM5/10/12
to plataforma...@googlegroups.com
On Thu, May 10, 2012 at 1:00 AM, webguy5 <master...@gmail.com> wrote:
> this is very nice. Great job! What does you javascript look like to
> send the data from the sessions controller to the form?


Hi Mike. My SessionsController responds with JSON, not JavaScript:

  def create
    resource = warden.authenticate :scope => resource_name

    if resource.is_a? User
      sign_in resource

      return render :json => {
        :status => 'success',
        :data   => {:message => I18n.t('devise.sessions.signed_in')},
      }
    end


Cheers,
Nick
Message has been deleted

webguy5

unread,
May 10, 2012, 10:58:43 PM5/10/12
to plataforma...@googlegroups.com
Thanks. When the user account is locked warden returns the user is invalid and triggers the failed_attempts strategy I have on the user. How do I call on the user object in the custom failure app to avoid it doing this.
Reply all
Reply to author
Forward
0 new messages