Add a username slug to the user URL

This way it won't be possible to browse all user URLs by just going to
/users/1, /users/2, /users/3, ... and collect usernames, which might not
be desirable in some cases.

Note we could use the username as a URL parameter and just find the user
with `@user = User.find_by!(id: id, username: username)`, but since
usernames might contain strange characters, this might lead to
strange/ugly URLs.

Finally, note we're using `username.to_s` in order to cover the case
where the username is `nil` (as is the case with erased users).
This commit is contained in:
Javi Martín
2023-11-28 17:49:02 +01:00
parent 2db807baa7
commit 77c043b68a
5 changed files with 123 additions and 0 deletions

View File

@@ -1,6 +1,7 @@
class DirectMessagesController < ApplicationController
before_action :authenticate_user!
load_and_authorize_resource :user, instance_name: :receiver
before_action :check_slug
load_resource through: :receiver, through_association: :direct_messages_received
authorize_resource except: :new
@@ -28,6 +29,12 @@ class DirectMessagesController < ApplicationController
private
def check_slug
slug = params[:user_id].split("-", 2)[1]
raise ActiveRecord::RecordNotFound unless @receiver.slug == slug.to_s
end
def direct_message_params
params.require(:direct_message).permit(allowed_params)
end