Skip to content

Commit

Permalink
fix: handle nameless controllers
Browse files Browse the repository at this point in the history
Fixes #277
  • Loading branch information
palkan committed Nov 21, 2024
1 parent 6a5c7b9 commit 29048c0
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## master

- Fix implicit authorization target in anonymous controllers. ([@palkan][])

- Improve default `ActionPolicy::Unauthorized` error message. ([@Spone][])

Before: `Not Authorized` / After: `Not authorized: UserPolicy#create? returns false`
Expand Down
2 changes: 1 addition & 1 deletion lib/action_policy/rails/controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def authorize!(record = :__undef__, to: nil, **options)
# Tries to infer the resource class from controller name
# (i.e. `controller_name.classify.safe_constantize`).
def implicit_authorization_target
controller_name.classify.safe_constantize
controller_name&.classify&.safe_constantize
end

def verify_authorized
Expand Down
33 changes: 33 additions & 0 deletions test/action_policy/rails/controllers_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -274,3 +274,36 @@ def test_index_authorized
assert_equal "OK", response.body
end
end

class TestAnonymousControllerIntegration < ActionController::TestCase
class UserPolicy < ::UserPolicy
authorize :user, allow_nil: true

def index? = user.present?
end

def test_nameless_controllers_work
controller_class = Class.new(ActionController::Base) do
authorize :user, through: :current_user

def index
authorize! with: UserPolicy
head :ok
end

def current_user
return unless params[:user]
@current_user ||= User.new(params[:user])
end
end

env = Rack::MockRequest.env_for("http://localhost:3000")

assert_raises(ActionPolicy::Unauthorized) do
controller_class.action(:index).call(env)
end

env = Rack::MockRequest.env_for("http://localhost:3000/?user=guest")
controller_class.action(:index).call(env)
end
end

0 comments on commit 29048c0

Please sign in to comment.