FIX: Fix `user_id` validation (#312)

Validation of `user_id` parameter will throw a 500 error because
`User.find_by_username_or_email` does not throw
`ActiveRecord::RecordNotFound`, but silently returns `nil`.
This results in a `NoMethodError` in `object.id` on the next line
This commit is contained in:
锦心 2024-08-21 12:03:29 +08:00 committed by GitHub
parent 760667d744
commit 6bf3ac7426
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 20 additions and 6 deletions

View File

@ -205,12 +205,9 @@ module ::DiscourseDataExplorer
invalid_format string, "The specified #{klass_name} was not found" invalid_format string, "The specified #{klass_name} was not found"
end end
elsif type == :user_id elsif type == :user_id
begin object = User.find_by_username_or_email(string)
object = User.find_by_username_or_email(string) invalid_format string, "The user named #{string} was not found" if object.blank?
value = object.id value = object.id
rescue ActiveRecord::RecordNotFound
invalid_format string, "The user named #{string} was not found"
end
elsif type == :post_id elsif type == :post_id
if string =~ %r{/t/[^/]+/(\d+)(\?u=.*)?$} if string =~ %r{/t/[^/]+/(\d+)(\?u=.*)?$}
object = Post.with_deleted.find_by(topic_id: $1, post_number: 1) object = Post.with_deleted.find_by(topic_id: $1, post_number: 1)

View File

@ -76,6 +76,23 @@ RSpec.describe DiscourseDataExplorer::Parameter do
end end
end end
end end
describe "user_id type" do
fab!(:user)
it "raises an error if no such user exists" do
expect {
param("user_id", :user_id, nil, false).cast_to_ruby("user_not_exist")
}.to raise_error(::DiscourseDataExplorer::ValidationError)
expect {
param("user_id", :user_id, nil, false).cast_to_ruby("user_not_exist@fake.email")
}.to raise_error(::DiscourseDataExplorer::ValidationError)
end
it "returns the user id if the user exists" do
expect(param("user_id", :user_id, nil, false).cast_to_ruby(user.username)).to eq(user.id)
expect(param("user_id", :user_id, nil, false).cast_to_ruby(user.email)).to eq(user.id)
end
end
end end
describe ".create_from_sql" do describe ".create_from_sql" do