Class: Discordrb::TokenCache

Inherits:
Object
  • Object
show all
Defined in:
lib/discordrb/token_cache.rb

Overview

Represents a token file

Instance Method Summary collapse

Constructor Details

#initializeTokenCache

Returns a new instance of TokenCache.



112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/discordrb/token_cache.rb', line 112

def initialize
  if File.file? CACHE_PATH
    @data = JSON.parse(File.read(CACHE_PATH))
  else
    LOGGER.debug("Cache file #{CACHE_PATH} not found. Using empty cache")
    @data = {}
  end
rescue => e
  LOGGER.debug('Exception occurred while parsing token cache file:', true)
  LOGGER.log_exception(e)
  LOGGER.debug('Continuing with empty cache')
  @data = {}
end

Instance Method Details

#store_token(email, password, token) ⇒ Object

Caches a token

Parameters:

  • email (String)

    The email to store this token under

  • password (String)

    The plaintext password to encrypt the token with

  • token (String)

    The plaintext token to cache



159
160
161
162
163
164
165
# File 'lib/discordrb/token_cache.rb', line 159

def store_token(email, password, token)
  cached = CachedToken.new
  cached.generate_verify_hash(password)
  cached.encrypt_token(password, token)
  @data[email] = cached.data
  write_cache
end

#token(email, password) ⇒ String?

Gets a token from this token cache

Parameters:

  • email (String)

    The email to get the token for

  • password (String)

    The plaintext password to get the token for

Returns:

  • (String, nil)

    the stored token, or nil if unsuccessful (e. g. token not cached or cached token invalid)



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/discordrb/token_cache.rb', line 130

def token(email, password)
  if @data[email]
    begin
      cached = CachedToken.new(@data[email])
      if cached.verify_password(password)
        token = cached.decrypt_token(password)
        if token
          begin
            cached.test_token(token)
            token
          rescue => e
            fail_token('Token cached, verified and decrypted, but rejected by Discord', email, e)
            sleep 1 # wait some time so we don't get immediately rate limited
            nil
          end
        else; fail_token('Token cached and verified, but decryption failed', email)
        end
      else; fail_token('Token verification failed', email)
      end
    rescue => e; fail_token('Token cached but invalid', email, e)
    end
  else; fail_token('Token not cached at all')
  end
end

#write_cacheObject

Writes the cache to a file



168
169
170
# File 'lib/discordrb/token_cache.rb', line 168

def write_cache
  File.write(CACHE_PATH, @data.to_json)
end