Skip to content

Instantly share code, notes, and snippets.

@dorianmariefr
Created September 3, 2023 14:11
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
# 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