Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

Rails Realtime Chat: Is it secure to implement it with just plain javascript?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...