Skip to content

Instantly share code, notes, and snippets.

@turboMaCk
Created September 5, 2014 08:00
Show Gist options
  • Save turboMaCk/b878f6b33f0d8318379a to your computer and use it in GitHub Desktop.
Save turboMaCk/b878f6b33f0d8318379a to your computer and use it in GitHub Desktop.
ActiveRecord (rails) token authenticable module
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