OmniAuthの設定方法が若干変更されてました
gemがプロバイダ毎に別れた為、個別にGemfileに設定する必要があります。
/Gemfile(twitterとFacebookの場合。追記後、$ bundle install 実行)
gem 'omniauth-twitter' gem 'omniauth-facebook'
/config/initializers/omniauth.rb(今までと同じ)
Rails.application.config.middleware.use OmniAuth::Builder do provider :twitter, 'TWITTER_KEY', 'TWITTER_SECRET' provider :facebook, 'FACEBOOK_ID', 'FACEBOOK_SECRET' end
SessionsControllerの作成
$ rails g controller sessions
/app/controller/sessions_controller.rb
class SessionsController < ApplicationController def create user = User.from_omniauth(env["omniauth.auth"]) session[:user_id] = user.id redirect_to root_url, notice: "Signed in!" end def destroy session[:user_id] = nil redirect_to root_url, notice: "Signed out!" end def failure redirect_to root_url, alert: "Authentication failed." end end
ルーティングの設定
/config/routes.rb
root :to => "home#index" match "/auth/:provider/callback" => "sessions#create" match "/auth/:provider/failure" => "sessions#failure" match "/signout" => "sessions#destroy", :as => :signout
Userモデルの作成
$ rails g model user
マイグレーションファイルの修正→migrate
class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.string :provider, :null => false t.string :uid, :null => false t.string :name, :null => false t.string :screen_name, :null => false t.timestamps end end def self.down drop_table :users end end
$ rake db:migrate
/app/models/user.rb
class User < ActiveRecord::Base def self.from_omniauth(auth) find_by_provider_and_uid(auth["provider"], auth["uid"]) || create_with_omniauth(auth) end def self.create_with_omniauth(auth) create! do |user| user.provider = auth["provider"] user.uid = auth["uid"] user.name = auth["info"]["name"] user.screen_name = auth["info"]["nickname"] end end end
テスト用
app/application_controller.rb
class ApplicationController < ActionController::Base protect_from_forgery helper_method :current_user private def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end end
/app/views/home/index.html.erb
<% if current_user %> Welcome <%= current_user.name %>! <br /> <%= link_to "Sign Out", signout_path %> <% else %> <%= link_to "Sign in with Facebook", "/auth/facebook" %><br /> <%= link_to "Sign in with Twitter", "/auth/twitter" %> <% end %>