ruby
1class OmniauthCallbacksController < Devise::OmniauthCallbacksController 2 3 def twitter 4 callback_from(:twitter) 5 end 6 7 private 8 9 def callback_from(provider) 10 @user = User.find_for_oauth(request.env['omniauth.auth'].except("extra")) 11 12 if @user.persisted? 13 sign_in_and_redirect @user, event: :authentication 14 set_flash_message(:notice, :success, kind: "#{provider}".capitalize) if is_navigational_format? 15 16 else 17 session["devise.#{provider}_data"] = request.env['omniauth.auth'].except("extra") 18 redirect_to new_user_registration_url 19 end 20 end 21end
こちらがUser.rb モデルとなります。
ruby
1class User < ApplicationRecord 2 # Include default devise modules. Others available are: 3 # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable 4 devise :database_authenticatable, :registerable, 5 :recoverable, :rememberable, :trackable, :validatable, :omniauthable 6 7 def self.find_for_oauth(auth) 8 user = User.where(uid: auth.uid, provider: auth.provider).first 9 10 unless user 11 user = User.create( 12 uid: auth.uid, 13 provider: auth.provider, 14 email: User.dummy_email(auth), 15 password: Devise.friendly_token[0, 20], 16 user_name: auth.info.nickname, 17 ) 18 end 19 20 user 21 end 22 23 private 24 25 def self.dummy_email(auth) 26 "#{auth.uid}-#{auth.provider}@example.com" 27 end 28end 29
ここでは公開できないものの、devise.rbも以下のようになっています。
ruby
1--省略 2config.omniauth :twitter, ENV['キー'], ENV['シークレットキー'], scope: 'email', oauth_callback: "url"
ちなみに、コマンドプロンプトはこうなりました。
Started GET "/users/auth/twitter" for ::1 at 2020-07-02 00:10:47 +0900 I, [2020-07-02T00:10:47.931087 #16912] INFO -- omniauth: (twitter) Request phase initiated. Started GET "/users/auth/twitter" for ::1 at 2020-07-02 00:10:48 +0900 I, [2020-07-02T00:10:48.407058 #16912] INFO -- omniauth: (twitter) Request phase initiated. Started GET "/users/auth/twitter/callback?oauth_token=VxRj-QAAAAABFl5dAAABcwruLzI&oauth_verifier=HncO5sdRW67GjaznVwFhqA4CWYjzTpSi" for ::1 at 2020-07-02 00:10:49 +0900 I, [2020-07-02T00:10:49.663093 #16912] INFO -- omniauth: (twitter) Callback phase initiated. Processing by OmniauthCallbacksController#twitter as HTML Parameters: {"oauth_token"=>"VxRj-QAAAAABFl5dAAABcwruLzI", "oauth_verifier"=>"HncO5sdRW67GjaznVwFhqA4CWYjzTpSi"} User Load (0.8ms) SELECT `users`.* FROM `users` WHERE `users`.`uid` = '1159159785406599168' AND `users`.`provider` = 'twitter' ORDER BY `users`.`id` ASC LIMIT 1 ↳ app/models/user.rb:8:in `find_for_oauth' (0.2ms) BEGIN ↳ app/models/user.rb:11:in `find_for_oauth' User Exists? (0.6ms) SELECT 1 AS one FROM `users` WHERE `users`.`email` = BINARY '1159159785406599168-twitter@example.com' LIMIT 1 ↳ app/models/user.rb:11:in `find_for_oauth' (0.7ms) ROLLBACK ↳ app/models/user.rb:11:in `find_for_oauth' Redirected to http://localhost:3000/users/sign_up Completed 302 Found in 296ms (ActiveRecord: 2.3ms | Allocations: 4796)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。