Combining Accounting for Helper Authentication with `OR` Operators in Rails
I am currently using Devise gem for user authentication.
There are helper methods that basically allow you to authenticate a user before they can access a specific route / view in your controller.
those. if you need user_type_one
to log in to access /home
:
class FooController < ApplicationController
before_action :authenticate_user_type_one!
def home
#stuff
end
end
How could you make it so that the specified types of users can access the page.
So, if I had three types of users user_type_one
, user_type_two
and user_type_three
, and I want to user_type_one
, and user_type_two
appealed to /home
, I want to do something like this.
before_action :authenticate_user_type_one! || :authenticate_user_type_two!
source to share
Devise handles a lot of defaults for you and does a great job of it, but when you need to start customizing the behavior it can get very prickly. In particular, if you are fairly new to Rails development, I often find it best to just write your own custom method that manually checks what you need to check. Then, as you become familiar with Devise, you can gradually learn about the built-in tools that you might have, or the internal hooks that you can hack to get more elegant behavior.
Specifically, as a starting point, I would try writing a custom before_action:
class FooController < ApplicationController
before_action :authenticate_apple_or_orange_or_pear!
def home
stuff
end
protected
def authenticate_apple_or_orange_or_pear!
unless apple_signed_in? or orange_signed_in? or pear_signed_in?
redirect_to go_away_and_never_return_path, alert: "You're not wanted here."
end
end
end
If I understand your need correctly, this should do what you ask. It checks if any of the required account types are signed, and if not, it redirects the visitor to a different path, blocking access to that controller.
If this is what you need for multiple controllers, you can also move that method definition into application_controller.rb
and it will become available to all controllers that inherit from ApplicationController
(which usually means everything).
source to share