Last active
May 6, 2020 16:48
-
-
Save ltello/5f5b295bc531b2053c1568e040bbe7a8 to your computer and use it in GitHub Desktop.
Sample DSL
This file contains hidden or 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
# frozen_string_literal: true | |
module PasswordResetable | |
extend ActiveSupport::Concern | |
included do | |
attr_reader :reset_password_token | |
end | |
# Check if the given token is valid to reset the password | |
def password_resetable_with?(token) | |
PasswordResetable::Token.create(token).alive? && | |
!!BCrypt::Password.valid_hash?(reset_password_digest) && | |
BCrypt::Password.new(reset_password_digest) == token | |
end | |
# Set the model so its password can be reset | |
def password_resetable! | |
duration = Rails.application.credentials.dig(:password, :reset_token, :duration_in_mins) | |
update!(reset_password_token: PasswordResetable::Token.new(duration)) | |
end | |
# The datetime when the password cannot be longer reset | |
def reset_password_expires_at | |
reset_password_token&.expires_at | |
end | |
# Renew the token to be able to reset the password | |
def reset_password_token=(token) | |
@reset_password_token = token | |
self.reset_password_digest = (BCrypt::Password.create(token) if token) | |
token | |
end | |
# Returns the digest of the password | |
def reset_password_digest | |
column_reset_password_digest_defined? ? super : no_column_reset_password_digest! | |
end | |
private | |
def column_reset_password_digest_defined? | |
self.class.column_names.include?("reset_password_digest") | |
end | |
def no_column_reset_password_digest! | |
raise("You need to add String column :reset_password_digest to your model!") | |
end | |
def reset_password_digest=(digest) | |
@reset_password_token = nil if digest.nil? | |
self[:reset_password_digest] = digest | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment