Module: Yclients::Api::Auth

Included in:
Client
Defined in:
lib/yclients/api/auth.rb

Constant Summary collapse

URL =
'https://api.yclients.com/api/v1/auth'

Instance Method Summary collapse

Instance Method Details

#authObject



7
8
9
# File 'lib/yclients/api/auth.rb', line 7

def auth
  @user_token || auth!
end

#auth!Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/yclients/api/auth.rb', line 11

def auth!
  unless @login || @password
    raise AuthError, "Отсутствует логин или пароль"
  end

  uri = URI(URL)
  req = Net::HTTP::Post.new(uri, headers)

  req.body = { "login" => @login, "password" => @password }.to_json

  res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
    http.request(req)
  end
  json = JSON.parse(res.body)

  if json.key?('user_token')
    @user_token = json['user_token']
  else
    raise AuthError, json.to_s
  end
end