Skip to content

Instantly share code, notes, and snippets.

@staycreativedesign
Created May 13, 2020 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save staycreativedesign/da07029c394816e68a2a67dbe086dc6c to your computer and use it in GitHub Desktop.
Save staycreativedesign/da07029c394816e68a2a67dbe086dc6c to your computer and use it in GitHub Desktop.
class NotificationsMailer < ApplicationMailer
def notify(params)
@subject = params[:notification][:subject]
@message = params[:notification][:message]
users = params[:notification][:user_ids].reject(&:blank?)
additional_emails = params[:notification][:emails]
marketers = params[:notification][:marketer_ids].reject(&:blank?)
documents = params[:notification][:document_ids].reject(&:blank?)
state = params[:notification][:state]
city = params[:notification][:city]
zipcode = params[:notification][:zipcode]
#this could be refactored into its own class
emails = []
emails << set_additional_emails(additional_emails)
emails << find_emails_from(User, users)
emails << find_emails_from(Marketer, marketers)
emails << find_emails_from_extra(:employer_state, state)
emails << find_emails_from_extra(:employer_city, city)
emails << find_emails_from_extra(:employer_zipcode, zipcode)
emails.flatten!.uniq!
#this could be refactored into its own class
documents.each do |doc_id|
doc = Document.find(doc_id)
attachments[doc.file.filename.to_s] = File.read(ActiveStorage::Blob.service.send(:path_for, doc.file.key ))
end
mail(to: 'gus.pares@pdgcreative.com', bcc: emails, subject: @subject)
end
private
def find_emails_from(email_class,users)
emails = []
users.each do |user|
emails << email_class.find(user).email
end
emails
end
def find_emails_from_extra(search_term, attribute )
emails = []
emails << User.where("#{search_term} = '#{ attribute }'").pluck(:email)
emails
end
def set_additional_emails(emails)
emails = emails.split(/\s*,\s*/)
end
end
@nilbus
Copy link

nilbus commented May 18, 2020

    emails << User.where("#{search_term} = '#{ attribute }'").pluck(:email)

Do NOT do this. ☝️ You must always use ? in a where string with user input, or it's vulnerable to SQL injection attacks, enabling all kinds of hacks, including stealing everyone's emails and passwords (or any data) and deleting all your data.

    emails << User.where(search_term => attribute).pluck(:email)

This should work and is safe since search_term is not user input.


Do you think a search might return the same email multiple times? You might consider using a Set to store emails instead of an array to prevent duplicates.

    emails = Set.new
    emails << User.where(search_term => attribute).pluck(:email)
    emails

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment