Created
September 5, 2014 08:00
-
-
Save turboMaCk/b878f6b33f0d8318379a to your computer and use it in GitHub Desktop.
ActiveRecord (rails) token authenticable module
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
module TokenAuthenticatable | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def find_by_authentication_token(authentication_token = nil) | |
if authentication_token | |
where(authentication_token: authentication_token).first | |
end | |
end | |
end | |
def ensure_authentication_token | |
if authentication_token.blank? | |
reset_authentication_token! | |
end | |
end | |
def reset_authentication_token! | |
self.authentication_token = generate_authentication_token | |
authentication_token_updated | |
end | |
def clear_authentication_token! | |
self.authentication_token = nil | |
authentication_token_updated | |
end | |
private | |
def authentication_token_updated | |
self.authentication_token_generated_at = DateTime.now | |
update_record_without_timestamping | |
end | |
def generate_authentication_token | |
loop do | |
token = SecureRandom.urlsafe_base64(16) | |
break token unless User.exists?(authentication_token: token) | |
end | |
end | |
# update without recording new timesamps | |
def update_record_without_timestamping | |
class << self | |
def record_timestamps; false; end | |
end | |
save! | |
class << self | |
remove_method :record_timestamps | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment