Skip to content

Instantly share code, notes, and snippets.

@buurzx
Created April 18, 2016 07:57
Show Gist options
  • Save buurzx/3416fbce7e5b073700903303d8d153ec to your computer and use it in GitHub Desktop.
Save buurzx/3416fbce7e5b073700903303d8d153ec to your computer and use it in GitHub Desktop.
class Account::PhoneVerificationService
attr_reader :account, :errors
MAX_FAILED_ATTEMPTS = 3
def initialize(account)
@account = account
end
def verify(code)
reset_errors!
validate_blank_phone_verification_code!
validate_verification_status!
validate_verification_expiration!
return if has_errors?
validate_code!(code)
end
private
def validate_verification_expiration!
return if account.phone_verification_sent_at.nil? ||
account.phone_verification_sent_at > Account::PHONE_VERIFICATION_TTL.ago
error! I18n.t('account.phone_verification.errors.expired')
end
def validate_verification_status!
return unless account.phone_verified?
error! I18n.t('account.phone_verification.errors.already_verified')
end
def validate_blank_phone_verification_code!
return if account.phone_verification_code.present?
error! I18n.t('account.phone_verification.errors.no_verification_code')
end
def validate_code!(code)
stored_verification_code = account.phone_verification_code
if code == stored_verification_code
account.update_column(:phone_verified_at, Time.zone.now)
account.update_column(:phone_verification_code, nil)
else
failed_attempt!
if failed_attempts_limit_exceeded?
resend_message
error! I18n.t('account.phone_verification.errors.failed_attempts_count_exceeded')
else
error! I18n.t('account.phone_verification.errors.invalid_code')
end
end
end
def failed_attempt!
account.increment!(:phone_verification_attempts)
end
def failed_attempts_limit_exceeded?
account.phone_verification_attempts >= MAX_FAILED_ATTEMPTS
end
def error!(message)
@errors = message
false
end
def has_errors?
@errors.present?
end
def reset_errors!
@errors = nil
end
def resend_message
account.update_column(:phone_verification_attempts, 0)
service = Account::PhoneVerificationDeliveryService.new(account)
service.force_code_generation!
service.send_verification
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment