155
159

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.

RailsでOmniauthを使ってTwitterログインする

Last updated at Posted at 2013-11-29

Ruby2.0, Rails4で確認

いつか試そういつか試そうと思っていたOmniauthを使ってのTwitterログインを試してみました。

詳細記事はこちらをご参照ください

初期設定

  • Twitterアプリの作成

callback URLに「http://127.0.0.1:3000/auth/twitter」を指定しておきます。

後々投稿もさせたいのでAccessを「Read and Write」にしてあります。

「Allow this application to use 'Sign in with Twitter」にチェックを入れておくと、二度目のログイン以降は認証画面を省略することができます。

  • Gemfile追加
gem 'omniauth'
gem 'omniauth-twitter'
gem 'settingslogic'
  • bundle install
./bin bundle install
  • settingslogic initializer設定
config/initializers/0_settings.rb
class Settings < Settingslogic
  source "#{Rails.root}/config/settings.yml"
  namespace Rails.env
end
  • settings.ymlにtwitter設定を記述
config/settings.yml
defaults: &defaults

development:
  <<: *defaults
  twitter:
    consumer_key: YOUR CONSUMER KEY
    consumer_secret: YOUR CONSUMER SECRET

test:
  <<: *defaults

production:
  <<: *defaults
  • omniauth initializer設定
config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :twitter, Settings.twitter.consumer_key, Settings.twitter.consumer_secret
end

model作成

  • userモデル作成
./bin/rails g model user provider:string uid:string screen_name:string name:string
  • migrate
./bin/rake db:migrate
  • app/models/user.rb
app/models/user.rb

class User < ActiveRecord::Base
  def self.create_with_omniauth(auth)
    create! do |user|
      user.provider = auth['provider']
      user.uid = auth['uid']
      user.screen_name = auth['info']['nickname']
      user.name = auth['info']['name']
    end
  end
end

controller作成

  • controller作成
./bin/rails g controller base
./bin/rails g controller home index
./bin/rails g controller sessions
  • routing追加
config/routes.rb
root 'home#index'
get "home/index"
get '/auth/:provider/callback', :to => 'sessions#callback'
post '/auth/:provider/callback', :to => 'sessions#callback'
get '/logout' => 'sessions#destroy', :as => :logout
  • BaseController
app/controllers/base_controller.rb
class BaseController < ActionController::Base
  protect_from_forgery
 
  def login_required
    if session[:user_id]
      @current_user = User.find(session[:user_id])
    else
      redirect_to root_path
    end
 
  end
 
  helper_method :current_user
 
  private
  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
end
  • HomeController
app/controllers/home_controller.rb
class HomeController < BaseController
  def index
  end
end
  • SessionController
app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
  def callback
    auth = request.env['omniauth.auth']
    user = User.find_by_provider_and_uid(auth['provider'], auth['uid']) || User.create_with_omniauth(auth)
    session[:user_id] = user.id
    redirect_to root_path
  end
   
  def destroy
    session[:user_id] = nil
    redirect_to root_path
  end
end

View変更

  • layout追加
app/views/layouts/application.html.erb
<% if current_user %>
  <%= current_user.name %> <%= link_to 'ログアウト', logout_path %>
<% else %>
  <%= link_to 'ログイン', '/auth/twitter' %>
<% end %>

ブラウザからhttp://127.0.0.1:3000
にアクセスするとログインリンクが表示され、Twitter認証ができるようになりました。

次回は

ログインしたアカウントでTweet投稿ができるようにしてみます。

参考

155
159
6

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
155
159

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?