How to fix Ruby Rack SessionId error Error: undefined class/module Rack::Session::SessionId when decoding the rack.session cookie - ruby

While writing a ruby script to decode rack session cookies and load the object using the ruby function Marshal load, I am getting the following error:
Error: undefined class/module Rack::Session::SessionId
This is my ruby script:
require 'pp'
require 'base64'
require 'uri'
require 'rack' # solves the error: Error: undefined class/module Rack::
c = gets
cookie, signature = c.split("--")
decoded = Base64.decode64(URI.decode(cookie))
begin
object = Marshal.load(decoded)
pp object
rescue ArgumentError => e
puts "Error: " + e.to_s
end
How do I fix this? I tried looking for solutions on stackoverflow but couldn't figure it out.

Thanks to Louis Nyffenegger (#snyff) who helped me with this
https://twitter.com/snyff/status/1407054131697758211?s=20
This error can be solved by creating a method stub
require 'pp'
require 'base64'
require 'uri'
require 'rack'
class Rack::Session::SessionId
end
c = gets
cookie, signature = c.split("--")
decoded = Base64.decode64(URI.decode(cookie))
begin
object = Marshal.load(decoded)
pp object
rescue ArgumentError => e
puts "Error: " + e.to_s
end

Try clearing all of the cookies for the site.
I think this works because something is causing an exception while loading the Rack::Session::SessionId class.
This type of error happens occasionally when working on Rails applications. A SyntaxError (or any other exception) inside a class definition (e.g. in a model) can then cause an undefined class/module error instead of the real error.

Related

Accessing the Receiving Object that Throws an Exception

While debugging a really strange issue with ActionMailer, I came to realize I didn't know how to access an object that was creating the exception. Not the exception, but the object itself.
begin
AppMailer.send_invoice(hostel_resident).deliver_later
flash[:success] = "Your invoice was sent successfully!"
rescue => msg
# display the system generated error message
flash[:error] = "#{msg}"
end
NoMethodError: undefined method `disposition_type' for #<Mail::UnstructuredField:0x009g71c2a68258>
This code works great to catch any exceptions and print the message.
However, how do I get ahold of the <Mail::UnstructuredField:0x009g71c2a68258> object? I'd like to be able to play around with this guy, read messages inside it, and just generally have access to it.
This has to be possible, but inspect doesn't help, cause is no use and backtrace just shows you where it happened. I need that object though, the receiver of the nonexistent method.
Thanks!
actionmailer (4.2.4)
mail (2.6.3)
Seems like you're using mail gem. This is a known issue which is already reported in the GitHub. See #851.
Try using different version of the gem, something in 2.6 series.
This seems to work, using receiver on NameError (which NoMethodError is a child of)
obj = Object.new
puts obj.to_s
begin
obj.do_something
rescue NoMethodError => e
puts e.message
puts e.receiver
end
# #<Object:0x007fa5ac84da88>
# undefined method `do_something' for #<Object:0x007fa5ac84da88>
# #<Object:0x007fa5ac84da88>
This seems to require ruby >= 2.3, to do this for < 2.3, AFAIK you have to do something like this (not tested in older rubies, but should work):
class MyNoMethodError < NoMethodError
attr_accessor :my_receiver
end
obj = Object.new
puts obj.to_s
begin
begin
obj.do_something
rescue NoMethodError => e
# rescue the exception and wrap it in the method that caused it, using `self` instead of `obj`
error = MyNoMethodError.new(e)
error.my_receiver = obj
raise error
end
rescue MyNoMethodError => c
puts c.inspect # custom exception stuff
puts c.cause.inspect # original exception stuff
puts c.my_receiver
end
# #<Object:0x007f884e846d58>
# #<MyNoMethodError: undefined method `do_something' for #<Object:0x007f884e846d58>>
# #<NoMethodError: undefined method `do_something' for #<Object:0x007f884e846d58>>
# #<Object:0x007f884e846d58>

Error in first attempt Ruby webcrawler

I am creating a basic scraper that gets the total relief amount rewarded to each state and then displays it, but I'm receiving an error I don't understand. Can you help me fix my program please?
require 'rubygems'
require 'crack'
require 'open-uri'
URL = 'http://www.recovery.gov/pages/GetXmlData.aspx?data=recipientHomeMap'
Crack::XML.parse(open(URL).read)['totals']['state'].each do |state|
puts ['id', 'awarded', 'received', 'jobs'].map{|f| state[f]}.join(', ')
end
rb:7:in ' : undefined method '[]' for nil:NilClass(NoMethodError)
Check what Crack::XML.parse(open(URL).read) return
You aren't getting anything back from Crack::XML.parse(open(URL).read)
You are trying to access values from nil hence the undefined method '[]' for nil:NilClass
Make sure you are actually getting the file first.

Ruby NoMethodError (undefined method `map') in Post Request

I'm trying to do a POST request from a ruby app and I'm getting the following error.
Here is the code:
def action_reply(token,action_id,reply_text)
require 'uri'
require 'net/http'
require 'net/https'
#reply = { 'ACTION_ID' => action_id, 'text' => reply_text }.to_json
#A token is required to do this post
#token_url = 'https://example.com/reply?oauth_token=' + token
uri = URI.parse(#token_url)
response = Net::HTTP.post_form(uri,#reply)
end
I'm getting an error in the last step that says:
NoMethodError (undefined method `map' for #<String:0x000000063798e8>)
Any idea why this is?
Thanks!
Because you're passing a string to a method expecting a hash: remove the to_json call.
Unrelated, but is it necessary to have those instance variables be instance variables?

Ruby namespacing issues

I'm attempting to build a gem for interacting w/ the Yahoo Placemaker API but I'm running into an issue. When I attempt to run the following code I get:
NameError: uninitialized constant Yahoo::Placemaker::Net
from /Users/Kyle/.rvm/gems/ruby-1.9.2-p290/gems/yahoo-placemaker-0.0.1/lib/yahoo-placemaker.rb:17:in `extract'
from (irb):4
from /Users/Kyle/.rvm/rubies/ruby-1.9.2-p290/bin/irb:16:in `<main>'
yahoo-placemaker.rb
require "yahoo-placemaker/version"
require 'json'
require 'ostruct'
require 'net/http'
module Yahoo
module Placemaker
def self.extract (text = '')
host = 'wherein.yahooapis.com'
payload = {
'documentContent' => text,
'appid' => APP_ID,
'outputType' => 'json',
'documentType' => 'text/plain'
}
req = Net::HTTP::Post.new('/v1/document')
req.body = to_url_params(payload)
response = Net::HTTP.new(host).start do |http|
http.request(req)
end
json = JSON.parse(response.body)
Yahoo::Placemaker::Result.new(json)
end
end
end
I have yet to figure out how exactly constant name resolution works in Ruby (I think the rules are a bit messy here), but from my experience it could well be that Net is looked up in the current namespace instead of the global one. Try using the fully qualified name:
::Net::HTTP::Post.new
A similar problem could occur in this line:
Yahoo::Placemaker::Result
You should replace it with either ::Yahoo::Placemaker::Result or better Result (as it lives in the current namespace).
Try requiring net/http before. Ruby is falling back to find it in the module if it isn't defined.
require 'net/http'

Convert to string/text ruby

I'm using the following code to download a page through a POST request:
require 'net/http'
require 'uri'
res = Net::HTTP.post_form(URI.parse('http://example.com'),{'post'=>'1'})
puts res.split("Date")
The URL I originally used has been replaced with example.com
It works great, but when I try to call split (last line) it returns an error:
<main>': undefined methodsplit' for # (NoMethodError)
I'm new to ruby, so I'm confused about this error.
The method you are calling returns a HTTPResponse object, so you need to leverage that object's methods to get what you want. maybe something like:
require 'net/http'
require 'uri'
res = Net::HTTP.post_form(URI.parse('http://example.com'),{'post'=>'1'})
puts res.body.split("Date")
Notice the body method.
Or, if you want to see all the data returned:
require 'net/http'
require 'uri'
res = Net::HTTP.post_form(URI.parse('http://example.com'),{'post'=>'1'})
puts res.inspect
Hope this helps!

Resources