Secretprtay

Message

Feb 2nd, 2022 (edited)
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rails 2.08 KB | None | 0 0
  1. class MessagesController < ApplicationController
  2.   before_action :authenticate_role
  3.   before_action :set_message, except: %i(index create)
  4.   before_action :set_sender, except: :index
  5.   before_action :autorize_action, only: %i(update destroy)
  6.  
  7.   def index
  8.     messages = Message.where(status: params[:status]).recent if params[:status]&.in?(Message::statuses.keys)
  9.     messages ||= Message.recent
  10.  
  11.     render json: messages
  12.   end
  13.  
  14.   def create
  15.     # return unless params[:receiverable].any? && params[:receiverable].is_a?(Array)
  16.     return unless params[:receiverable].any? && params[:receiverable].is_a?(Array) && !params[:receiverable].any?(Hash)
  17.  
  18.     create_errors = []
  19.     params[:receiverable].each do |receiver|
  20.       # message = @sender.sended_messages.build(message_params.merge({receiverable: receiver}))
  21.       message = @sender.sended_messages.build(message_params)
  22.       message.receiverable = receiver
  23.  
  24.       unless message.save
  25.         create_errors << { message: "An error occurred: #{message.errors.full_messages.join('; ')}" }
  26.       end
  27.     end
  28.  
  29.     render json: { errors: create_errors }, status: 422 if create_errors.any?
  30.   end
  31.  
  32.  
  33.   def update
  34.     if @message.update(message_params)
  35.       render json: @message, status: :ok
  36.     else
  37.       render json: { message: "An error occurred: #{@message.errors.full_messages.join('; ')}" }, status: 422
  38.     end
  39.   end
  40.  
  41.   def destroy
  42.     @message.destroy
  43.     render json: { status: :ok }
  44.   end
  45.  
  46.   private
  47.  
  48.   def authenticate_role
  49.     current_admin! || current_customer! || current_respondent!
  50.   end
  51.  
  52.   def set_message
  53.     @message = Message.find_by_id(params[:id])
  54.   end
  55.  
  56.   def set_sender
  57.     @sender = current_admin || current_customer || current_respondent
  58.   end
  59.  
  60.   def message_params
  61.     params.require(:message).permit(:receiverable, :status, :subject, :text)
  62.   end
  63.  
  64.   def autorize_action
  65.     unless current_customer == @message.senderable || current_respondent == @message.senderable || current_admin # admin_signed_in?
  66.       return render json: { error: 'An unauthorized!' }, status: 401
  67.     end
  68.   end
  69. end
  70.  
Add Comment
Please, Sign In to add comment