Sha256: 36a203cc0424817c6d09c2e1ce12097cefa6bdf18b61a5fc4dc6110b05ad3dd2

Contents?: true

Size: 987 Bytes

Versions: 1

Compression:

Stored size: 987 Bytes

Contents

require 'securerandom'

module CruLib
  class AccessToken < ActiveModelSerializers::Model
    attr_accessor :key_guid, :email, :first_name, :last_name, :token

    def initialize(attributes = {})
      super
      generate_access_token unless attributes['token']
      write
    end

    class << self

      def read(token)
        json = exist?(token)
        new(Oj.load(json)) if json
      end

      def exist?(token)
        redis_client.get(redis_key(token))
      end

      def redis_client
        @redis_client ||= CruLib.redis_client
      end

      def redis_key(token)
        ['cru_lib:access_token', token].join(':')
      end
    end

    private

    def generate_access_token
      loop do
        attributes[:token] = SecureRandom.uuid.gsub(/\-/, '')
        break unless self.class.exist?(attributes[:token])
      end
    end

    def write
      self.class.redis_client.setex(self.class.redis_key(attributes[:token]), 30.minutes.to_i, to_json)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
cru_lib-0.0.4 lib/cru_lib/access_token.rb