Skip to content

Instantly share code, notes, and snippets.

@dorianmariecom
Created September 3, 2023 14:11
Show Gist options
  • Save dorianmariecom/db4d6deedaa3bb9082523e0af0865a9a to your computer and use it in GitHub Desktop.
Save dorianmariecom/db4d6deedaa3bb9082523e0af0865a9a to your computer and use it in GitHub Desktop.
# requires :password_reset_token and :password_reset_token_expires_at fields
module PasswordResetable
extend ActiveSupport::Concern
included do
before_validation do
if password_reset_token_expires_at && password_reset_expires_at.past?
expire_password_reset!
end
end
end
def reset_password!(token:, password:)
if password_reset_token_expires_at && password_reset_expires_at.future? &&
ActiveSupport::SecurityUtils.secure_compare(password_reset_token, token)
update!(password: password)
expire_password_reset!
true
else
false
end
end
def will_reset_password!
self.password_reset_token ||= SecureRandom.hex
self.password_reset_token_expires_at ||= 1.hour.from_now
save!
end
def expire_password_reset!
self.password_reset_token = nil
self.password_reset_token_expires_at = nil
save!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment