zquestz / omniauth-google-oauth2

Oauth2 strategy for Google
1.46k stars 414 forks source link

google-oauth2 + devise :: service.list_user_labels user_id - error - Google::Apis::ClientError: Request had insufficient authentication scopes #407

Closed momwhocode closed 2 years ago

momwhocode commented 3 years ago

Error - Google::Apis::ClientError: insufficientPermissions: Request had insufficient authentication scopes.

Facing error - at line result = service.list_user_labels user_id in dashboards_controller.rb

Following are my files.

devise.rb

config.omniauth :google_oauth2, client_id, client_secret

users/omniauth_callbacks_controller.rb

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def google_oauth2
    #create user

    if user.present?
      flash[:success] = t 'devise.omniauth_callbacks.success', kind: 'Google'
      sign_in_and_redirect user, event: :authentication
    else
      flash[:alert] = t 'devise.omniauth_callbacks.failure', kind: 'Google', reason: "#{auth.info.email} is not authorized."
      redirect_to new_user_session_path
    end
  end
end

dashboards_controller.rb

require 'google/api_client/client_secrets.rb'
require 'google/apis/gmail_v1'
require 'googleauth'

class DashboardsController < ApplicationController
  def show
        # Initialize the API
        service = Google::Apis::GmailV1::GmailService.new
        service.authorization = google_secret.to_authorization
        service.authorization.refresh!
        # Show the user's labels
        user_id = current_user.uid
        result = service.list_user_labels user_id
        puts "Labels:"
        #puts "No labels found" if result.labels.empty?
        #result.labels.each { |label| puts "- #{label.name}" }
  end

  private

      def google_secret
            scope = "https://www.googleapis.com/auth/gmail.labels"

            Google::APIClient::ClientSecrets.new(
          { "web" =>
            { "access_token" => current_user.token,
              "refresh_token" => current_user.refresh_token,
              "client_id" => client_id,
              "client_secret" => client_secret,
              "scope" => scope
            }
          }
        )
      end
end
zquestz commented 3 years ago

You will definitely need to add some scopes to the login. Ideally you should be getting all the scopes you need when you initialize the plugin. My guess is you are just missing the needed scope for that call.

config.omniauth :google_oauth2, client_id, client_secret