i successfully got generating tokens working on the ios side, and i have a heroku rails app set up. How do i retrieve this token on the server side?
getting the error `Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms)
NoMethodError (undefined method []' for nil:NilClass):
app/controllers/login_controller.rb:11:in 'log_in'
here is my controller code:
class LoginController < ApplicationController
def index
end
def log_in
puts params
headers = {"X-Parse-Application-Id" => "APIKEY",
"X-Parse-REST-API-Key" => "APIKEY"}
query = {:username => params[:user][:username],
:password => params[:user][:password]}
#response = HTTParty.get('https://api.parse.com/1/login',
:query => query,
:headers => headers)
session[:session_token] = #response["sessionToken"]
session[:object_id] = #response["objectId"]
#object_id = session[:object_id]
#test = HTTParty.get("https://api.parse.com/1/classes/_User/#{#object_id}",
:headers => {"X-Parse-Application-Id" => "APIKEY",
"X-Parse-REST-API-Key" =>"APIKEY"} )
session[:stripe_acct_id] = #test["uid"]
end
def logout
logout = HTTParty.post('https://api.parse.com/1/logout',
:headers => {"X-Parse-Application-Id" => "APIKEY",
"X-Parse-REST-API-Key" => "APIKEY",
"X-Parse-Session-Token" => session[:session_token]})
reset_session
redirect_to :controller => "login"
end
def deauthorize
#object_id = session[:object_id]
HTTParty.post("https://connect.stripe.com/oauth/deauthorize",
:basic_auth => { :username => ENV['STRIPE_SECRET'] },
:query => { client_id: ENV['STRIPE_CONNECT_CLIENT_ID'],
stripe_user_id: session[:stripe_acct_id]})
end
end
In your controller add:
protect_from_forgery: :null, only: :log_in
For your error, it's because you don't send user object in your post request.
Related
I want to use Yahoo Fantasy sport API in my web application, For that I am using OAuth for Yahoo login. I have consumer key and secret key and i passed the keys successfully, When I run the following code. It redirects to Yahoo login, It asks permission for accessing the user's credentials. If i give AGREE the page Redirects to https://api.login.yahoo.com/oauth/v2/request_auth and It shows the Verifying code. If i press the close button in verification code page, it's not callback to my URL.
#ts=Time.now.to_i
#callback_url = "http://localhost:3000/callback"
#nonce = SecureRandom.hex()
consumer = OAuth::Consumer.new("my consumerkey","secret key",
{ :site => 'https://api.login.yahoo.com',
:http_method => :post,
:scheme => :header,
:oauth_nonce => #nonce,
:request_token_path => '/oauth/v2/get_request_token',
:authorize_path => '/oauth/v2/request_auth',
:access_token_path => '/oauth/v2/get_token',
:oauth_callback => "http://localhost:3000/callback",
:oauth_timestamp => Time.now.to_i,
:oauth_signature_method => "HMAC-SHA-1",
:oauth_version => "1.0",
:oauth_callback_confirmed => true,
})
request_token = consumer.get_request_token
session[:request_token]=request_token
redirect_to request_token.authorize_url
access_token=request_token.get_access_token
access = ActiveSupport::JSON.decode(access_token.to_json)
if !(access.present?)
#response = "Response failed"
else
#response = access
end
Can you please tell me What changes to be made to get the callback for to get access_token.
I think you got confused while getting callback. change your code as follows, You will surely get access token to make Yahoo API call.
##access_token = nil
##request_token = nil
def get_request_token
##consumer = OAuth::Consumer.new('consumer key',
'secret key',
{
:site => 'https://api.login.yahoo.com',
:scheme => :query_string,
:http_method => :get,
:request_token_path => '/oauth/v2/get_request_token',
:access_token_path => '/oauth/v2/get_token',
:authorize_path => '/oauth/v2/request_auth'
})
##request_token = ##consumer.get_request_token( { :oauth_callback => 'http://localhost:3000/callback' } )
session[:request_token]=##request_token
redirect_to ##request_token.authorize_url
#redirect_to ##request_token.authorize_url( { :oauth_callback => 'http://localhost:3000/success' } )
end
def callback
request_token = ActiveSupport::JSON.decode(##request_token.to_json)
if !(request_token.present?)
$request_token_value = "Response failed"
else
$request_token_value = request_token
end
# access_token = ##request_token.get_access_token({:oauth_verifier=>params[:oauth_verifier],:oauth_token=>params[:oauth_token]})
##access_token = ##request_token.get_access_token(:oauth_verifier=>params[:oauth_verifier])
access_json = ActiveSupport::JSON.decode(##access_token.to_json)
puts "****************************"
puts $access_json
puts "****************************"
end
I think I stated the title of this question right, but this is the issue:
I have the following in my SurveysController-
def pull_responses
call= "/api/v2/surveys/"
auth = {:username => "test", :password => "password"}
url = HTTParty.get("https://fluidsurveys.com#{call}",
:basic_auth => auth,
:headers => { 'ContentType' => 'application/json' } )
response = JSON.parse(url.body)
survey_ids = response["surveys"].map { |s| s["id"] }
survey_ids.each do |x|
call= "/api/v2/surveys/#{x}/responses/?_completed=1"
auth = {:username => "test", :password => "password"}
url = HTTParty.get("https://Fluidsurveys.com#{call}",
:basic_auth => auth,
:headers => { 'ContentType' => 'application/json' } )
response = JSON.parse(url.body)
response_count = response["count"]
Survey.create(y: response_count)
end
end
helper_method :pull_responses
All I am trying to do is put the variable response_count in my Surveys view. I may not need Survey.create(y: response_count), but that was a peice of one of my attempts to get this to work. Essentially, I just want to write this in a view:
puts response_count
What is the proper way to put that response into a view?
You need to assign the value to an instance variable (by adding # before the name) so that it will persist to the view:
#response_count = response["count"]
then in the view you can print it like so:
<%= #response_count %>
I know we can sync data using rhodes without Rhosync or Rhoconnect by using direct web service, but I'm here little bit confuse where to place that code for webservice call and how do we initialize it. Can anyone help me with small example?
Thanks in Advance.
I got it and it works for me.
class ProductController < Rho::RhoController
include BrowserHelper
# GET /product
def index
response = Rho::AsyncHttp.get(:url => "example.com/products.json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
render :back => '/app'
end
# GET /product/{1}
def show
id =#params['id']
response = Rho::AsyncHttp.get(:url => "example.com/products/"+ id +".json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
end
# GET /product/new
def new
#product = product.new
render :action => :new, :back => url_for(:action => :index)
end
# GET /product/{1}/edit
def edit
id =#params['product_id'].to_s
response = Rho::AsyncHttp.get(:url => "example.com/products/#{id}.json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
end
# POST /product/create
def create
name = #params['product']['name']
price = #params['product']['price']
body = '{"product" : {"name" : "'+ name +'","price" :"'+ price +'" } }'
#result = Rho::AsyncHttp.post(:url => "example.com/products.json",
:body => body, :http_command => "POST", :headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
# POST /product/{1}/update
def update
name=#params['product']['name']
price=#params['product']['price']
body = '{"product" : {"name" : "' + name + '","price" :"' + price + '" } }'
id = #params["product_id"].to_s
response = Rho::AsyncHttp.post(:url => "example.com/products/#{id}.json",
:body => body, :http_command => "PUT",:headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
# POST /product/{1}/delete
def delete
id = #params["product_id"].to_s
response = Rho::AsyncHttp.post(:url => "example.com/products/#{id}.json",
:http_command => "DELETE",
:headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
end
Most easy form of http server request is next:
Rho::AsyncHttp.get(
:url => "http://www.example.com",
:callback => (url_for :action => :httpget_callback)
)
where httpget_callback is name of the controller callback method.
See more details at official Rhodes docs.
I am very new guy in Rhomobile and I want to login a webservice using Rhoconnect can anyone help me how to implement this.
I've tried with in Settings Controler:
def do_login
if #params['username'] and #params['password']
begin
SyncEngine.login(#params['username'], #params['password'], (url_for :action => :login_callback) )
#response['headers']['Wait-Page'] = 'true'
redirect :action => :index
rescue Rho::RhoError => e
#msg = e.message
render :action => :login
end
else
#msg = Rho::RhoError.err_message(Rho::RhoError::ERR_UNATHORIZED) unless #msg && #msg.length > 0
render :action => :login
end
end
Where SyncEngine.login(#params['username'], #params['password']) call the sourecadapter method login; where I'm calling
def login(username, password)
user_info = {:username => username, :password => password }
response = RestClient.get(#base+#params['username']+#params['password'])
result = RestClient.post(:url => "my-webservice" )
#msg=result["body"]
render :action => :index
end
I've tried in:
class Application < Rhoconnect::Base
class << self
def authenticate(username,password,session)
result = RestClient.post(:url => "mywebservice" )
true # do some interesting authentication here...
end
end
But I got nothing..
plz give some idea me; how to solve this
SyncEngine.login call from Rhodes app will call authenticate(username, password, session)
method in application.rb of your RhoConnect app. Then, you can code the authenticate method to call your implementation of user authentication as follows:
def authenticate(username, password, session)
# for example
resp = RestClient.post(:url => "mywebservice", :login => {:username => username, :password => password})
#parse resp as needed and return the result either true or false
# i.e. status contains value true or false in the response body
result = JSON.parse(resp.body)['status']
end
Hope that helps.
OK, I am pulling my hair after trying this out too many times to debug.
So please help me out here. I keep getting 401 Unauthorized error after I am redirected back.
Here is my code. What am I doing wrong here?
require 'rubygems'
require 'OAuth'
require 'json'
class SessionController < ApplicationController
before_filter :load_oauth
def index
if session[:request_token] && params[:oauth_token]
#request_token = OAuth::RequestToken.new(#consumer,
session[:request_token], session[:request_secret])
#access_token =
#request_token.get_access_token(:oauth_verifier =>
params[:oauth_verifier])
puts #access_token
#info = #access_token.get("http://api.foursquare.com/v1/
test")
flash[:notice] = "Foursquare! Yay!"
else
redirect_to(#foursqrurl)
end
end
private
def load_oauth
#oauth_key = 'key'
#oauth_secret = 'secret'
#consumer = OAuth::Consumer.new(#oauth_key,#oauth_secret,{
:site => "http://foursquare.com",
:scheme => :header,
:http_method => :post,
:request_token_path => "/oauth/request_token",
:access_token_path => "/oauth/access_token",
:authorize_path => "/oauth/authorize"
})
#request_token = #consumer.get_request_token(:oauth_callback =>
"http://localhost:3001/session")
session[:request_token] = #request_token.token
session[:request_secret] = #request_token.secret
puts #request_token.token
puts #request_token.secret
# redirecting user to foursquare to authorize
#foursqrurl = #request_token.authorize_url
puts #foursqrurl
end
end
I know absolutely nothing about Oauth and this may be completely wrong, but, if http://foursquare.com is not your local machine and oauth_callback is a URL that http://foursquare.com will call when it has completed then it will be calling back to itself as its definition of localhost will be its own 127.0.0.1 i.e itself.
If I have guessed correctly here then change the :oauth_callback to your public IP Address/name.
I think #request_token = OAuth::RequestToken.new(#consumer,
session[:request_token], session[:request_secret]) is wrong.
If you already have the token and the secret, you don't really need to do the verifier thing.
You should construct it like this:
OAuth::RequestToken.from_hash(consumer, { :oauth_token => params[:oauth_token] })
access_token = request_token.get_access_token(:oauth_verifier => params[:oauth_verifier])
Or if you already have the token and the secret, you should do:
access_token = OAuth::AccessToken.from_hash(consumer, {
:oauth_token => "YOUR_TOKEN",
:oauth_token_secret => "YOUR_SECRET"
})