I am building a API to a recieve stats for a specific game.
Right now I am able to recieve stats once every time I start my server. After looking up 1 Player I and I'm trying to refresh the page to look up another(right now I am using gets.chomp via console to enter the names) I get the following error:
uninitialized constant SiteController::API
class SiteController < ApplicationController
require_relative '../../lib/api'
def stats
api = API.new(
username: 'someusername',
password: 'somepassword',
token: 'sometoken',
)
puts "Username: "
username = gets.chomp
puts "Platform: "
platform = gets.chomp
#allStats = api.getStats(username, platform)
end
end
api.rb
require 'net/http'
require 'json'
class API
def initialize(auth)
#auth = auth
#Token = getToken['access_token']
end
def TOKEN_URL
'https://antoherlink.com'
end
def EXCHANGE_URL
'https://somelink.com'
end
def LOOKUP_URL(username)
"https://somelink.com{username}"
end
def STATS_URL(id)
"https://somelink.com"
end
def httpGet(url, auth)
uri = URI(url)
req = Net::HTTP::Get.new(uri)
req['Authorization'] = auth
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(req)
end
JSON.parse(res.body)
end
def httpPost(url, params, auth)
uri = URI(url)
req = Net::HTTP::Post.new(uri)
req.set_form_data(params)
req['Authorization'] = auth
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(req)
end
JSON.parse(res.body)
end
def getToken
params = {
grant_type: 'password',
includePerms: true,
username: #auth[:username],
password: #auth[:password]
}
httpPost(TOKEN_URL(), params, "basic #{#auth[:token]}")
end
def getExchangeCode
httpGet(EXCHANGE_URL(), "bearer #{getToken['access_token']}")['code']
end
def getToken
params = {
grant_type: 'exchange_code',
includePerms: true,
token_type: 'eg1',
exchange_code: getExchangeCode
}
httpPost(TOKEN_URL(), params, "basic #{#auth[:anothertoken]}")
end
def lookup(username)
httpGet(LOOKUP_URL(username), "bearer #{#Token}")
end
def getRawStats(username)
httpGet(STATS_URL(lookup(username)['id']), "bearer #{#Token}")
end
def getStats(username, platform)
result = decodeRawStats(getRawStats(username), platform)
What did I miss?
Try changing:
class SiteController < ApplicationController
require_relative '../../lib/api'
# ...
end
to
require_dependency 'api'
class SiteController < ApplicationController
# ...
end
Related
I am receiving a json response (response.body) from the api call I am making with my model and in my controller I would like to parse it to store its id key's value in my session[:user_id].
I've tried to implement it in the following way
parsed_body = JSON.parse(User.new.get_credentials, :symbolize_names => true)
puts "The parsed_body is: #{parsed_body}"
session[:user_id] = parsed_body[0][:id]
puts "The session id is: #{session[:user_id]} "
The response.body is:
{"result":[{"id":"3","username":"Sam","password":"111"},{"id":"4","username":"Harshal","password":"1234"},{"id":"5","username":"Dev","password":"112"},{"id":"6","username":"Lam","password":"113"},{"id":"7","username":"Tim","password":"114"},{"id":"8","username":"Harry","password":"222"}]}
The parsed_body is:
{:result=>[{:id=>"3", :username=>"Sam", :password=>"111"}, {:id=>"4", :username=>"Harshal", :password=>"1234"}, {:id=>"5", :username=>"Dev", :password=>"112"}, {:id=>"6", :username=>"Lam", :password=>"113"}, {:id=>"7", :username=>"Tim", :password=>"114"}, {:id=>"8", :username=>"Harry", :password=>"222"}]}
Here is my code for users controller, user model and sessions controller:
Users Controller
class UsersController < ApplicationController
def create
#users = User.new(token: user_params).credentials
parsed_body = JSON.parse(User.new.get_credentials, :symbolize_names => true)
puts "The parsed_body is: #{parsed_body}"
session[:user_id] = parsed_body[0][:id]
puts "The session id is: #{session[:user_id]} "
redirect_to '/dashboard'
end
private
def user_params
params.require(:user).permit(:id, :username, :password).to_hash
end
end
User Model
class User
def initialize(attributes={})
#token ||= attributes[:token]
end
def credentials
my_connection = Net::HTTP.new('localhost', 8080)
request = my_connection.post('/restapitrial/index.php/Users/insert/', #token.to_json, "Content-Type" => "application/json")
end
def get_credentials
my_connection = Net::HTTP.new('localhost', 8080)
request = my_connection.get('/restapitrial/index.php/Users/displayinfo/', "Content-Type" => "application/json")
puts "The req body is #{request.body}"
return request.body
end
end
Sessions Controller
class SessionsController < ApplicationController
def create
user = User.find_by(id: login_params[:id])
if user && user.authenticate(login_params[:password])
session[:user_id] = user.id
redirect_to '/dashboard'
else
flash[:login_errors] = ['invalid credentials']
redirect_to '/'
end
end
private
def login_params
params.require(:login).permit(:id, :username, :password)
end
end
If you want to get the last id in the array that is returned then use the
parsed_body[:result][-1][:id]
I don't understand what I do wrong. I want to send a simple request to an API, and it didn't work:
class Paytrace
require 'rest-client'
attr_reader :auth_token, :authorize
def initialize()
#auth_token = auth_token
end
def auth_token
response = RestClient.post 'https://api.paytrace.com/oauth/token', { grant_type: :password, username: "loginname", password: "htmlkoi8r" }
puts response
end
def authorize
headers = {:Authorization => "Bearer #{auth_token['access_token']}"}
response1 = RestClient.get('https://api.paytrace.com/v1/transactions/sale/keyed', headers)
puts response1
end
end
a = Paytrace.new
a.authorize
console.log
lucker#lucker-pc:~/git/paytrace-testh$ ruby integration.rb
{"access_token":"c6d69786f6075633:8647d6c6b6f6968327:092e8cfc553726d2b8198577ea2836f41173aae68a53aa1d2af2b2c7f65dcdc7","token_type":"Bearer","expires_in":7200,"created_at":1556098344}
{"access_token":"c6d69786f6075633:8647d6c6b6f6968327:232c92f977a301d033eec321c3d82b73bb65ebec33f9fcc8f6c2d7575c8b0d88","token_type":"Bearer","expires_in":7200,"created_at":1556098346}
Traceback (most recent call last): 1: from integration.rb:25:in
<main>' integration.rb:16:inauthorize': undefined method `[]' for
nil:NilClass (NoMethodError)
Why is the access_token generated twice?
Why is there an undefined method '[]' for nil:NilClass?
Your method auth_token is not returning a response, but a nil (puts returns nil).
Btw, you don't need attr_reader :authorize since you have a method with that name.
Also, as you are setting attr_reader :auth_token, the method auth_token must be rename (and maybe become private).
Change your code to:
class Paytrace
require 'rest-client'
attr_reader :auth_token
def initialize()
#auth_token = get_auth_token
end
def authorize
headers = {:Authorization => "Bearer #{auth_token['access_token']}"}
RestClient.get('https://api.paytrace.com/v1/transactions/sale/keyed', headers)
end
private
def get_auth_token
RestClient.post 'https://api.paytrace.com/oauth/token', { grant_type: :password, username: "loginname", password: "htmlkoi8r" }
end
end
a = Paytrace.new
puts a.auth_token
puts a.authorize
Seems like there are 3 mistakes in this code the 2 puts. line 12 and 20
and the
headers = {:Authorization => "Bearer #{auth_token['access_token']}"}
should be
headers = {:Authorization => "Bearer #{auth_token[:access_token]}"}
or
headers = {:Authorization => "Bearer #{#auth_token[:access_token]}"}
try this code
class Paytrace
require 'rest-client'
attr_reader :auth_token, :authorize
def initialize()
#auth_token = auth_token
end
def auth_token
response = RestClient.post 'https://api.paytrace.com/oauth/token', { grant_type: :password, username: "loginname", password: "htmlkoi8r" }
# puts response
end
def authorize
headers = {:Authorization => "Bearer #{#auth_token[:access_token]}"}
response1 = RestClient.get('https://api.paytrace.com/v1/transactions/sale/keyed', headers)
# puts response1
end
end
a = Paytrace.new
a.authorize
take care the your response hash if you check is
{:access_token=>"c6d69786f6075633:8647d6c6b6f6968327:092e8cfc553726d2b8198577ea2836f41173aae68a53aa1d2af2b2c7f65dcdc7",
:token_type=>"Bearer",
:expires_in=>7200,
:created_at=>1556098344}
and not
{"access_token":"c6d69786f6075633:8647d6c6b6f6968327:092e8cfc553726d2b8198577ea2836f41173aae68a53aa1d2af2b2c7f65dcdc7","token_type":"Bearer","expires_in":7200,"created_at":1556098344}
I'm trying to do a request in httparty but it's not working
require 'httparty'
module PvWatch
class Client
include HTTParty
# base_uri ENV["pv_watch_endpoint"]
def login
response = self.class.post('http://pvwatch.xxx.xxx.xxx.net/api/v1/login', options)
end
def options
{
headers: {
'content-type' => 'application/json',
'access-key' => 'FORGET ABOUT THIS',
'authorization' => 'uri=api/v1/login'
},
body: {
username: "case",
password: "123"
}
}
end
end
end
the weird thing is that when i do the request with net/http is working and i don't know what i'm doing wrong with httparty
require 'uri'
require 'net/http'
module PvWatch
class Client
def login
url = URI("http://pvwatch.xxx.xxx.xxx.net/api/v1/login")
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Post.new(url)
request["content-type"] = 'application/x-www-form-urlencoded'
request["access-key"] = 'FORGET ABOUT THIS'
request["authorization"] = 'uri=api/v1/login'
request.body = "username=case&password=123"
response = http.request(request)
puts response.read_body
end
end
end
any idea what i'm doing wrong?
module Asterisk
class Client
include HTTParty
base_uri 'https://asterisk.dev/'
def initialize(session_key = nil)
#session_key = session_key
end
def get_session_key(login, password)
self.class.put('/api/auth', query: { login: login, password: password })
end
def get_contacts
self.class.get("/api/#{#session_key}/contacts")
end
def get_contact(id)
self.class.get("/api/#{#session_key}/contact/#{id}")
end
def create_contact
self.class.put("/api/#{#session_key}/create")
end
def logout
self.class.delete("/api/#{#session_key}/logout")
end
end
end
Right now it works like below
session_key = Asterisk::Client.new.get_session_key('login', 'pass')
client = Asterisk::Client.new(session_key)
client.get_contacts
I would like to get and set session key using singleton. How to do that?
module Asterisk
class Client
include HTTParty
include Singleton
base_uri 'https://asterisk.dev/'
attr_reader :last_session_update
private
def session_key
if !#session_key || session_refresh_needed?
#session_key = set_session_key
#last_session_update = Time.now
else
#session_key
end
end
def set_session_key
self.class.put('/api/auth', query: { login: login, password: password })
end
def password
#the way you get pass
end
def login
#the way you get login (ENV...)
end
def session_refresh_needed?
return true unless last_session_update
( Time.now - last_session_update) > 30.minute
end
end
end
It includes your issue with 30 minutes refresh.
Now call Asterisk::Client.instance
I'm trying to get the account info from Unfuddle API using ActiveResource
The url is http://mydomain.unfuddle.com/api/v1/account
this is my ActiveResource class
class Account < ActiveResource::Base
self.collection_name = "account"
self.site = "https://mydomain.unfuddle.com/api/v1"
self.user = "me"
self.password = "pass"
end
if I try getting my account info with Account.all I'll get an empty array but if I try this
require 'net/https'
UNFUDDLE_SETTINGS = {
:subdomain => 'mydomain',
:username => 'me',
:password => 'pass',
:ssl => true
}
http = Net::HTTP.new("#{UNFUDDLE_SETTINGS[:subdomain]}.unfuddle.com",UNFUDDLE_SETTINGS[:ssl] ? 443 : 80)
if UNFUDDLE_SETTINGS[:ssl]
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
begin
request = Net::HTTP::Get.new('/api/v1/account')
request.basic_auth UNFUDDLE_SETTINGS[:username], UNFUDDLE_SETTINGS[:password]
response = http.request(request)
if response.code == "200"
puts response.body
else
puts "HTTP Status Code: #{response.code}."
end
rescue => e
puts e.message
end
I get my account information , any ideas why the ActiveResource approach isn't working ?
**UPDATE
I forgot to specify that I had this issue https://github.com/rails/rails/issues/2318 and I use erikkallens hack .
It seems to be this issue https://github.com/rails/rails/issues/2318 , I tried vaskas solution but it didn't work by default I had to modify it.
class Account < ActiveResource::Base
self.collection_name = "account"
self.site = "https://mydomain.unfuddle.com/api/v1"
self.user = "me"
self.password = "pass"
self.format = AccountXMLFormatter.new
end
class AccountXMLFormatter
include ActiveResource::Formats::XmlFormat
def decode(xml)
[account: ActiveResource::Formats::XmlFormat.decode(xml)]
end
end