email_domain_blocks_controller.rb 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # frozen_string_literal: true
  2. module Admin
  3. class EmailDomainBlocksController < BaseController
  4. before_action :set_email_domain_block, only: [:show, :destroy]
  5. def index
  6. authorize :email_domain_block, :index?
  7. @email_domain_blocks = EmailDomainBlock.where(parent_id: nil).includes(:children).order(id: :desc).page(params[:page])
  8. @form = Form::EmailDomainBlockBatch.new
  9. end
  10. def batch
  11. authorize :email_domain_block, :index?
  12. @form = Form::EmailDomainBlockBatch.new(form_email_domain_block_batch_params.merge(current_account: current_account, action: action_from_button))
  13. @form.save
  14. rescue ActionController::ParameterMissing
  15. flash[:alert] = I18n.t('admin.email_domain_blocks.no_email_domain_block_selected')
  16. rescue Mastodon::NotPermittedError
  17. flash[:alert] = I18n.t('admin.email_domain_blocks.not_permitted')
  18. ensure
  19. redirect_to admin_email_domain_blocks_path
  20. end
  21. def new
  22. authorize :email_domain_block, :create?
  23. @email_domain_block = EmailDomainBlock.new(domain: params[:_domain])
  24. end
  25. def create
  26. authorize :email_domain_block, :create?
  27. @email_domain_block = EmailDomainBlock.new(resource_params)
  28. if action_from_button == 'save'
  29. EmailDomainBlock.transaction do
  30. @email_domain_block.save!
  31. log_action :create, @email_domain_block
  32. (@email_domain_block.other_domains || []).uniq.each do |domain|
  33. next if EmailDomainBlock.where(domain: domain).exists?
  34. other_email_domain_block = EmailDomainBlock.create!(domain: domain, parent: @email_domain_block)
  35. log_action :create, other_email_domain_block
  36. end
  37. end
  38. redirect_to admin_email_domain_blocks_path, notice: I18n.t('admin.email_domain_blocks.created_msg')
  39. else
  40. set_resolved_records
  41. render :new
  42. end
  43. rescue ActiveRecord::RecordInvalid
  44. set_resolved_records
  45. render :new
  46. end
  47. private
  48. def set_email_domain_block
  49. @email_domain_block = EmailDomainBlock.find(params[:id])
  50. end
  51. def set_resolved_records
  52. Resolv::DNS.open do |dns|
  53. dns.timeouts = 5
  54. @resolved_records = dns.getresources(@email_domain_block.domain, Resolv::DNS::Resource::IN::MX).to_a
  55. end
  56. end
  57. def resource_params
  58. params.require(:email_domain_block).permit(:domain, other_domains: [])
  59. end
  60. def form_email_domain_block_batch_params
  61. params.require(:form_email_domain_block_batch).permit(email_domain_block_ids: [])
  62. end
  63. def action_from_button
  64. if params[:delete]
  65. 'delete'
  66. elsif params[:save]
  67. 'save'
  68. end
  69. end
  70. end
  71. end