Skip to content

Instantly share code, notes, and snippets.

@lalitlogical
Created December 18, 2018 06:19
Show Gist options
  • Save lalitlogical/0c8768ab69577d30e2d25c4a6dfe4cee to your computer and use it in GitHub Desktop.
Save lalitlogical/0c8768ab69577d30e2d25c4a6dfe4cee to your computer and use it in GitHub Desktop.
customise devise for otp or reset password token
module CustomiseDevise
extend ActiveSupport::Concern
included do
attr_accessor :project_name, :mailer_host_name, :confirmation_required, :confirmation_type
after_create :send_confirmation_instructions, if: :confirmation_required?
class_eval do
def confirmation_required?
!!confirmation_required
end
def friendly_token(length = 20)
return rand(10 ** 3...10 ** 4) if confirmation_type == 'OTP'
rlength = (length * 3) / 4
SecureRandom.urlsafe_base64(rlength).tr('lIO0', 'sxyz')
end
def generate_token
token = self.friendly_token
while User.where(confirmation_token: token).first
token = self.friendly_token
end
token
end
# Generates a new random token for confirmation, and stores
# the time this token is being generated in confirmation_sent_at
def generate_confirmation_token
if self.confirmation_token && !confirmation_period_expired?
@raw_confirmation_token = self.confirmation_token
else
self.confirmation_token = @raw_confirmation_token = generate_token
self.confirmation_sent_at = Time.now.utc
end
end
end
# override the devise method to set the mailer_host_name name
class << self
# set some project specific values here
def set_project_specific_values resource, attributes = {}
attributes[:mailer_host_name] || raise('Mailer host name not defined.')
[:project_name, :mailer_host_name, :confirmation_type, :confirmation_required].each do |key|
resource.send("#{key}=", attributes[key])
end
end
def send_confirmation_instructions(attributes={})
confirmable = find_by_unconfirmed_email_with_errors(attributes) if reconfirmable
unless confirmable.try(:persisted?)
confirmable = find_or_initialize_with_errors(confirmation_keys, attributes, :not_found)
end
set_project_specific_values(confirmable, attributes)
confirmable.resend_confirmation_instructions if confirmable.persisted?
confirmable
end
def send_reset_password_instructions(attributes={})
recoverable = find_or_initialize_with_errors(reset_password_keys, attributes, :not_found)
recoverable.send_reset_password_instructions if recoverable.persisted?
set_project_specific_values(recoverable, attributes)
recoverable
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment