LoginSignup
13
14

More than 5 years have passed since last update.

【最速シリーズ】最速でdeviseでfacebookログインまで作る

Last updated at Posted at 2016-04-26

①Gemfileを変更する

Gemfile
gem 'devise'
gem 'omniauth'
gem 'omniauth-facebook'

変更したら$ bundle install

② deviseの諸々をインストールする

$ bundle exec rails g devise:install
$ bundle exec rails g devise User provider:string uid:string name:string token:string
$ bundle exec rails g devise:controllers
$ bundle exec rails g devise:views users
$ bundle exec rails g controller home index

最後のControllerはroot用ですぜ

$ rake db:create
$ rake db:migrate

も忘れずに!

③ deviseのデフォルトのURLを変更

config/environments/development.rb

Rails.application.configure do

  ...

  # mailer setting
  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

end

④ facebookのAPPIDとSECRET_KEYをGETする

ここからGETしてくれよな!
https://developers.facebook.com/

⑤ 4で取得したやつらをconfigに反映させる

config/initializers/devise.rb
require "omniauth-facebook"
Devise.setup do |config|

  ...

  OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE if Rails.env.development? #とりあえずローカルで動く奴つくるよ!
  config.omniauth :facebook, ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_APP_SECRET']  #dotenv-railsとか使ってね!

end

facebook_app_idとかはdotenv-railsとかで管理!!

⑥Userモデルのdevise設定にomniauthを追加するぜ

app/models/user.rb
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :recoverable,
         :rememberable, :trackable, :validatable, :omniauthable

end

⑦Routingを変更する

routes.rb

Rails.application.routes.draw do

  root 'home#index'
  devise_for :users, :controllers => { omniauth_callbacks: 'users/omniauth_callbacks' }

end

ルートの設定とomniauthのrouting設定が大事

⑧じゃあ、facebookログイン用のリンクをviewに用意しようぜ

app/views/home.html.slim

h1 Home#index
p Find me in app/views/home/index.html.slim

h1
  | Home#index
  - if user_signed_in?
    |  Logged in as
    strong
      = current_user.email
    | .
    = link_to "Settings", edit_user_registration_path, :class => "navbar-link"
    |  |
    = link_to "Logout", destroy_user_session_path, method: :delete, :class => "navbar-link"
  - else
    = link_to "Sign up", new_user_registration_path, :class => 'navbar-link'
    |  |
    = link_to "Login", new_user_session_path, :class => 'navbar-link'
    |  |
    = link_to "Sign in with Facebook", user_omniauth_authorize_path(:facebook)

⑨リンク先のControllerを対応させよう!(ゴールは近い)

app/controllers/users/omniauth_callbacks_controller.rb

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController

  def facebook
    callback_from :facebook
  end

  private
  def callback_from(provider)
    @user = User.find_for_oauth(request.env['omniauth.auth'])

    if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication
      set_flash_message(:notice, :success, :kind => provider.to_s) if is_navigational_format?
    else
      if provider.to_s == "facebook"
        session["devise.facebook_data"] = request.env["omniauth.auth"]
        redirect_to new_user_registration_url
      end
    end
  end
end

最後にこのメソッドをUserモデルに実装しよう!
User.find_for_oauth(request.env['omniauth.auth'])

⑩ find_for_oauthをUserモデルに実装する

app/models/user.rb
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :recoverable,
         :rememberable, :trackable, :validatable, :omniauthable

  def self.find_for_oauth(auth)
    user = User.where(provider: auth.provider, uid: auth.uid).first

    unless user
      user = User.create( name:     auth.extra.raw_info.name,
                          provider: auth.provider,
                          uid:      auth.uid,
                          email:    auth.info.email,
                          token:    auth.credentials.token,
                          password: Devise.friendly_token[0,20] )
    end

    return user
  end
end

これで完成!!!!!!!!!!!
な、はず!
帰ったら確かめる笑

参考リンク

[Rails] deviseの使い方
http://qiita.com/cigalecigales/items/73d7bd7ec59a001ccd74

devise と omniauth 使って、オリジナルログイン・facebook ログイン・twitter ログインを実装する方法
http://abeyuusuke1978.hatenablog.com/entry/2015/01/03/235255

最速シリーズ

【最速シリーズ】最速でCarrierwaveで画像アップロードまで作る
http://qiita.com/funao/items/cd4c4e33cf43767338e2

13
14
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
13
14