Created
November 12, 2015 02:36
-
-
Save tarot/a74a804997511cec7f7a to your computer and use it in GitHub Desktop.
This file contains 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 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