Question

I'm working on an e-commerce application. When a user logs into my app, I want to make a check to my external subscription handler and make sure that their subscription is still active and not expired/failed/whatever.

I successfully figured out how to use a Warden callback in my initializers/devise.rb to perform a check on the model after login. However, if there is a problem, I want to log them out again and redirect to a certain page that tells them what to do next.

Here is what I have. I know I can't use redirect_to from the callback. Given that, what is the best way to do what I'm trying to do?

Warden::Manager.after_authentication do |user, auth, opts|
  begin
    user.check_active_subscription # this works, and will raise one of several exceptions if something is goofy
  rescue
    redirect_to "/account/expired" # obviously this won't work, but see what I'm trying to do?
  end
end
Was it helpful?

Solution

Just let the callback raise the exception and rescue from it in your controller. E.g.:

Warden::Manager.after_authentication do |user, auth, opts|
  user.check_active_subscription
end

class SessionsController < ApplicationController
  def create
    # Authenticate
  rescue SubscriptionExpiredException
    # Logout
    redirect_to "/account/expired"
  end
end

You could also use rescue_from in your ApplicationController like this:

class ApplicationController
  rescue_from SubscriptionExpiredException, :with => :deny_access

  def deny_access
    redirect_to "/account/expired"
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top