How to add access token - ruby-on-rails

How to add access token for this URL http://graph.facebook.com/?id=#{checked_url}&access_token=#{access_token} instead of http://graph.facebook.com/?id=#{checked_url}
module SocialShares
class Facebook < Base
def shares!
response = RestClient.get(url, params: {
fields: 'share'
})
json_response = JSON.parse(response)
if json_response['share']
json_response['share']['share_count'] || 0
else
0
end
end
private
def url
"http://graph.facebook.com/?id=#{checked_url}"
end
end
end

Add access token to
"http://graph.facebook.com/?id=#{checked_url}#{access_token}"
private
def access_token
youracesstoken
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

Best practices for Ruby on Rails service

I'm writing some mobile otp validation service and below is my service class
require 'nexmo'
class NexmoServices
def initialize api_key = nil, api_secret = nil, opts = {}
api_key = api_key || Rails.application.secrets.nexmo_api_key
api_secret = api_secret || Rails.application.secrets.nexmo_secret_key
#nexmo_client = Nexmo::Client.new(
api_key: api_key,
api_secret: api_secret,
code_length: 6
)
#brand = 'CryptoShop'
end
def send_verification_code opts
#nexmo_client.verify.request(number: opts[:number], brand: #brand)
end
def check_verification_code opts
#nexmo_client.verify.check(request_id: opts[:request_id], code: opts[:verification_code])
end
def cancel_verification_code opts
#nexmo_client.verify.cancel(opts[:request_id])
end
end
in the controller i'm calling the service methods like below
class NexmoController < ApplicationController
def send_verification_code
response = NexmoServices.new.send_verification_code params[:nexmo]
if response.status == '0'
render json: response.request_id.to_json
else
render json: response.error_text.to_json
end
end
def cancel_verification_code
response = NexmoServices.new.cancel_verification_code params[:nexmo]
if response.status == '0'
render json: response.to_json
else
render json: response.error_text.to_json
end
end
end
I have read that usually there will be call method inside service class and controller will call that. service method call will take care of the rest.
My case im instantiating service objects for all the methods if you see my controller(NexmoService.new).
is it correct??? I want to know the best practise must be followed in this scenario.
Thanks,
Ajith

How to send a get to a server and wait a get in my app in Ruby on Rails

I am using Zapier to search some information in google sheets. I used Webhocks to send a GET to his server with a JSON information. The response of GET is an "OK" and I can't custom this.
So, they will execute a task, find what a I want and return a value, but the response must be a GET in my server, and I don't know how to intercept this response in my route.
I'm trying to study Rails Rack to intercept de request in my app, but I don't know how to send the response to the event that sent the first GET.
How is my middleware:
class DeltaLogger
def initialize app
#app = app
end
def call env
Rails.logger.debug "#{env['QUERY_STRING']}"
#status, #headers, #response = #app.call(env)
[#status, #headers, #response]
end
end
Thanks!
Example
So, to get the value returned from Zapier, I created two routes and a global class cache.
class Zapier
require 'httparty'
def initialize
#answer = ""
#id = 0
end
def request(uri, task)
last_event = Event.last
puts last_event.inspect
if last_event.nil?
last_id = 0
else
last_id = last_event.event_id
end
event_id = last_id + 1
Event.find_or_create_by(event_id: event_id)
result = HTTParty.post(uri.to_str,
:body => {id: event_id, task: task}.to_json,
:headers => {'content-Type' => 'application/json'})
#answer = ""
#id = event_id
end
def response(event_id, value)
if event_id != #id
#answer = ""
else
#answer = value
end
end
def get_answer
#answer
end
end
And my controller:
class ZapierEventsController < ApplicationController
require 'zapier_class'
before_action :get_task, only: [:get]
before_action :get_response, only: [:set]
##zapier ||= Zapier.new
def get
##zapier.request('https://hooks.zapier.com',#task)
sleep 10 #Wait for response
#value = ##zapier.get_answer
render json: { 'value': #value }, status:
end
def set
##zapier.response(#id, #value)
render json: { 'status': 'ok' }, status: 200
end
def get_task
#task = params["task"]
end
def get_response
#id = Integer(params["id"])
#value = params["value"]
end
end
Now i have to make a Task Mananger

How to refactor wrapper using singleton to set up session?

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

Resources