teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

試してみたことを追記しました

2018/10/03 02:15

投稿

yamady
yamady

スコア176

title CHANGED
@@ -1,1 +1,1 @@
1
- ユーザー紐づくGoogleカレンダーの情報を取得したい(rails)
1
+ ログイン時にGoogleカレンダーの予定を取得したいです(rails)
body CHANGED
@@ -3,132 +3,71 @@
3
3
  Ruby on RailsでGoogle認証したユーザーのカレンダー情報を半年分取得できるような仕様を実装したいと考えています。ユーザー登録したときに、これを実行できればと考えているのですが、下記のエラーが出てしまい実行できません。
4
4
 
5
5
  ```
6
- NoMethodError in SessionsController#create
6
+ uninitialized constant SessionsController::Google
7
- undefined method `input_calendar' for #<Class:0x007fe5214385b0>
8
7
  ```
9
8
 
10
9
  ユーザーはGoogle認証で取ってきていますが、deviseは使っていません。
11
10
  カレンダーは、ユーザーと1対多で紐付く形で格納していきたいと考えています。
12
11
 
13
12
  下記のサイトを参考に作りました。
14
- [https://qiita.com/iron-breaker/items/2440c4ab41a482b1b096](https://qiita.com/iron-breaker/items/2440c4ab41a482b1b096)
13
+ [https://qiita.com/PharaohKJ/items/ba2a226a2c8173c4bb41](https://qiita.com/PharaohKJ/items/ba2a226a2c8173c4bb41)
15
14
 
16
- ### ソースコード
15
+ まず、Google api clientが正常に動いていないと考え
16
+ [こちらの記事](https://web-salad.hateblo.jp/entry/2014/06/28/213040)を参考に再度goggle client api のgemをインストールして入れ直してみたのですが、やはりうまくいっていません。
17
17
 
18
- カレンダーのモデル(calendar.rb)
19
- ```ruby
18
+ ### 開発環境
19
+ Mac
20
+ 'rails', '~> 5.2.1'
21
+ 'google-api-client', '~> 0.11'
20
- class Calendar < ApplicationRecord
22
+ 'omniauth-google-oauth2'
21
- belongs_to :user
22
23
 
23
- def input_calendar
24
- # Initialize OAuth 2.0 client
25
- # authorization
24
+ ### ソースコード
26
- client = Google::APIClient.new(:application_name => '')
27
- client.authorization.client_id = ENV['GOOGLE_CLIENT_ID']
28
- client.authorization.client_secret = ENV['GOOGLE_CLIENT_SECRET']
29
- client.authorization.scope = "https://www.googleapis.com/auth/calendar"
30
- client.authorization.refresh_token = current_user.refresh_token
31
- client.authorization.access_token = current_user.access_token
32
25
 
33
- cal = client.discovered_api('calendar', 'v3')
26
+ > /config/omniauth.rb
34
27
 
35
- # イベント取得月の確認
28
+ ```Ruby
36
- printf("カレンダーを表示する年(20XX):")
29
+ Rails.application.config.middleware.use OmniAuth::Builder do
37
- year = gets.strip.to_i
38
- printf("カレンダーを表示する月(1-12):")
39
- month = gets.strip.to_i
30
+ provider :google_oauth2,
40
-
41
- # 時間を格納
42
- time_min = Time.utc(year, month, 1, 0).iso8601
43
- time_max = Time.utc(year, month, 31, 0).iso8601
44
-
45
- # イベントの取得
46
- params = {'calendarId' => 'primary',
31
+ Rails.application.credentials.google[:google_client_id],
47
- 'orderBy' => 'startTime',
32
+ Rails.application.credentials.google[:google_client_secret],
48
- 'timeMax' => time_max,
33
+ {
49
- 'timeMin' => time_min,
34
+ :provider_ignores_state => true,
35
+ image_size: 150,
36
+ scope: %w(https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/calendar).join(' '),
37
+ prompt: 'consent',
50
- 'singleEvents' => 'True'}
38
+ access_type: 'offline'
51
-
52
- result = client.execute(:api_method => cal.events.list,
53
- :parameters => params)
54
-
55
- events.each do |event|
56
- calendar.startTime = event.start.date
57
- calendar.endTime = event.end.date
58
- calendar.summary = event.summary
59
- end
39
+ }
60
- end
61
40
  end
62
41
  ```
63
42
 
64
- セッションコントローラー
43
+ > app/controllers/sessions_controller.rb
65
- ```ruby
44
+ ```Ruby
66
45
  class SessionsController < ApplicationController
67
- def new
68
- end
46
+ ・・・
69
-
70
47
  def create
71
- user = User.from_omniauth(request.env["omniauth.auth"])
48
+ @user = User.from_omniauth(request.env["omniauth.auth"])
72
- calendar = Calendar.input_calendar
49
+ secrets = Google::APIClient::ClientSecrets.new(
73
- if user.save
50
+ web: {
74
- session[:user_id] = user.id
51
+ access_token: @user.credentials.token,
75
- redirect_to root_path
76
- else
77
- redirect_to new_session_path
52
+ refresh_token: @user.credentials.refresh_token,
53
+ client_id: Rails.application.credentials.google[:google_client_id],
54
+ client_secret: Rails.application.credentials.google[:google_client_secret]
78
- end
55
+ }
79
- end
56
+ )
80
57
 
81
- def destroy
58
+ cal_service = Google::Apis::CalendarV3::CalendarService.new
82
- session[:user_id] = nil
59
+ cal_service.authorization = secrets.to_authorization
83
- redirect_to new_session_path
60
+ @calendar_list = cal_service.list_calendar_lists
84
- end
85
- end
86
- ```
87
61
 
88
- ユーザーモデル
89
- ```Ruby
62
+ if @user.save
90
- class User < ApplicationRecord
63
+ session[:user_id] = @user.id
91
- has_many :calendars
64
+ render json: @calendar_list
92
-
93
- def self.from_omniauth(auth)
65
+ else
94
- where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
95
- user.provider = auth.provider
96
- user.uid = auth.uid
97
- user.name = auth.info.name
98
- user.email = auth.info.email
99
- user.image = auth.info.image
100
- user.access_token = auth.credentials.token
101
- user.refresh_token = auth.credentials.refresh_token
66
+ render json: "fail to login.\n", status: 500
102
- user.oauth_expires_at = Time.at(auth.credentials.expires_at)
103
- return user
104
67
  end
105
68
  end
106
- end
69
+ ・・・
107
70
  ```
108
71
 
109
- 認証(omniauth.rb)
110
- ```Ruby
111
- Rails.application.config.middleware.use OmniAuth::Builder do
112
- provider :google_oauth2,
113
- ENV['GOOGLE_CLIENT_ID'],
114
- ENV['GOOGLE_CLIENT_SECRET'],
115
- {
116
- scope: "https://www.googleapis.com/auth/userinfo.email,
117
- https://www.googleapis.com/auth/userinfo.profile,
118
- https://www.googleapis.com/auth/calendar",
119
- prompt: "select_account",
120
- access_type: "offline"
121
- }
122
- end
123
- ```
124
-
125
- アプリケーションコントローラー
126
- ```Ruby
127
- class ApplicationController < ActionController::Base
72
+ Googleカレンダーを取得してくるアクションをメソッド化して、別のパターンでも取ってこれるようにするのが理想です。
128
- helper_method :current_user
129
-
130
- def current_user
131
- User.find(session[:user_id]) if session[:user_id]
73
+ 欲しい情報は、各イベントの「開始日時」、「終了日時」のみです。すみませんが、おたすけくださいませ。
132
- end
133
- end
134
- ```