Rhoconnect webservice login need - rhomobile

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.

Related

Getting Filter chain halted for callback_phase in cutom omniauth strategy

I am trying to implement custom strategy for linking account here is my code
require 'omniauth-oauth2'
require 'multi_json'
module OmniAuth
module Strategies
class MyStrategy < OmniAuth::Strategies::OAuth2
option :name, 'my_strategy'
args [:consumer_key, :consumer_secret]
option :consumer_key, nil
option :consumer_secret, nil
option :client_options, {
site: SITE_URL,
header: { ACCEPT_HEADERS },
request_token_url: request_token_uri,
access_token_url: access_token_uri,
authorize_url: authorizerequest_token_uri
}
option :provider_ignores_state, true
def consumer
consumer = ::OAuth::Consumer.new(options.consumer_key, options.consumer_secret, options.client_options)
end
def request_phase
binding.pry
request_token = consumer.get_request_token({:oauth_callback => callback_url}, options.request_params)
session["oauth"] ||= {}
session["oauth"][name.to_s] = {"callback_confirmed" => request_token.callback_confirmed?, "request_token" => request_token.token, "request_secret" => request_token.secret}
if request_token.callback_confirmed?
redirect request_token.authorize_url(options[:authorize_params])
else
redirect request_token.authorize_url(options[:authorize_params].merge(:oauth_callback => callback_url))
end
rescue ::Timeout::Error => e
fail!(:timeout, e)
rescue ::Net::HTTPFatalError, ::OpenSSL::SSL::SSLError => e
fail!(:service_unavailable, e)
end
def callback_phase
binding.pry
end
def build_access_token
binding.pry
token_params = {
:redirect_uri => callback_url.split('?').first,
:client_id => client.id,
:client_secret => client.secret
}
verifier = request.params['code']
client.auth_code.get_token(verifier, token_params)
end
credentials do
{ "token" => access_token.token, "secret" => access_token.secret }
end
extra do
{ "access_token" => access_token }
end
def raw_info
binding.pry
#raw_info ||= access_token
end
end
end
end
But I am getting following warning to the request phase
Filter chain halted as :require_no_authentication rendered or redirected
Because of this it going into the infinite loop (i.e. it continuously executing the callback_phase).
Can any one help tell why this is happening and how can I fix this issue.
I am using rails 4.
Thanks

How to access the token created by iOS Stripe?

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.

Not receiving paypal notifications through active merchant

I was working on an app in which I need to work with ipn, but it seems it does not work well.
I am trying to get the notification in success action and have specified the correct url in paypal sandbox.
def success
topup = current_user.topups.last
logger.debug "topup -------->"
logger.debug topup.amount.to_i
# raise request
details = EXPRESS_GATEWAY.details_for(topup.express_token)
logger.debug "details ------->"
logger.debug details.payer_id
# raise params[:payer_id]
response = EXPRESS_GATEWAY.purchase(topup.price_in_cents,{
:ip => request.remote_ip,
:token => topup.express_token,
:payer_id => details.payer_id
})
logger.debug "Response starts here --------->"
logger.debug response
if response.success?
amount = topup.amount.to_i
current_user.credits = current_user.credits.to_i + amount
current_user.save!
flash[:success] = "Thank you for the top up"
# #account_history = current_user.account_histories.build
# #account_history.update_attribute(:type => "Top Up", :details => "", :amount => amount, :user_id => current_user.id)
redirect_to current_user
notify = Paypal::Notification.new request.raw_post
logger.info "Notifying --------->"
logger.info notify
logger.info notify.status
logger.info "Notifying 2 --------->"
logger.info notify.acknowledge
logger.debug notify.status
if notify.acknowledge
logger.debug "Notifying --------->"
logger.debug notify.mc_gross
logger.debug notify.txn_id
end
else
redirect_to root_url
end
end
notify.acknowledge does not return anything (it is blank)
After banging my head for quite some time I was able to solve the issue. Posting my solution just in case anyone is stuck in the similar situation :-
One important thing is that IPN sends post data to the IPN listener so make sure you have a route defined for this.
I also had a before_filter :authenticate_user! , because of which I was getting html code 401. Had to skip before filter for notify action.
def pay_with_account
topup = Topup.find(params[:id])
response = EXPRESS_GATEWAY.setup_purchase(topup.price_in_cents,{
:ip => request.remote_ip,
:currency_code => 'GBP',
:return_url => topups_success_url(topup),
:notify_url => topups_notify_url(topup),
:cancel_return_url => topups_cancel_url(topup),
# :allow_guest_checkout => true,
:items => [{:name => "Topup", :quantity => 1,:description => "Top up my account", :amount => topup.price_in_cents}]
})
topup.update_attribute :express_token, response.token
redirect_to EXPRESS_GATEWAY.redirect_url_for(response.token)
end
This is the return url :-
def success
topup = current_user.topups.last
details = EXPRESS_GATEWAY.details_for(topup.express_token)
response = EXPRESS_GATEWAY.purchase(topup.price_in_cents,{
:ip => request.remote_ip,
:currency_code => 'GBP',
:token => topup.express_token,
:payer_id => details.payer_id
})
if response.success?
amount = topup.amount.to_i
current_user.credits = current_user.credits.to_i + amount
current_user.save!
redirect_to user_payments_path(current_user)
flash[:success] = "Your transaction was successfully completed"
else
flash[:error] = "Your transaction could not be compelted"
redirect_to user_payments_path(current_user)
end
end
This is the notify url :-
def notify
notify = Paypal::Notification.new(request.raw_post)
if notify.acknowledge
#account_history = topup.user.account_histories.build
#account_history.update_attributes(:payment_type => "Top up",:status => notify.status, :amount => notify.gross)
if params[:payer_status] == "verified"
#account_history.update_attributes(:details => "Pay Pal #{#account_history.id}")
elsif params[:payer_status] == "unverified"
#account_history.update_attributes(:details => "Credit Card #{#account_history.id}")
end
#account_history.save
end
render :nothing => true
end
routes :-
get "topups/pay_with_account"
get "topups/pay_without_account"
get "topups/success"
get "topups/cancel"
get "topups/notify"
post "topups/notify

How to use Rhodes without Rhosync or RhoConnect?

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.

Error using Xpath in Rhomobile

I am trying to parse XML using rexml Xpath, but facing error as const_missing: XPath in rhomobile application. can anyone give me the solution.
Below is the sample code:
file = File.new(file_name)
begin
require 'rexml/document'
xmldoc = REXML::Document.new(file)
names = XPath.match(xmldoc, "//MP_HOST_NAME" )
in your build.yml file:
extensions:
- rexml
if using blackberry, replace rexml with rhoxml
Assuming you've done this, replace your XPath with:
REXML::XPath.match(xmldoc, "//MP_HOST_NAME" )
Here is a sample controller I knocked to test xml parsing
I can use the get_names method in the view then to get an array of names
require 'rho/rhocontroller'
require 'rexml/document'
class WebServiceTestController < Rho::RhoController
def index
##get_result = ""
Rho::AsyncHttp.get(
:url => 'http://www.somesite.com/some_names.xml',
#:authorization => {:type => :basic, :username => 'user', :password => 'none'},
:callback => (url_for :action => :httpget_callback),
:authentication => {
:type => :basic,
:username => "xxxx",
:password => "xxxx"
},
:callback_param => "" )
render :action => :wait
end
def get_res
##get_result
end
def get_error
##error_params
end
def httpget_callback
if #params["status"] != "ok"
##error_params = #params
WebView.navigate( url_for(:action => :show_error) )
else
##get_result = #params["body"]
begin
# require "rexml/document"
##doc = REXML::Document.new(##get_result)
# puts "doc : #{doc}"
rescue Exception => e
# puts "Error: #{e}"
##get_result = "Error: #{e}"
end
WebView.navigate( url_for(:action => :show_result) )
end
end
def show_error
render :action => :error, :back => '/app'
end
def show_result
render :action => :index, :back => "/app"
end
def get_doc
##doc
end
def get_names
names = []
REXML::XPath.each( get_doc, "//name_or_whatever_you_are_looking_for") do |element|
names << element.text
end
names
end
end
ensure that rhoxml is set in the build.yml file rather than rexml this works fine and it's a little faster

Resources