Skip to content

Instantly share code, notes, and snippets.

@tarot
Created November 12, 2015 02:36
Show Gist options
  • Save tarot/a74a804997511cec7f7a to your computer and use it in GitHub Desktop.
Save tarot/a74a804997511cec7f7a to your computer and use it in GitHub Desktop.
module Tokenizable
extend ActiveSupport::Concern
module ClassMethods
def from_token(token)
row = Rails.cache.read(token).try { |id| find_by_id(id) }
Rails.cache.write(token, row.id, expires_in: 2.hours.to_i) if row.present?
row
end
end
def add_access_token
raise 'cannot add access token if not persisted' unless persisted?
token = generate_token(Settings.access_token.length)
Rails.cache.write(token, id, expires_in: 2.hours.to_i)
token
end
private
def generate_token(size)
validity = -> (token) { Rails.cache.read(token).nil? }
begin
token = SecureRandom.hex(size)[0, size]
end until validity[token]
token
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment