Rails Google cloud print

2019-08-17 04:27发布

问题:

I am setting google cloud printing on my rails app with cloudprint following this example.

This is the setup controller:

 class SetupController < ApplicationController
      protect_from_forgery with: :exception

      def show
         @google_client = CloudPrint::Client.new(
           client_id: 'xxxxxxxxxx',
           client_secret: 'xxxxxxxxxxx'
         )

         if Rails.application.secrets.google_refresh_token
           # Actually nothing..
         elsif params[:code]
           @token = @google_client.oauth_client.auth_code.get_token(params[:code], redirect_uri: root_url)
         else
           redirect_to @google_client.auth.generate_url(root_url)
         end
      end
     end

And this is setup/show view:

<%= @token.refresh_token %>

By visiting the page I get the consent screen to select google account and give permission to printers.

In my application controllers I have:

def authenticate_google_cloud
    @google_client = CloudPrint::Client.new(
      refresh_token: Rails.application.secrets.google_refresh_token,
      client_id: 'xxxxxxxxxx',
      client_secret: 'xxxxxxxxxxxxxxxx'
    )
 end

Then printers_controller:

  @printers = @google_client.printers.all

When I try to list printers I get error:

RuntimeError (A refresh_token is not available)

as I assume the refresh token is not stored in secrets. As I am on rails 5.2 should I store it in credentials instead? Or if I need to store it in secrets how should I do it? This part confuses me..

I tried also to change in setup controller the line:

if Rails.application.secrets.google_refresh_token

to

if refresh_token

and in application controller the line:

refresh_token: Rails.application.secrets.google_refresh_token,

to

refresh_token: 'refresh_token'

but this returns:

OAuth2::Error (invalid_grant: Bad Request
{
  "error": "invalid_grant",
  "error_description": "Bad Request"
}):

How can I get it to work?