4

I'm putting together a small app which will allow a user to log into a semi-popular social networking site that doesn't have a sufficient API, so I'm using the mechanize gem to automate a few functions I wanted to add for anyone to use, such as bulk messaging.

Because of the API restrictions, I'm forced to do this by pretending to be a user interacting with the http interface of the site.

The problem I'm having is once a user logs in to my site, how can I keep the cookie from the social networking site statefully in the session so they don't need to enter credentials for every page load?

I was trying to marshal the cookie from the mechanize instance but I received errors regarding mutex's not having a Marshal method.

EDIT - Solved

Turned out to be quite simple, but the documentation sure didn't help the matter, just because of incompleteness.

Here's what I did to catch the cookies and bring them back for future requests (much inbetween code and error checking excluded for brevity):

users_controller.rb

def create
  session.delete(:agent) if session[:agent]
  agent = Mechanize.new
  page = agent.get('www.socialnetwork.com/login')
  login_form = page.form
  login_form.email = params[:login][:email]
  login_form.password = params[:login][:password]
  page = agent.submit(login_form, login_form.buttons.first)
  cookies = agent.cookie_jar.store.map {|i| i}
  session[:agent] = Marshal.dump cookies
  redirect_to root_path
end

application_controller.rb

before_filter :set_agent
def set_agent
  if session[:agent]
    @agent = Mechanize.new
    cookies = Marshal.load session[:agent]
    cookies.each {|i| @agent.cookie_jar.store.add i}
  end
end
bdx
  • 3,316
  • 4
  • 32
  • 65
  • The error I'm receiving when trying to store the mechanize agent in the session is: "no _dump_data is defined for class Mutex" – bdx Jun 09 '13 at 05:20

1 Answers1

0

Don't store the agent, just the session cookie. Find the name of the cookie you want to capture. After logging in, grab it from the Mechanize cookie jar, store it in the session, and make sure it's in the cookie jar before every "API request".

davidfurber
  • 5,274
  • 1
  • 20
  • 11