Rails 3 - Log into another site and keep cookie in session

不问归期 提交于 2019-12-01 04:11:31

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/17005921/rails-3-log-into-another-site-and-keep-cookie-in-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!