FIX: Get correct selectable avatar from URL (#10339)

FIX: Get correct selectable avatar from URL (#10339)

The URL for selectable avatars was ‘cooked’ which means that the find_by method was not enough.

diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb
index a3b779e..f0ca878 100644
--- a/app/controllers/users_controller.rb
+++ b/app/controllers/users_controller.rb
@@ -1134,11 +1134,11 @@ class UsersController < ApplicationController
       return render json: failed_json, status: 422
     end
 
-    unless SiteSetting.selectable_avatars[url]
+    unless upload = Upload.get_from_url(url)
       return render json: failed_json, status: 422
     end
 
-    unless upload = Upload.find_by(url: url)
+    unless SiteSetting.selectable_avatars[upload.url]
       return render json: failed_json, status: 422
     end
 
diff --git a/app/models/user.rb b/app/models/user.rb
index 370ad17..91f2070 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -1152,7 +1152,7 @@ class User < ActiveRecord::Base
     if SiteSetting.selectable_avatars_enabled? && SiteSetting.selectable_avatars.present?
       urls = SiteSetting.selectable_avatars.split("\n")
       if urls.present?
-        if upload = Upload.find_by(url: urls.sample)
+        if upload = Upload.get_from_url(urls.sample)
           update_column(:uploaded_avatar_id, upload.id)
           UserAvatar.create!(user_id: id, custom_upload_id: upload.id)
         end
diff --git a/spec/requests/users_controller_spec.rb b/spec/requests/users_controller_spec.rb
index 77c8b40..0e92d3f 100644
--- a/spec/requests/users_controller_spec.rb
+++ b/spec/requests/users_controller_spec.rb
@@ -2377,6 +2377,17 @@ describe UsersController do
             expect(user.reload.uploaded_avatar_id).to eq(avatar1.id)
             expect(user.user_avatar.reload.custom_upload_id).to eq(avatar1.id)
           end
+
+          it 'can succesfully select an avatar using a cooked URL' do
+            events = DiscourseEvent.track_events do
+              put "/u/#{user.username}/preferences/avatar/select.json", params: { url: UrlHelper.cook_url(avatar1.url) }
+            end
+
+            expect(events.map { |event| event[:event_name] }).to include(:user_updated)
+            expect(response.status).to eq(200)
+            expect(user.reload.uploaded_avatar_id).to eq(avatar1.id)
+            expect(user.user_avatar.reload.custom_upload_id).to eq(avatar1.id)
+          end
         end
       end
     end

GitHub sha: 2682da81

This commit appears in #10339 which was approved by ZogStriP and ZogStriP. It was merged by nbianca.