Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cookie jar save to and load from file #646

Open
dsisnero opened this issue Jan 29, 2021 · 4 comments
Open

cookie jar save to and load from file #646

dsisnero opened this issue Jan 29, 2021 · 4 comments

Comments

@dsisnero
Copy link

jar = HTTP::CookieJar.new
jar.load(filename)

or

jar = HTTP::CookiJare.new(store: :mozilla, filename: 'cookies.sqlite')

I want to use another http client to start a session , (cuprite), and then when I am authenticated I want to to use http. Being able to load a cookie jar file would enable one to share sessions between different clients.

@tarcieri
Copy link
Member

The HTTP::CookieJar class comes from the http-cookie gem:

https://github.com/sparklemotion/http-cookie

@dsisnero
Copy link
Author

dsisnero commented Feb 1, 2021

I know. Can we add methods on http to save and load cookies?

@tarcieri
Copy link
Member

tarcieri commented Feb 1, 2021

The functionality to do this is already defined on the HTTP::CookieJar class:

https://www.rubydoc.info/gems/http-cookie/1.0.2/HTTP/CookieJar#save-instance_method

Are you asking for some sort of helper method that delegates to HTTP::CookieJar? Why not use the HTTP::CookieJar class directly?

Can you make a more concrete proposal for the functionality you want added? Perhaps a complete example of what you have in mind?

@ixti
Copy link
Member

ixti commented Feb 2, 2021

I'm going to work on (have some preliminray code that is not ready to be shared yet) with session alike object (I'm still sketching out API), but the very simple version (if you need this now for your own usage) will look like:

class WebBrowserAlikeClient
  attr_reader :cookies

  def initialize(&block)
    @cookies = HTTP::CookieJar.new
    @http    = block || -> { HTTP }
  end

  %i[get post].each do |verb|
    define_method(verb) { |*args, **kwargs| request(verb, *args, **kwargs) }
  end

  def request(verb, uri, headers: {}, **options)
    headers = HTTP::Headers.coerce(headers || {})
    cookies = @cookies.each(uri.to_s).map(&:to_s).join("; ")

    if cookies.empty?
      headers.delete(HTTP::Headers::COOKIE)
    else
      headers[HTTP::Headers::COOKIE] = cookies
    end

    @http.call.public_send(verb, uri, { :headers => headers, options }).tap do |res|
      response.headers.each do |k, v|
        @cookies.parse(v, res.uri) if HTTP::Headers::SET_COOKIE == k
      end
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants