FIX: use discourse route_for function to check url route it takes care if there is a relative url root

FIX: use discourse route_for function to check url route it takes care if there is a relative url root

diff --git a/app/controllers/user_badges_controller.rb b/app/controllers/user_badges_controller.rb
index cb67ee7..276f990 100644
--- a/app/controllers/user_badges_controller.rb
+++ b/app/controllers/user_badges_controller.rb
@@ -61,13 +61,7 @@ class UserBadgesController < ApplicationController
         return render json: failed_json.merge(message: I18n.t('invalid_grant_badge_reason_link')), status: 400
       end
 
-      path = begin
-        URI.parse(params[:reason]).path
-      rescue URI::Error
-      end
-
-      route = Rails.application.routes.recognize_path(path) if path
-      if route
+      if route = Discourse.route_for(params[:reason])
         topic_id = route[:topic_id].to_i
         post_number = route[:post_number] || 1
 
diff --git a/spec/requests/user_badges_controller_spec.rb b/spec/requests/user_badges_controller_spec.rb
index 92da1a6..3ee7927 100644
--- a/spec/requests/user_badges_controller_spec.rb
+++ b/spec/requests/user_badges_controller_spec.rb
@@ -188,6 +188,38 @@ describe UserBadgesController do
 
       expect(response.status).to eq(200)
     end
+
+    describe 'with relative_url_root' do
+      before do
+        @orig_relative_url_root = ActionController::Base.config.relative_url_root
+        ActionController::Base.config.relative_url_root = "/discuss"
+      end
+
+      after do
+        ActionController::Base.config.relative_url_root = @orig_relative_url_root
+      end
+
+      it 'grants badge when valid post/topic link is given in reason' do
+        admin = Fabricate(:admin)
+        post = create_post
+
+        sign_in(admin)
+
+        post "/user_badges.json", params: {
+          badge_id: badge.id,
+          username: user.username,
+          reason: "#{Discourse.base_url}#{post.url}"
+        }
+
+        expect(response.status).to eq(200)
+
+        expect(UserBadge.exists?(
+          badge_id: badge.id,
+          post_id: post.id,
+          granted_by: admin.id)
+        ).to eq(true)
+      end
+    end
   end
 
   context 'destroy' do

GitHub sha: 99856478

1 Like