I have an authorization module that I built to authorize user actions. Everything is working great, except now I want to skip the action if the user requesting the page is the current user. The resource is nested below user
so passes a :user_id
as part of the params.
From what I've been able to find out, the simplest way to do this is to use a lambda, but it doesn't appear that I have access to the passed params from the before filter.
This is my controller
class Certifications::FitnessController < ApplicationController
prepend_before_action :authenticate_user!
before_action :authorize, unless: -> { params[:user_id] == current_user.id }
end
The problem is that the :authorize
before_action is never called so all actions are allowed (I assume because the unless statement is always evaluating to true), but I can't examine what is going on because if I stop execution there, no params seem to be there (which I would think should make it always evaluate to false, not true).
If anyone can tell me either what I'm doing wrong or a better way to implement, I would really appreciate it.
EDIT: The code above actually works if you convert the params to an integer to match the current_user.id
before_action :authorize, unless: -> { params[:user_id].to_i == current_user.id }
before_action do |controller|
unless params[:user_id].to_i == current_user.id
controller.authorize
end
end
Alternatively you can do so like:-
before_action :authorize
def authorize
unless params[:user_id].to_i == current_user.id
#do your stuff..
end
end
2nd Alternative
before_action :authorize, unless: -> { params[:user_id].to_i == current_user.id }
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.