Skip to content

Instantly share code, notes, and snippets.

@Ex-Ark
Created February 13, 2020 13:51
Show Gist options
  • Save Ex-Ark/a3bd3534c43ea4f22b29789bff282bb0 to your computer and use it in GitHub Desktop.
Save Ex-Ark/a3bd3534c43ea4f22b29789bff282bb0 to your computer and use it in GitHub Desktop.
Rails + Devise + Omniauth Google access_type: 'offline' + Google::Apis::Calendar
class AddTokensToUsers < ActiveRecord::Migration[6.0]
def change
add_column :users, :refresh_token, :string
end
end
Devise.setup do |config|
# ....
client_id = Rails.application.secrets[:google_client_id]
client_secret = Rails.application.secrets[:google_secret]
config.omniauth :google_oauth2, client_id, client_secret, {
access_type: 'offline'
scope: 'userinfo.email, calendar'
}
end
gem 'rails', '~> 6.0.0'
gem 'devise'
gem 'omniauth'
gem 'omniauth-google-oauth2'
gem 'google-api-client'
require "google/apis/calendar_v3"
class GoogleCalendarService
SCOPE = Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY
def initialize(current_user)
configure_service(current_user)
end
def call
calendar_id = "primary"
response = @calendar_api.list_events(calendar_id,
max_results: 10,
single_events: true,
order_by: "startTime",
time_min: DateTime.now.rfc3339)
end
private
def configure_service(current_user)
creds = Google::Auth::UserRefreshCredentials.new client_id: Rails.application.secrets[:google_client_id],
client_secret: Rails.application.secrets[:google_secret],
scope: SCOPE,
refresh_token: current_user.refresh_token
creds.fetch_access_token!
@calendar_api = Google::Apis::CalendarV3::CalendarService.new
@calendar_api.authorization = creds
end
end
module Users
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
hash = request.env['omniauth.auth']
resource = resource_class.find_by(email: auth_hash.info.email)
if resource
resource.attributes = {provider: hash.provider, uid: hash.uid, last_login: DateTime.now.in_time_zone}
# refresh token is only sent once by google (first connection), next time it will be null
resource.attributes = {refresh_token: hash.credentials.refresh_token} if hash.credentials.refresh_token
resource.save
sign_in(resource)
redirect_to root_path
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment