简体   繁体   中英

How to use before_action in Rails?

I have some methods in my controller. First of all I write

before_action :require_user
before_action :require_rights, only: [:show, :my_method]

Can I put methods dynamically ? eg

before_action :require_rights, only: current_user.allowed_actions

I think to save method names somewhere and configure each user to groups with access rights. Or there are better solutions in existing gems ?

You can try this:

#controller
before_action :require_rights

def require_rights
  unless current_user.allowed_actions
    raise 'not authorized'
  end
end

Make your condition in your method can fix your problem.

You can do it in such a way.

before_action :require_user
before_action :require_rights


def require_rights
  fail 'Not allowed' unless current_user.allowed_actions.include?(action_name) # Guard to check if user allowed to do certain action
end

Also I would recommend you to create a special class which will handle this logic for you. Example:

class RightsPolicyService
  attr_reader :user

  def initialize(user)
    @user = user
  end

  def allowed?(controller_name, action_name)
    # Define here your custom logic for checking if user is allowed
    user.allowed_controllers.include?(controller_name) &&
      user.allowed_actions.include?(action_name)
  end
end

# And in the controller
def require_rights
  fail 'Not allowed' unless RightsPolicyService.new(current_user).allowed?(controller_name, action_name)
end

Note: failing is just made an example, you should generate a response in this case or redirect somewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM