2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

メール認証を実装してしまった人のためのTwitterログイン認証の実装方法

Last updated at Posted at 2018-08-25

https://qiita.com/keeya/items/c96a0393c76f5560ee41
https://qiita.com/puremoru0315/items/f1d459b663fd3b715dee
https://qiita.com/To_BB/items/01863aa50d628c069b64

Twitterログイン認証を解説する記事は数多いですが、Railsチュートリアルなどでメール認証を実装してしまった後だと、残念ながら上の記事にあるコードをそのままコピペしてもログイン認証は機能しません。

なんでって?
self.find_or_create_by(provider: provider,uid: uid)では、バリデーションに弾かれてしまうからです。

find_or_created_byメソッドは、引数で渡したカラムでfindをかけて引っかからなかったらcreateします。
createはsaveまで行ってしまうので、メール認証で設定したemailやpasswordのvalidatesで弾かれてしまいます。

この問題を解決するためには、上の記事にあるfind_or_created_byをfind_or_initialize_byに変更する必要があります。
このメソッドは、引数で渡したカラムでfindをかけて引っかからなかったらnewしてくれます。
あとは、インスタンスにバリデーションを回避できるだけの情報を与えて、saveすればいいだけです。

models/user.rb
 #Twitter認証用メソッド
  def self.find_or_initialize_from_auth(auth)
    provider = auth[:provider]
    uid = auth[:uid]
    user_name = auth[:info][:name]
    email = "#{('a'..'z').to_a.shuffle[0..10].join}@gmail.com"
    password = "foobar"
    image_url = auth[:info][:image]
    profile   = auth[:info][:description]

    self.find_or_initialize_by(provider: provider, uid: uid) do |user|
      user.name = user_name
      user.email = email
      user.password = password
      user.image_url = image_url
      user.profile = profile
      user.activated = true
    end
  end
sessions_controller.rb
def twitter
    @user = User.find_or_initialize_from_auth(request.env['omniauth.auth'])
    @user.save
    session[:user_id] = @user.id
    if session[:user_id]
      flash[:success] = "ユーザー認証が完了しました。"
      redirect_to @user
    else
      flash[:danger] = "ユーザー認証に失敗しました。"
      redirect_to root_url
    end
  end

バリデーション以外にも、activatedをtrueにするのも忘れないようにしましょう。

ちなみに、僕はemailをランダム生成してますが、API設定の方でPrivacy Policy URLとTerms of Service URLをきちんと設定すれば、email情報も取得できるそうです。

omniauthを使って他にどんな情報が取得できるかは、以下のリンクが参考になります。

以上。
誰かの役に立ちますように。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?