Unfuddle API get accounts info - ruby-on-rails

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

Related

How can I parse a json response.body to store a key's value in ruby on rails?

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]

Ruby on Rails - uninitialized constant SiteController::API

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

uninitialized constant "controllername::modulename" TableauServer

Im trying to test the tableau_trusted.rb example for trusted authentication for tableau server in Ruby on rails but I keep getting the error "uninitialized constantTableauTrustedsController::TableauTrustedInterface", this is my code:
tableautrusteds_controller.rb
class TableauTrustedsController < ApplicationController
include TableauTrustedInterface
def index
tabserver = 'xxxxx'
tabuser = 'test'
tabpath = 'views/Tableau_DW1/General?:iid=1'
tabparams = ':embed=yes&:toolbar=no'
ticket = tableau_get_trusted_ticket(tabserver, tabuser, request.remote_ip)
if ticket != "-1"
url = "http://#{tabserver}/trusted/#{ticket}/#{tabpath}?#{tabparams}"
redirect_to url
return
end
render :status => 403, :text => "Error with request"
end
end
module TableauTrustedInterface
require 'net/http'
require 'uri'
# the client_ip parameter isn't necessary to send in the POST unless you have
# wgserver.extended_trusted_ip_checking enabled (it's disabled by default)
def tableau_get_trusted_ticket(tabserver, tabuser, client_ip)
post_data = {
"username" => tabuser,
"client_ip" => client_ip
}
response = Net::HTTP.post_form(URI.parse("http://#{tabserver}/trusted"), post_data)
case response
when Net::HTTPSuccess
return response.body.to_s
else
return "-1"
end
end
end
I have changed the line "include TableauTrustedInterface" to "extend TableauTrustedInterface" but it didn't work.
Also, The URL I put in the browser is
http://localhost:3000/tableautrusteds/index, I use get 'tableautrusteds/index' in routes.rb.
I don't really know if that is important but some people ask me for this.
I am little bit new in rails so any help will be very appreciated.
I fixed my problem, if anybody was having a similar issue here is my code
module TableauTrustedInterfaces
require 'net/http'
require 'uri'
# the client_ip parameter isn't necessary to send in the POST unless you have
# wgserver.extended_trusted_ip_checking enabled (it's disabled by default)
def tableau_get_trusted_ticket(tabserver, tabuser, client_ip)
post_data = {
"username" => tabuser,
"client_ip" => client_ip
}
response = Net::HTTP.post_form(URI.parse("http://#{tabserver}/trusted"), post_data)
case response
when Net::HTTPSuccess
return response.body.to_s
else
return "-1"
end
end
end
class TableauTrustedController < ApplicationController
include TableauTrustedInterfaces
def index
tabserver = 'xxxxx'
tabuser = 'test'
tabpath = 'views/Tableau_DW1/General?:iid=1'
tabparams = ':embed=yes&:toolbar=no'
ticket = tableau_get_trusted_ticket(tabserver, tabuser, request.remote_ip)
if ticket != "-1"
url = "http://#{tabserver}/trusted/#{ticket}/#{tabpath}?#{tabparams}"
redirect_to url
return
end
render json: {}, status: :forbidden
end
end
In order to use the module it needs to be declared before the class. Also, and very important I changed the name of the file to tableau_trusted_controler.rb because the snake case that rails uses.

Updating Rails 5 Initializer with Devise User Parameters

I thought I was getting closer to wrapping my head around Rails until this challenge. I have an initializer agilecrm.rb - content show below. I am using AgileCRM Ruby code to try and connect my app with AgileCRM system. When using the code below, with the test Create Contact array at the bottom, it successfully creates a contact in my AgileCRM account, so I know at least this part works. What I need to do is create a new AgileCRM user every time I create a new Devise user. I have a feeling that I am looking at this the wrong way and probably need a controller for this, but this is not completely foreign to me, but I still can't figure out when way to go. Thank you.
config/initializers/agilecrm.rb
require 'net/http'
require 'uri'
require 'json'
class AgileCRM
class << self
def api_key=(key)
##api_key = key
end
def domain=(d)
##domain = d
end
def email=(email)
##email = email
end
def api_key
##api_key
end
def domain
##domain
end
def email
##email
end
def request(method, subject, data = {})
path = "/dev/api/#{subject}"
case method
when :get
request = Net::HTTP::Get.new(path)
when :post
request = Net::HTTP::Post.new(path)
request.body = data.to_json
when :put
request = Net::HTTP::Put.new(path)
request.body = data.to_json
when :delete
request = Net::HTTP::Delete.new(path)
else
raise "Unknown method: #{method}"
end
uri = URI.parse("https://#{domain}.agilecrm.com")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request['Content-Type'] = 'application/json'
request['Accept'] = 'application/json'
request.basic_auth AgileCRM.email, AgileCRM.api_key
response = http.request(request)
response.body
end
end
end
AgileCRM.api_key = '*******'
AgileCRM.domain = '*******'
AgileCRM.email = '*******'
# ======================Create Contact====================================
contact_data = '{
"star_value": "4",
"lead_score": "92",
"tags": [
"Lead",
"Likely Buyer"
],
"properties": [
{
"type": "SYSTEM",
"name": "first_name",
"value": "John"
}
]
}'
parsed_contact_data = JSON.parse(contact_data)
print(AgileCRM.request :post, 'contacts', parsed_contact_data)
You might want to move this logic into your User model, and have a after_save hook to push data to agilecrm. Assuming that the Devise user model is called User :
class User < ApplicationRecord
...
after_save :sync_to_agilecrm
def sync_to_agilecrm
# your agilecrm api calls go here
...
end
end
The above should do what you are trying to achieve.

Force fake response using ActiveMerchant response

have a transaction model similar to RailsCasts ActiveMerchant tutorial.
How can I create a fake response?
Tried something like the following but no luck.
response = #success=true, #params = {"ref" => "123"}, #authorization = "54321", ...
models/order_transaction.rb
class OrderTransaction < ActiveRecord::Base
belongs_to :order
serialize :params
def response=(response)
self.success = response.success?
self.authorization = response.authorization
self.message = response.message
self.params = response.params
rescue ActiveMerchant::ActiveMerchantError => e
self.success = false
self.authorization = nil
self.message = e.message
self.params = {}
end
end
you can do something like
a = OpenStruct.new
def a.success?
true
end

Resources