summaryrefslogtreecommitdiff
path: root/app/controllers/messages_controller.rb
blob: 480a6718a358684ad21cb0aae45682d5bc19aae3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
class MessagesController < ApplicationController

  before_filter :check_permission, only: :destroy

  def index
    if current_user
      @messages = Message.where(user_target: current_user).page(params[:page])
    else
      flash[:alert] = "Please log in to see your private messages."
      redirect_to blogposts_path
    end
  end

  def new
    if current_user
      @message = Message.new
    else
      flash[:alert] = "Please log in to send a private message."
      redirect_to blogposts_path
    end
  end

  def create
    unless message_params[:user_target_id]
      flash[:alert] = "Please enter a valid IGN before sending."
      redirect_to new_message_path
      return
    end
    if message_params[:subject].blank?
      flash[:alert] = "Please write a subject before sending."
      redirect_to new_message_path
      return
    elsif message_params[:text].blank?
      flash[:alert] = "Please write a message before sending."
      redirect_to new_message_path
      return
    end
    @message = Message.new(message_params)
    @message.user_target = User.find(@message.user_target_id)
    if @message.save
      @message.send_new_message_mail
      flash[:notice] = "Message sent!"
      redirect_to messages_path
    else
      flash[:alert] = "Something went wrong while creating your message."
      render action: "new"
    end
  end

  def destroy
    if @message.user_target.is?(current_user)
      if @message.destroy
        flash[:notice] = "Message deleted!"
      else
        flash[:alert] = "There was a problem while deleting this message."
      end
    else
      flash[:alert] = "You are not allowed to delete this message."
    end
    redirect_to messages_path
  end

  def destroy_all
    Message.destroy_all(user_target_id: current_user.id)
    if Message.where(user_target_id: current_user.id).empty?
      flash[:notice] = "Your messages have been deleted!"
    else
      flash[:alert] = "There was a problem while deleting your messages."
    end
    redirect_to messages_path
  end

  def message_params(add = [])
    params[:message][:user_target_id] = User.find_by(ign: params[:message][:user_target].strip).try(:id)
    params[:message][:user_sender_id] = User.find_by(ign: params[:message][:user_sender]).id

    params.require(:message).permit([:subject, :text, :user_target_id, :user_sender_id])
  end

  private

  def check_permission
    @message = Message.find(params[:id])
    unless @message.user_target == current_user
      flash[:alert] = "You are not allowed to view this message"
      redirect_to home_statics_path
    end
  end
end