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
有帮助吗?

解决方案

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top