Created
April 18, 2016 07:57
-
-
Save buurzx/af9b1cb24ca4e2a5a9b126266932a21d to your computer and use it in GitHub Desktop.
PhoneVerificationDeliveryService
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Account::PhoneVerificationDeliveryService | |
PHONE_NUMBER = Rails.application.secrets.twilio['phone_number'] if Rails.application.secrets.twilio | |
attr_reader :account, :errors | |
def initialize(account) | |
@account = account | |
@errors = [] | |
end | |
def send_verification | |
generate_verification_code_if_needed! | |
send_verification_code!.tap do |result| | |
account.update_column(:phone_verification_sent_at, Time.zone.now) if result | |
end | |
end | |
def force_code_generation! | |
@force_code_generation = true | |
end | |
def force_code_generation? | |
!!@force_code_generation | |
end | |
private | |
def send_verification_code! | |
twilio_client.messages.create(to: formatted_phone_number, from: PHONE_NUMBER, | |
body: message) | |
rescue Twilio::REST::RequestError => e | |
@errors << e.message | |
Rails.logger.error(e.message) | |
false | |
end | |
def twilio_client | |
@twilio_client ||= Twilio::REST::Client.new | |
end | |
def formatted_phone_number | |
"+1#{account.phone.tr('-', '')}" | |
end | |
def generate_verification_code_if_needed! | |
return if !force_code_generation? && | |
account.phone_verification_code.present? && !verification_code_expired? | |
account.update_column(:phone_verification_code, generate_phone_verification_code) | |
end | |
def verification_code_expired? | |
account.phone_verification_sent_at && | |
account.phone_verification_sent_at < Account::PHONE_VERIFICATION_TTL.ago | |
end | |
def generate_phone_verification_code | |
rand(0000..9999).to_s.rjust(4, '0') | |
end | |
def message | |
I18n.t('account.phone_verification.message', code: account.phone_verification_code) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment