Reputation: 346
I have a controller that I am calling
before_action :authenticate_user!
at the beginning of. However, I also have a model, admin, that should access this controller, i.e.
before_action :authenticate_admin!
How can I make it so either one can access the controller?
Upvotes: 1
Views: 491
Reputation: 14082
Devise offers you helper methods user_signed_in?
and admin_signed_in?
for the User
model and Admin
model, respectively.
You can write custom filter in ApplicationController
, and apply the filter in the concrete controller on demand.
class ApplicationController < ActionController::Base
...
class AuthorizationException < StandardError
end
rescue_from AuthorizationException do
render text: "Access Denied", status: :unauthorized
end
protected
def authenticate_user_or_admin!
unless user_signed_in? or admin_signed_in?
raise AuthorizationException.new
end
end
end
You can use the filter authenticate_user_or_admin!
in your controller now.
Upvotes: 4