fineuploader multi-part rails - ruby-on-rails

I am trying to get multi-part upload working with rails as server to sign the requests.
Below is the code snippet. signature.endpoint is create action.
require 'base64'
require 'openssl'
require 'digest/sha1'
class WelcomeController < ApplicationController
skip_before_action :verify_authenticity_token
def success
render json: params
end
def index
end
def create
if(params[:headers])
signature = OpenSSL::HMAC.digest(
OpenSSL::Digest::Digest.new('sha1'),
key,
params[:headers].to_s).gsub("\n", "")
params[:signature]= signature
else
conditions = params[:conditions]
conds = [
{"acl" => "private"},
{"bucket" => conditions[1][:bucket]},
{"Content-Type" => conditions[2]["Content-Type"]},
{"success_action_status" => "200"},
{"key" => conditions[4][:key]},
{"x-amz-meta-qqfilename" => conditions[5]["x-amz-meta-qqfilename"]}
]
policy = Base64.encode64({ "expiration" => params[:expiration],
"conditions" => conds
}.to_json).
gsub("\n","")
signature = Base64.encode64(
OpenSSL::HMAC.digest(
OpenSSL::Digest::Digest.new('sha1'),
key, policy)
).gsub("\n","")
params[:signature]= signature
params[:policy] = policy
end
render :json => params, :status => 200 and return
end
end
This works fine for files < 5mb in size, i.e. else part of if-else block.
But, request is not signed properly when the file size > 5mb.
Please suggest what am I missing here.

Soln:
require 'base64'
require 'openssl'
require 'digest/sha1'
class WelcomeController < ApplicationController
skip_before_action :verify_authenticity_token
def success
render json: params
end
def index
end
def create
if(params[:headers])
logger.info params[:welcome][:headers]
signature = Base64.encode64(OpenSSL::HMAC.digest(
OpenSSL::Digest::Digest.new('sha1'),
key,
params[:welcome][:headers])).gsub("\n", "")
params[:signature]= signature
else
conditions = params[:conditions]
conds = [
{"acl" => "public-read"},
{"bucket" => conditions[1][:bucket]},
{"Content-Type" => conditions[2]["Content-Type"]},
{"success_action_status" => "200"},
{"key" => conditions[4][:key]},
{"x-amz-meta-qqfilename" => conditions[5]["x-amz-meta-qqfilename"]}
]
policy = Base64.encode64({ "expiration" => params[:expiration],
"conditions" => conds
}.to_json).
gsub("\n","")
signature = Base64.encode64(
OpenSSL::HMAC.digest(
OpenSSL::Digest::Digest.new('sha1'),
key, policy)
).gsub("\n","")
params[:signature]= signature
params[:policy] = policy
end
logger.info signature
render :json => params, :status => 200 and return
end
end

Related

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.

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 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

401 Unauthorized for foursquare OAuth

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"
})

Resources