I've added a realtime chat to my rails application using only vanilla javascript. I've included it below. I'm just wondering, are there any security issues just looking at the code I've provided? I'm just not sure whether there's any issues with AJAX injections or any unknown unknowns I need to worry about. I didn't add ActionCable mainly because I don't need all of its functionality. Thanks for your help! :)
A chat has many private messages between 2 users. Users have many messages. I've added policies using pundit so only authorized users can access chats. And I'm using devise so only logged in users can access chats. Every model uses UUID.
chats/show.html.erb
<% if @messages %>
<div id="messages">
<%= render @messages %>
</div>
<% end %>
<%= form_with(model: [@chat, Message.new], local: false, html: { id: "message-form" }) do |form| %>
<div class="field">
<%= form.text_area :content, placeholder: "Send a message" %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
messages/_message.html.erb
<%= message.user.name %>
<%= message.content %>
messages/create.js.erb
var messages = document.querySelector("#messages");
messages.insertAdjacentHTML("beforeend", "<%= j render(@message) %>");
document.getElementById("message-form").reset();
controllers/messages_controller.rb
def create
@chat = Chat.find(params[:chat_id])
@message = @chat.messages.build(message_params)
@message.user = current_user
authorize @message
respond_to do |format|
if @message.save
format.html { redirect_to @chat, notice: 'Message was successfully created.' }
format.js
format.json { render :show, status: :created, location: @chat }
else
format.html { redirect_to @chat, alert: 'Message not created.' }
format.json { render json: @message.errors, status: :unprocessable_entity }
end
end
end
controllers/chats_controller.rb
def show
@listing = Listing.find(params[:listing_id])
@chats = @listing.chats
@chat = Chat.find(params[:id])
if @chat.messages
@messages = @chat.messages
end
end
question from:
https://stackoverflow.com/questions/65909033/rails-realtime-chat-is-it-secure-to-implement-it-with-just-plain-javascript 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…