Class: WordstreamClient::Auth

Inherits:
Object
  • Object
show all
Defined in:
lib/wordstream_client/auth.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Auth

Returns a new instance of Auth.



5
6
7
# File 'lib/wordstream_client/auth.rb', line 5

def initialize(config)
  @config = config
end

Class Method Details

.clear_sessionObject



9
10
11
# File 'lib/wordstream_client/auth.rb', line 9

def self.clear_session
  Config.session_id = nil
end

.get_api_creditsObject



62
63
64
# File 'lib/wordstream_client/auth.rb', line 62

def self.get_api_credits
  Config.client.auth.get_api_credits
end

.loginObject



18
19
20
# File 'lib/wordstream_client/auth.rb', line 18

def self.
  Config.client.auth.
end

.logoutObject



41
42
43
# File 'lib/wordstream_client/auth.rb', line 41

def self.logout
  Config.client.auth.logout
end

Instance Method Details

#clear_sessionObject



13
14
15
16
# File 'lib/wordstream_client/auth.rb', line 13

def clear_session
  self.class.clear_session
  @config.session_id = nil if @config
end

#get_api_creditsObject



66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/wordstream_client/auth.rb', line 66

def get_api_credits
  path  = '/authentication/get_api_credits'
  query = "?session_id=#{@config.session_id}"
  resp  = RestClient.get(@config.default_host + path + query)
  data  = JSON.parse resp.body

  raise AuthError.new('get_api_credits', data['detail']) if data['code'].match(/error/i)

  return data
rescue JSON::ParserError => e
  raise AuthError.new('get_api_credits', 'Bad response from Wordstream when trying to get api credits.')
end

#loginObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/wordstream_client/auth.rb', line 22

def 
  path  = '/authentication/login'
  query = "?username=#{@config.username}&password=#{@config.password}"
  resp  = RestClient.get(@config.default_host + path + query)
  data  = JSON.parse resp.body

  raise AuthError.new('login', data['error']) if data.has_key?('error')

  session_id         = data['data']['session_id'] if data.has_key?('data')
  Config.session_id  = session_id
  @config.session_id = session_id

  raise AuthError.new('login', 'Failed to get a session id from Wordstream.') if @config.session_id.nil?

  return data
rescue JSON::ParserError => e
  raise AuthError.new('login', 'Bad response from Wordstream when trying to login.')
end

#logoutObject



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/wordstream_client/auth.rb', line 45

def logout
  path  = '/authentication/logout'
  query = "?session_id=#{@config.session_id}"
  resp  = RestClient.get(@config.default_host + path + query)
  data  = JSON.parse resp.body

  raise AuthError.new('logout', data['error']) if data.has_key?('error')

  clear_session

  return data
rescue JSON::ParserError => e
  raise AuthError.new('logout', 'Bad response from Wordstream when trying to logout.')
ensure
  clear_session
end