質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Devise

Deviseとは、Ruby-on-Railsの認証機能を追加するプラグインです。

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Twitter

Twitterは、140文字以内の「ツイート」と呼ばれる短文を投稿できるサービスです。Twitter上のほぼ全ての機能に対応するAPIが存在し、その関連サービスが多く公開されています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

ログイン

ログインは、ユーザーがコンピューターシステムにアクセスするプロセスの事を呼びます。

Q&A

0回答

562閲覧

Twitter認証を、deviseを用いたomniauthで実装したいが、ログイン出来ない

3dmagicball

総合スコア6

Devise

Deviseとは、Ruby-on-Railsの認証機能を追加するプラグインです。

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Twitter

Twitterは、140文字以内の「ツイート」と呼ばれる短文を投稿できるサービスです。Twitter上のほぼ全ての機能に対応するAPIが存在し、その関連サービスが多く公開されています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

ログイン

ログインは、ユーザーがコンピューターシステムにアクセスするプロセスの事を呼びます。

1グッド

2クリップ

投稿2019/12/25 13:04

現状

RailsでWebサイトを構築しており、
ユーザー認証システムで、deviseを用いております。

そこに、Twitter認証を連携させるべく、omniauthを使用を考えております。

Twitter側での登録などは完了したことで、
ユーザー情報自体はDBに格納されるものの、
その後のログインに失敗してしまいます。
(TOPページに遷移し、ログイン出来ていない状態です)

やりたいこと

devise,omniauthを用いたtwitter認証でのログインです。
何が原因で、ログイン出来ていないのか教えていただきたいです。

値について

binding.pryで検証したところ、
@userは値が代入されており、
current_userはnil となっている状態です。

※@userにはしっかりとprovider twitterとなったアカウントが登録されております。

また普通のdeviseログインでは、
@user,current_userともに値は代入されております。

以下ソースコード

該当箇所と思われる部分のソースコードを記載します

registrations_controller.rb

Ruby

1# frozen_string_literal: true 2# frozen_string_literal: true 3 4class Users::RegistrationsController < Devise::RegistrationsController 5 # before_action :configure_sign_up_params, only: [:create] 6 before_action :configure_account_update_params, only: [:update] 7 before_action :configure_sign_up_params, only: [:create] 8 9 # GET /resource/sign_up 10 def new 11 super 12 end 13 14 # POST /resource 15 def create 16 #bypass_sign_in() 17 params[:user][:gender] = params[:user][:gender].to_i 18 super 19 #binding.pry 20 end 21 22 # GET /resource/edit 23 def editheroku certs:auto 24 super 25 end 26 27 # PUT /resource ここいじり中 28 def update 29 current_user.update_attributes(account_update_params) 30 if current_user.save 31 redirect_to root_path, notice: 'プロフィールを更新しました' 32 else 33 render "edit" 34 end 35 end 36 37 # DELETE /resource 38 def destroy 39 super 40 end 41 42 # GET /resource/cancel 43 # Forces the session data which is usually expired after sign 44 # in to be expired now. This is useful if the user wants to 45 # cancel oauth signing in/up in the middle of the process, 46 # removing all OAuth session data. 47 def cancel 48 super 49 end 50 51 protected 52 53 # If you have extra params to permit, append them to the sanitizer. 54 def configure_sign_up_params 55 devise_parameter_sanitizer.permit(:sign_up, keys: [:attribute]) 56 end 57 58 # If you have extra params to permit, append them to the sanitizer. 59 #編集するやつ 60 def configure_account_update_params 61 devise_parameter_sanitizer.permit(:account_update, keys: [:image,:birthday,:content,:email]) 62 devise_parameter_sanitizer.permit(:account_update, keys: [:attribute]) 63 end 64 65 # The path used after sign up. 66 def after_sign_up_path_for(resource) 67 super(resource) 68 end 69 70 # The path used after sign up for inactive accounts. 71 def after_inactive_sign_up_path_for(resource) 72 super(resource) 73 end 74 75 #gender保存用 76 def configure_sign_up_params 77 devise_parameter_sanitizer.permit(:sign_up, keys: [:gender]) 78 devise_parameter_sanitizer.permit(:sign_up, keys: [:birthday]) 79 devise_parameter_sanitizer.permit(:sign_up, keys: [:content]) 80 devise_parameter_sanitizer.permit(:sign_up, keys: [:image]) 81 82 end 83 84end

omniauth_callbacks_controller.rb

Ruby

1# frozen_string_literal: true 2 3class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController 4 def facebook 5 callback_from :facebook 6 end 7 8 def twitter 9 callback_from :twitter 10 end 11 12 private 13 14 def callback_from(provider) 15 provider = provider.to_s 16 17 # # Facebook上でメール使用を許可しているかの分岐 18 # if request.env['omniauth.auth'].info.email.blank? 19 # redirect_to '/users/auth/facebook?auth_type=rerequest&scope=email' 20 # end 21 22 @user = User.find_for_oauth(request.env['omniauth.auth']) 23 binding.pry 24 25 #ここでメールアドレスでの分岐が必要 26 if @user.persisted? 27 # こっちで進んでいる 28 # flash[:notice] = I18n.t('devise.omniauth_callbacks.success', kind: provider.capitalize) 29 # sign_in_and_redirect @user, event: :authentication 30 sign_in_and_redirect rooms_path, event: :authentication 31 32 else 33 session["devise.#{provider}_data"] = request.env['omniauth.auth'].except("extra") 34 redirect_to new_user_registration_url 35 end 36 37 end 38 39 def after_sign_in_path_for(resource) 40 #リダイレクトしたいパス 41 # @user 42 root_path 43 end 44 45end 46

application_controller.rb

Ruby

1class ApplicationController < ActionController::Base 2 protect_from_forgery with: :exception 3 4 #以下user-parameterで使用 5 before_action :configure_permitted_parameters, if: :devise_controller? 6 #before_action :set_current_user 7 8 protected 9 10 def configure_permitted_parameters 11 devise_parameter_sanitizer.permit(:sign_up, keys: [:name]) 12 devise_parameter_sanitizer.permit(:account_update, keys: [:name]) 13 end 14 15end
#require "message.rb" class UsersController < ApplicationController #下のやつもしかしたら場所違うかも # twitter用ログインで一度消す before_action :authenticate_user!, only: [:show,:message_room_id] #before_action :message_params, only: [:show] def new end #ここからはdeviseとは別用で記載(eventsで使用) def index @users = User.paginate(page: params[:page]) end def show @user = User.find(params[:id]) #@events = @user.events.paginate(page: params[:page]) @q = Event.ransack(params[:q]) @events = @q.result(distinct: true).paginate(page: params[:page]).where(user_id: @user.id) #message用 #ログインユーザー @currentUserEntry=Entry.where(user_id: current_user.id) #その画面のユーザー @userEntry=Entry.where(user_id: @user.id) if @user.id == current_user.id else @currentUserEntry.each do |cu| @userEntry.each do |u| if cu.room_id == u.room_id @isRoom = true @roomId = cu.room_id end end end #初なら、部屋とエントリーを作る! if @isRoom else @room = Room.new @entry = Entry.new end end end #ここから3つはdevise用記載 #絶対書いちゃだめ!!書くと上書きされてしまう! # def user_signed_in? # end # def current_user # end private #これでいいかな # def message_params # params.require(:message).permit(:content,:from_id,:to_id,:room_id) # end end

User.rb

Ruby

1class User < ApplicationRecord 2 has_many :events, dependent: :destroy 3 has_many :messages, dependent: :destroy 4 has_many :entries, dependent: :destroy 5 6 7 validate :image_size 8 9 10 # Include default devise modules. Others available are: 11 # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable 12 devise :database_authenticatable, :registerable,:confirmable, 13 :recoverable, :rememberable, :validatable, :omniauthable 14 15 def feed 16 #Event.where("user_id = ?") 17 Event.where("user_id = @user.id") 18 end 19 20 #enumの定義 gender 21 enum gender: {男性: 0,女性: 1} 22 23 24 #画像のアップロード 25 mount_uploader :image, ImageUploader 26 27 # アップロードされた画像のサイズをバリデーションする 28 def image_size 29 if image.size > 20.megabytes 30 errors.add(:image, "画像サイズが大きすぎます。20MB以内に変更してください") 31 end 32 end 33 34 35 36 #twitter認証 37 def self.find_for_oauth(auth) 38 user = User.where(uid: auth.uid, provider: auth.provider).first 39 40 unless user 41 #実際にFBから引っ張ったユーザーを認識してる 42 user = User.create( 43 uid: auth.uid, 44 provider: auth.provider, 45 email: User.dummy_email(auth), 46 name: auth.info.name, 47 password: Devise.friendly_token[0, 20], 48 image: auth.info.image 49 ) 50 end 51 52 user 53 end 54 55 private 56 57 def self.dummy_email(auth) 58 "#{auth.uid}-#{auth.provider}@example.com" 59 end 60 61end 62

_links.html.erb

Ruby

1 2<%- if controller_name != 'sessions' %> 3 <%= link_to "既にアカウントがある方は", new_session_path(resource_name) %> 4<% end %> 5 6<%- if devise_mapping.registerable? && controller_name != 'registrations' %> 7 <%= link_to "新規登録はこちら", new_registration_path(resource_name),class: "forgot" %> 8<% end %> 9 10<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %> 11 <%= link_to "パスワードを忘れた方は", new_password_path(resource_name),class: "forgot" %> 12<% end %> 13 14<%- if devise_mapping.confirmable? && controller_name != 'confirmations' %> 15 <%= link_to "確認用メールを再送する", new_confirmation_path(resource_name),class: "forgot" %> 16<% end %> 17 18<%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %> 19 <%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name),class: "forgot" %> 20<% end %> 21 22<%- if devise_mapping.omniauthable? %> 23 <%- resource_class.omniauth_providers.each do |provider| %> 24 <%= link_to "Sign in with #{OmniAuth::Utils.camelize(provider)}", omniauth_authorize_path(resource_name, provider),class: "forgot" %> 25 <% end %> 26<% end %> 27 28
DrqYuto👍を押しています

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問