【 Ruby on Rails】複数のOmniauth

**[>>> アプリケーションはこちらです <<<](http://renshu-multiple-omniauth.herokuapp.com/)**

*参考：[Bootstrapの開発環境を自動的に作る](http://qiita.com/YutoYasunaga/items/f53e62d850570eb85e4f)*


![Screen Shot 2015-05-27 at 20.28.11.png](https://qiita-image-store.s3.amazonaws.com/0/35605/d4659969-7c74-3230-b216-478692ddab53.png)


```ruby:Gemfile
gem 'omniauth-facebook'
gem 'omniauth-twitter'
gem 'omniauth-google-oauth2'
gem 'omniauth-tumblr'
gem 'omniauth-amazon'
```

```ruby:config/dev_variables.rb
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'
```

```ruby:config/initializers/omniauth.rb
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
```

```ruby:config/routes.rb
  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`

```ruby:app/models/user.rb
  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`

```ruby:app/controllers/sessions_controller.rb
  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
```

```ruby:app/helpers/application_helper.rb
  def user_signed_in?
    session[:user_id]
  end

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
```

```app/views/users/index.html.slim
- 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

ポップアップで登録

```app/assets/javascripts/facebook.js.coffee.erb
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:
```
http://localhost:3000/auth/google_oauth2/callback
https://localhost:3000/auth/google_oauth2/callback
```

[https://console.developers.google.com](https://console.developers.google.com)にアクセスして、APIs の 'Contacts API' と 'Google+ API' をオンする

#### Amazon

Allowed Return URLs:
```
http://localhost:3000/auth/amazon/callback
https://your_website_here/auth/amazon/callback
```