Rails dalli gem, load session with session id - session

is there a way to get the session info if i know the session id when dalli_store is used as the session store???r

Into config/initializers/session_store.rb add
mem_options = {
:key => '_your_session_key',
:secret => ....
}
ActionController::Dispatcher.middleware.insert_before(ActionController::Base.session_store, CMS::FlashSessionCookieMiddleware, mem_options[:key])
And your flash_session_cookie_middleware.rb should contain:
require 'rack/utils'
module CMS
class FlashSessionCookieMiddleware
def initialize(app, session_key = '_session_id')
#app = app
#session_key = session_key
end
def call(env)
if env['HTTP_USER_AGENT'] =~ /^(Adobe|Shockwave) Flash/
params = ::Rack::Utils.parse_query(env['QUERY_STRING'])
env['HTTP_COOKIE'] = [#session_key, params[#session_key]].join('=').freeze unless params[#session_key].nil?
end
#app.call(env)
end
end
end

Related

How do I access the Magento REST API with Ruby?

I want to start working with Magento's REST API, but I can't seem to get it working.
To start with I need to get access tokens, here's what I'm trying:
require 'oauth'
#consumer = OAuth::Consumer.new("4200100753b2c8b03bde1f5b062c5a80", "c06abdcb734c85dfd7bb115c6a67ae4d", {:site=>"http://178.62.173.99/"})
#request_token = #consumer.get_request_token
# => oauth-0.4.7/lib/oauth/consumer.rb:216:in `token_request': 404 Not Found (OAuth::Unauthorized)
But I keep getting a 404 error.
What should I try next?
Here's a Ruby module I've written to create an access token for the Magento REST API:
module Token
def create_consumer
OAuth::Consumer.new(
CONSUMER_KEY,
CONSUMER_SECRET,
:request_token_path => '/oauth/initiate',
:authorize_path=>'/admin/oauth_authorize',
:access_token_path=>'/oauth/token',
:site => URL
)
end
def request_token(args = {})
args[:consumer].get_request_token(:oauth_callback => URL)
end
def get_authorize_url(args = {})
args[:request_token].authorize_url(:oauth_callback => URL)
end
def authorize_application(args = {})
m = Mechanize.new
m.get(args[:authorize_url]) do |login_page|
auth_page = login_page.form_with(:action => "#{URL}/index.php/admin/oauth_authorize/index/") do |form|
form.elements[1].value = ADMIN_USERNAME
form.elements[2].value = ADMIN_PASSWORD
end.submit
authorize_form = auth_page.forms[0]
#callback_page = authorize_form.submit
end
#callback_page.uri.to_s
end
def extract_oauth_verifier(args = {})
callback_page = "#{args[:callback_page]}".gsub!("#{URL}/?", '')
callback_page_query_string = CGI::parse(callback_page)
callback_page_query_string['oauth_verifier'][0]
end
def get_access_token(args = {})
args[:request_token].get_access_token(:oauth_verifier => args[:oauth_verifier])
end
def save_tokens_to_json(args = {})
auth = {}
auth[:time] = Time.now
auth[:token] = args[:access_token].token
auth[:secret] = args[:access_token].secret
File.open("#{args[:path]}#{args[:filename]}.json", 'w') {|f| f.write(auth.to_json)}
auth
end
def get_new_access_tokens
new_consumer = self.create_consumer
new_request_token = self.request_token(consumer: new_consumer)
new_authorize_url = self.get_authorize_url(request_token: new_request_token)
authorize_new_application = self.authorize_application(authorize_url: new_authorize_url)
extract_new_oauth_verifier = self.extract_oauth_verifier(callback_page: authorize_new_application)
new_access_token = self.get_access_token(request_token: new_request_token, oauth_verifier: extract_new_oauth_verifier)
save_tokens_to_json(filename: 'magento_oauth_access_tokens', path: '/', access_token: new_access_token)
return 'Successfully obtained new access tokens.'
end
end
Run #get_new_access_tokens to get an access token.
Don't forget to define the following variable:
CONSUMER_KEY
CONSUMER_SECRET
URL
ADMIN_USERNAME
ADMIN_PASSWORD
Check out mage on rails. It should work right out of the box. Check out this page for annotated ruby code showcasing the oauth flow

Standardizing api responses in a modular Sinatra application

I'm developing an api as a modular Sinatra web application and would like to standardize the responses that are returned without having to do so explicitly. I thought this could be achieved by using middleware but it fails in most scenarios. The below sample application is what I have so far.
config.ru
require 'sinatra/base'
require 'active_support'
require 'rack'
class Person
attr_reader :name, :surname
def initialize(name, surname)
#name, #surname = name, surname
end
end
class MyApp < Sinatra::Base
enable :dump_errors, :raise_errors
disable :show_exceptions
get('/string') do
"Hello World"
end
get('/hash') do
{"person" => { "name" => "john", "surname" => "smith" }}
end
get('/array') do
[1,2,3,4,5,6,7, "232323", '3245235']
end
get('/object') do
Person.new('simon', 'hernandez')
end
get('/error') do
raise 'Failure of some sort'
end
end
class ResponseMiddleware
def initialize(app)
#app = app
end
def call(env)
begin
status, headers, body = #app.call(env)
response = {'status' => 'success', 'data' => body}
format(status, headers, response)
rescue ::Exception => e
response = {'status' => 'error', 'message' => e.message}
format(500, {'Content-Type' => 'application/json'}, response)
end
end
def format(status, headers, response)
result = ActiveSupport::JSON.encode(response)
headers["Content-Length"] = result.length.to_s
[status, headers, result]
end
end
use ResponseMiddleware
run MyApp
Examples (in JSON):
/string
Expected: {"status":"success","data":"Hello World"}
Actual: {"status":"success","data":["Hello World"]}
/hash (works)
Expected: {"status":"success","data":{"person":{"name":"john","surname":"smith"}}}
Actual: {"status":"success","data":{"person":{"name":"john","surname":"smith"}}}
/array
Expected: {"status":"success","data": [1,2,3,4,5,6,7,"232323","3245235"]}
Actual: {"status":"error","message":"wrong number of arguments (7 for 1)"}
/object
Expected: {"status":"success","data":{"name":"simon","surname":"hernandez"}}
Actual: {"status":"success","data":[]}
/error (works)
Expected: {"status":"error","message":"Failure of some sort"}
Actual: {"status":"error","message":"Failure of some sort"}
If you execute the code, you will see that /hash and /error give back the required responses, but the rest do not. Ideally, I would not like to change anything in the MyApp class. It's currently being built on top of Sinatra 1.3.3, ActiveSupport 3.2.9 and Rack 1.4.1.
With some help from #sinatra on irc.freenode.org, I managed to get it down to what I want. I added the following to MyApp:
def route_eval
result = catch(:halt) { super }
throw :halt, {"result" => result}
end
I then changed the following line in ResponseMiddleware:
response = {'status' => 'success', 'data' => body}
to
response = {'status' => 'success', 'data' => body["result"]}
and all my test cases passed.

Ruby: Thor and Httparty

I am trying to use HTTParty in my class FindXYZ extending Thor but it is not working. All I wish to do is use HTTParty get to query couchdb in my method xyz
When I try to run I see error cannot find get
require 'json'
require 'httparty'
require 'thor'
class FindXyz < Thor
include Thor::Actions
include HTTParty
headers 'Accept' => 'application/json'
server = '192.168.5.50:5984'
user = 'uname'
password = 'passo'
couchdb_url = "http://#{user}:#{password}##{server}"
basic_auth user, password
base_uri couchdb_url
default_params :output => 'json'
format :json
desc "xyz", "Find scenarios that contains SSL"
method_option :name, :aliases => "-t", :required => true
method_option :location, :aliases => "-s",:required => true
def xyz
name = options[:name]
loc = options[:location]
file_path = File.join(loc, name)
t_json = JSON.parse(File.read(file_path))
t_json["ids"].each do |temp|
path_to_doc = "/test123/#{temp}"
response = get(path_to_doc)
puts "Found => #{temp}" if response.to_s.include?('Birdy')
end #close the loop
end #close the method xyz
end #close class
Try it this way from outside the class
puts FindXyz.get('....').inspect
and HTTParty.get(...) inside FinXyz class

Connect Rails 3 to Salesforce/Any other App via OAuth

Has anybody connected to Salesforce through Rails 3 App via oauth? Could you please post code for doing same. I am trying to same but I get some error below is my code
def oauth_client
consumer_key = '....'
consumer_secret = '....'
oauth_options = {
:site => 'https://login.salesforce.com',
:scheme => :body,
:request_token_path => '/_nc_external/system/security/oauth/RequestTokenHandler',
:authorize_path => '/setup/secur/RemoteAccessAuthorizationPage.apexp',
:access_token_path => '/_nc_external/system/security/oauth/AccessTokenHandler',
}
OAuth::Consumer.new consumer_key, consumer_secret, oauth_options
end
def oauth_redirect_uri
uri = URI.parse(request.url)
uri.path = '/sfdc/oauth_callback'
uri.query = nil
# uri = "http://localhost:3000/sfdc/oauth_callback"
uri.to_s
end
def oauth_connect
consumer_key = '...' # from SalesForce
consumer = oauth_client
request_t = consumer.get_request_token
redirect_to request_t.authorize_url(
:redirect_uri => oauth_redirect_uri,
:oauth_consumer_key => consumer_key
)
end
def oauth_callback
access = request_t.get_access_token :oauth_verifier => params[:oauth_verifier]
p access
render :text => access.token
end
Error undefined method get_access_token for #<ActionDispatch::Request:0x12b79f370>. the request variable is nil here. How do I get it back?
The rforce gem has quite a bit of an example that I pasted below. However you might just want to use rforce instead of rolling your own.
def init_server(url)
#url = URI.parse(url)
if (#oauth)
consumer = OAuth::Consumer.new \
#oauth[:consumer_key],
#oauth[:consumer_secret],
{
:site => url,
:proxy => #proxy
}
consumer.http.set_debug_output $stderr if show_debug
#server = OAuth::AccessToken.new \
consumer,
#oauth[:access_token],
#oauth[:access_secret]
class << #server
alias_method :post2, :post
end
else
#server = Net::HTTP.Proxy(#proxy).new(#url.host, #url.port)
#server.use_ssl = #url.scheme == 'https'
#server.verify_mode = OpenSSL::SSL::VERIFY_NONE
# run ruby with -d or env variable SHOWSOAP=true to see SOAP wiredumps.
#server.set_debug_output $stderr if show_debug
end
end

refactoring rails3 models with use with an external model API

How could I optimize (refactor) this non activerecord based model in rails3 that i have created.?
application.rb contains this:
CS = CloudServers::Connection.new(:username => '<hidden>', :api_key => '<hidden>')
cloudserver.rb (model) contains this:
class Cloudserver
# extend ActiveModel::Naming
attr_reader :id
attr_reader :name
attr_reader :image_id
attr_reader :flavor_id
attr_reader :status
attr_reader :progress
attr_reader :host_id
def initialize(id,name,image_id,flavor_id,status,progress,host_id)
#id = id
#name = name
#image_id = image_id
#flavor_id = flavor_id
#status = status
#progres = progress
#host_id = host_id
end
def self.all
server = CS.servers.map { |i|
new(i[:id],i[:name],i[:imageId],i[:flavorId],i[:status],i[:progress],i[:hostId])
# new(i)
}
end
def self.find(param)
all.detect { |l| l.id == param.to_i } || raise(ActiveRecord::RecordNotFound)
end
# def self.new
# server = CS.create_server(:name => "BOOYA", :imageId => 49, :flavorId => 2, :metadata => {'Luke' => 'Awesome'})
# end
end
FYI i am trying to build rails models for this api:
https://github.com/rackspace/ruby-cloudservers
should I bother or just have the controllers access the CS Object directly
Just for the sake of refactoring, here's a shorter way of writing the same class
class Cloudserver < Struct.new(:id, :name, :image_id, :flavor_id, :status, :progress, :host_id)
class << self
def all
server = CS.servers.map { |i|
new(i[:id],i[:name],i[:imageId],i[:flavorId],i[:status],i[:progress],i[:hostId])
}
end
def find
all.detect { |l| l.id == param.to_i } || raise(ActiveRecord::RecordNotFound)
end
end
end

Resources