rubycdp / ferrum

Headless Chrome Ruby API
https://ferrum.rubycdp.com
MIT License
1.74k stars 123 forks source link

authenticate current_user in ferrum browser #423

Closed yshmarov closed 10 months ago

yshmarov commented 10 months ago

I am trying to invoke Ferrum::Browser.new inside a Rails controller and access an action that requires authentication.

However it naturally brings me to/renders the sign_in page:

Screenshot 2023-12-03 at 11 15 46

I know that I could do something like this to authenticate the user

  browser.go_to "http://localhost:3000/users/sign_in"
  browser.at_css("#user_email").focus.type(current_user.email)
  browser.at_css("#user_password").focus.type(current_user.password)
  browser.at_css("input[type='submit']").click
  browser.go_to url_for(report_url(@report))

However is there a legit way to set the user in the browser?

I was thinking something like this, but it does not seem to work:

cookie = request.cookies["_myapp_session"]
browser.cookies.set(name: '_myapp_session', value: cookie, domain: 'localhost')

full code:

  def show
    respond_to do |format|
      format.html
      format.pdf do
        cookie = request.cookies["_myapp_session"]

        filename = "newfile.pdf"
        tmp = Tempfile.new(filename)
        browser = Ferrum::Browser.new
        browser.cookies.set(name: '_myapp_session', value: cookie, domain: 'localhost')
        browser.go_to url_for(report_url(@report))
        sleep(1)
        pdf = browser.pdf(path: tmp.path,
                          format: "A4".to_sym,
                          scale: 1,
                          landscape: false)
        browser.quit
        pdf_data = File.read(tmp.path)
        send_data(pdf_data, type: "application/pdf", disposition: "inline", filename: filename)
      end
    end
  end