Yuto Blog

Yuto Blog

【 Ruby on Rails】複数のOmniauth

>>> アプリケーションはこちらです <<<

参考:Bootstrapの開発環境を自動的に作る

Screen Shot 2015-05-27 at 20.28.11.png

Copy Gemfile
1
2
3
4
5
gem 'omniauth-facebook'
gem 'omniauth-twitter'
gem 'omniauth-google-oauth2'
gem 'omniauth-tumblr'
gem 'omniauth-amazon'
Copy config/dev_variables.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
ENV['FACEBOOK_KEY']    = 'xxxxxxxxxxxxxxxxxxx'
ENV['FACEBOOK_SECRET'] = 'xxxxxxxxxxxxxxxxxxx'

ENV['TWITTER_KEY']    = 'xxxxxxxxxxxxxxxxxxx'
ENV['TWITTER_SECRET'] = 'xxxxxxxxxxxxxxxxxxx'

ENV['GOOGLE_KEY']    = 'xxxxxxxxxxxxxxxxxxx'
ENV['GOOGLE_SECRET'] = 'xxxxxxxxxxxxxxxxxxx'

ENV['TUMBLR_KEY']    = 'xxxxxxxxxxxxxxxxxxx'
ENV['TUMBLR_SECRET'] = 'xxxxxxxxxxxxxxxxxxx'

ENV['AMAZON_KEY']    = 'xxxxxxxxxxxxxxxxxxx'
ENV['AMAZON_SECRET'] = 'xxxxxxxxxxxxxxxxxxx'
Copy config/initializers/omniauth.rb
1
2
3
4
5
6
7
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET']
  provider :twitter, ENV['TWITTER_KEY'], ENV['TWITTER_SECRET']
  provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET']
  provider :tumblr, ENV['TUMBLR_KEY'], ENV['TUMBLR_SECRET']
  provider :amazon, ENV['AMAZON_KEY'], ENV['AMAZON_SECRET']
end
Copy config/routes.rb
1
2
3
4
5
  get 'auth/:provider/callback' => 'sessions#create'
  get 'auth/failuer'            => 'sessions#auth_fail'
  get 'sign_out'                => 'sessions#destroy'

  root 'users#index'

User を作成: rails g model User name image provider uid

データベースをマイグレート: rake db:migrate

Copy app/models/user.rb
1
2
3
4
5
6
7
8
9
  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
      user.provider = auth.provider
      user.uid      = auth.uid
      user.name     = auth.info.name
      user.image    = auth.info.image
      user.save!
    end
  end

Sessionコントローラーを作成: rails g controller sessions

Copy app/controllers/sessions_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  def create
    user = User.from_omniauth(env['omniauth.auth'])
    session[:user_id] = user.id
    redirect_to root_path, notice: "Signed in with #{user.provider.capitalize} account!"
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_path, notice: "Signed out!"
  end

  def auth_fail
    render text: "You've tried to authenticate via #{params[:strategy]}, but the following error occurred: #{params[:message]}", status: 500
  end
Copy app/helpers/application_helper.rb
1
2
3
4
5
6
7
  def user_signed_in?
    session[:user_id]
  end

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
Copy app/views/users/index.html.slim
1
2
3
4
5
6
7
8
9
- if user_signed_in?
  p Signed in as #{current_user.name}
  = link_to 'Sign out', sign_out_path, id: 'sign_out'
- else
  li = link_to 'Sign in with Facebook', '/auth/facebook', id: 'sign_in'
  li = link_to 'Sign in with Twitter', '/auth/twitter', id: 'sign_in'
  li = link_to 'Sign in with Google', '/auth/google_oauth2', id: 'sign_in'
  li = link_to 'Sign in with Tumblr', '/auth/tumblr', id: 'sign_in'
  li = link_to 'Sign in with Amazon', '/auth/amazon', id: 'sign_in'

Facebook

ポップアップで登録

Copy app/assets/javascripts/facebook.js.coffee.erb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
jQuery ->
  $('body').prepend('<div id="fb-root"></div>')

  $.ajax
    url: "#{window.location.protocol}//connect.facebook.net/en_US/all.js"
    dataType: 'script'
    cache: true

window.fbAsyncInit = ->
  FB.init(appId: <%= ENV['FACEBOOK_KEY'] %>, cookie: true)

  $('#sign_in').click (e) ->
    e.preventDefault()
    FB.login (response) ->
      window.location = '/auth/facebook/callback' if response.authResponse

  $('#sign_out').click (e) ->
    FB.getLoginStatus (response) ->
      FB.logout() if response.authResponse
    true

Google

Redirect uris:

Copy
1
2
http://localhost:3000/auth/google_oauth2/callback
https://localhost:3000/auth/google_oauth2/callback
https://console.developers.google.comにアクセスして、APIs の 'Contacts API' と 'Google+ API' をオンする

Amazon

Allowed Return URLs:

Copy
1
2
http://localhost:3000/auth/amazon/callback
https://your_website_here/auth/amazon/callback
Created by Yuto at 2022-01-21 17:42
1
Like this article
Le Minh Thien Toan

Tác giả:Yuto Yasunaga

Xin chào các bạn. Mình là kỹ sư IT đang làm việc ở Nhật Bản. Mình tạo blog này để chia sẻ về cuộc sống và những kinh nghiệm trong quá trình học tập và làm việc.
Hy vọng bài viết này sẽ có ích cho bạn.