如何修复Rails中的授权不足?

时间:2015-11-19 18:25:37

标签: ruby-on-rails security

我在https://medium.com/@danamulder/tutorial-create-a-simple-messaging-system-on-rails-d9b94b0fbca1#.xjhgikji4使用Dana Mulder的教程开发了一个简单的消息传递应用程序 然而,在能够获得工作系统后,我意识到任何用户都可以通过玩这个网址来查看其他用户消息。

例如,用户可以迭代此网址http://localhost:3000/conversations/3/messages中的数字,并查看他们不在其中的所有其他消息。我试图在没有运气的情况下添加一些保护。有人知道如何修复此应用程序的授权不足问题吗?谢谢!

这是我的conversations_controller.rb

class ConversationsController < ApplicationController
  before_action :confirm_logged_in
  layout 'authenticated'

  def index
    @users = User.all
    @conversations = Conversation.all
  end

  def create
    if Conversation.between(params[:sender_id],params[:recipient_id]).present?
      @conversation = Conversation.between(params[:sender_id], params[:recipient_id]).first
    else
      @conversation = Conversation.create!(conversation_params)
    end
    redirect_to conversation_messages_path(@conversation)
  end

  private
  def conversation_params
    params.permit(:sender_id, :recipient_id)
  end
end

这是messages_controller.rb

class MessagesController < ApplicationController

  layout 'authenticated'
  before_action do
    @conversation = Conversation.find(params[:conversation_id])
  end

  def index
    @messages = @conversation.messages
    if @messages.length > 10
      @over_ten = true
      @messages = @messages[-10..-1]
    end
    if params[:m]
      @over_ten = false
      @messages = @conversation.messages
    end
    if @messages.last
      if @messages.last.user_id != current_user.id
        @messages.last.read = true;
      end
    end

    @message = @conversation.messages.new
  end

  def new
    @message = @conversation.messages.new
  end

  def create
    @message = @conversation.messages.new(message_params)
    if @message.save
      redirect_to conversation_messages_path(@conversation)
    end
  end

  private
  def message_params
    params.require(:message).permit(:body, :user_id)
  end
end

1 个答案:

答案 0 :(得分:1)

我假设在您的模型设计中,用户有很多转换current_user是对象代表当前登录的用户。您可以通过此查询将他可以查看的对话限制为仅属于他的对话:

@conversation = Conversation.where("(sender_id = ? OR recipient_id =?) AND id = ?", current_user.id, current_user.id, params[:conversation_id]).first

而不是@conversation = Conversation.find(params[:conversation_id]),这会将Conversation传递给参数conversation_id