make URI.parse part of the validation for the sharing URL

the regexp alone and web browsers allows URLs to contain non-ASCII
characters, which `URI.parse` does not like -- resulting in the inbox
page to suddenly break.

also changed the `redirect_to` in the controller to a `render :edit` so
that validation errors are shown properly
This commit is contained in:
Georg Gadinger 2023-02-10 20:48:15 +01:00
parent 46bf8ec841
commit 606629577a
5 changed files with 31 additions and 4 deletions

View File

@ -10,10 +10,11 @@ class Settings::SharingController < ApplicationController
:sharing_autoclose,
:sharing_custom_url)
if current_user.update(user_attributes)
flash[:success] = t(".success")
flash.now[:success] = t(".success")
else
flash[:error] = t(".error")
flash.now[:error] = t(".error")
end
redirect_to settings_sharing_path
render :edit
end
end

View File

@ -61,7 +61,7 @@ class User < ApplicationRecord # rubocop:disable Metrics/ClassLength
end
validates :email, fake_email: true, typoed_email: true
validates :sharing_custom_url, format: URI::DEFAULT_PARSER.make_regexp(%w[http https]), allow_blank: true
validates :sharing_custom_url, allow_blank: true, valid_url: true
validates :screen_name,
presence: true,
format: { with: SCREEN_NAME_REGEX, message: I18n.t("activerecord.validation.user.screen_name.format") },

View File

@ -0,0 +1,21 @@
# frozen_string_literal: true
class ValidUrlValidator < ActiveModel::EachValidator
URI_REGEXP = URI::DEFAULT_PARSER.make_regexp(%w[http https]).freeze
def validate_each(record, attribute, value)
return if valid?(value)
record.errors.add(attribute, :invalid_url)
end
def valid?(value)
return false unless URI_REGEXP.match?(value)
URI.parse(value) # raises URI::InvalidURIError
true
rescue URI::InvalidURIError
false
end
end

View File

@ -104,6 +104,9 @@ en:
user:
screen_name:
format: "contains invalid characters"
errors:
messages:
invalid_url: "does not look like a valid URL"
helpers:
submit:
user:

View File

@ -63,6 +63,8 @@ RSpec.describe User, type: :model do
include_examples "valid url", "http://insecurebutvalid.business/"
include_examples "invalid url", "ftp://fileprotocols.cool/"
include_examples "invalid url", "notevenanurl"
include_examples "invalid url", %(https://richtig <strong>oarger</strong> shice) # passes the regexp, but trips up URI.parse
include_examples "invalid url", %(https://österreich.gv.at) # needs to be ASCII
end
describe "email validation" do