1

I am working on a simple authorization in a Rails 4 app. Each user has a role; then I set up pages they can access, for example:

AUTH_MODERATOR_DEFINITIONS = {"articles"     => "index",
                              "readers"  => "index"}

Then, in a controller action, I will call:

def index
  check_permissions(current_admin)
  ...
end

And in the ApplicationController:

  def check_permissions(current_admin)
    if current_admin.role == 1 # for moderators
      # find a pair key-vale AUTH_DISPATCHER_DEFINITIONS that matches `params[:controller]` and `params[:action]
    else
      redirect_to root_path, :alert => "No permission"
    end
  end

But how to search a hash according to key AND value?

Thank you in advance.

1 Answer 1

1

You can do something like this:

key = params[:controller]
value= params[:action]
p is_permitted = (AUTH_MODERATOR_DEFINITIONS[key] == value)

However, I think you may revise values in your hash to be array at some point, as it is unlikely that a controller will have only one action, and hence, user can have access to multiple actions. For example:

AUTH_MODERATOR_DEFINITIONS = {
    "articles" => "index",
    "readers"  => "index",
    "commenters"  => ["index","new","update"] # Added by me to show possible use case
}

Considering the above scenario, I think you can do something like this. This will work in both scenarios (your example, and my extension to that example)

key = params[:controller]
value= params[:action]

p is_permitted = [AUTH_MODERATOR_DEFINITIONS[key]].flatten.include?(value)
Sign up to request clarification or add additional context in comments.

3 Comments

This is best, as it is o(1).
Your first solution is what I liked most.
Hi Wand, thank you for the answer. I am testing it, but the output is still false (p is_permitted), no matter if I am on an approved page or not. Do I overlook something or what I do wrong?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.