OmniAuth


## OmniAuth

様々なプロバイダーのログイン認証を手軽に実現するプラグイン。

### 公式リポジトリ

[https://github.com/intridea/omniauth](https://github.com/intridea/omniauth)

### 公式ドキュメント

[https://github.com/intridea/omniauth/wiki](https://github.com/intridea/omniauth/wiki)

### The Ruby Toolbox

[https://www.ruby-toolbox.com/projects/omniauth](https://www.ruby-toolbox.com/projects/omniauth)

### 参考ドキュメント

[簡単なOmniAuth - ASCIIcasts](http://ja.asciicasts.com/episodes/241-simple-omniauth)
[Rails3.2.3 + omniauth-twitter New App - I can't change the world.](http://change-the-world.heroku.com/32)

## インストール

### For GitHub

Gemfileに、omniauth、omniauth-githubを記述する。

```ruby:Gemfile
gem 'omniauth'
gem 'omniauth-github'
```

インストールする。

```bash
$ bundle install
```

## 初期設定

### For GitHub

設定ファイルを新規作成する。
`CLIENT_ID`、`SECRET`には、GitHubで登録したアプリケーションのClient ID、Secretを設定する。

```ruby:config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :github, "CLIENT_ID", "SECRET"
end
```

セッションコントローラを新規作成する。

```bash
rails g controller sessions
      create  app/controllers/sessions_controller.rb
      invoke  erb
      create    app/views/sessions
      invoke  helper
      create    app/helpers/sessions_helper.rb
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/sessions.js.coffee
      invoke    scss
      create      app/assets/stylesheets/sessions.css.scss
```

```ruby: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
    reset_session
    redirect_to root_path
  end
end
```

ルーティングを追加する。

```ruby:config/routes.rb
match "/auth/:provider/callback" => "sessions#callback"
match "/signout" => "sessions#destroy"
```

Userモデルを新規作成する。

```bash
$ rails generate model user
      invoke  active_record
      create    db/migrate/20120418060936_create_users.rb
      create    app/models/user.rb
```

```ruby:db/migrate/20120418060936_create_users.rb
class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :provider, :null => false
      t.string :uid, :null => false
      t.string :name, :null => false
      t.string :nickname
      t.string :image
      t.string :token

      t.timestamps
    end
  end
end
```

```ruby: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.name = auth["info"]["name"]
      user.nickname = auth["info"]["nickname"]
      user.image = auth["extra"]["raw_info"]["avatar_url"]
      user.token = auth["credentials"]["token"]
    end
  end
end
```

```bash
$ rake db:migrate
==  CreateUsers: migrating ====================================================
-- create_table(:users)
   -> 0.0021s
==  CreateUsers: migrated (0.0022s) ===========================================
```

ヘルパーメソッドを追加する。

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

ビューにログイン、ログアウトのリンクを追加する。

```ruby
<% if current_user %>
  <%= link_to "Sign out", signout_path 
<% else %>
  <%= link_to "Sign in with GitHub", "/>
<% end %>
```

## OmniAuthで取得可能な情報

### For GitHub

OmniAuthで取得出来る情報は以下の通り。

```bash
{"provider"=>"github",
 "uid"=>572020,
 "info"=>
  {"nickname"=>"FakeStarBaby",
   "email"=>nil,
   "name"=>"Yoshinori Hirasawa",
   "urls"=>
    {"GitHub"=>"https://github.com/FakeStarBaby",
     "Blog"=>"http://twitter.com/#!/fakestarbaby"}},
 "credentials"=>
  {"token"=>"1234567890123456789012345678901234567890", "expires"=>false},
 "extra"=>
  {"raw_info"=>
    {"public_gists"=>10,
     "type"=>"User",
     "blog"=>"http://twitter.com/#!/fakestarbaby",
     "location"=>"Tokyo",
     "html_url"=>"https://github.com/FakeStarBaby",
     "created_at"=>"2011-01-19T05:08:56Z",
     "email"=>nil,
     "public_repos"=>51,
     "followers"=>16,
     "company"=>"Japan",
     "hireable"=>false,
     "bio"=>nil,
     "url"=>"https://api.github.com/users/FakeStarBaby",
     "following"=>69,
     "login"=>"FakeStarBaby",
     "name"=>"Yoshinori Hirasawa",
     "gravatar_id"=>"0e3e4d3a8e69ccae1e9b9dcc219f3f1f",
     "avatar_url"=>
      "https://secure.gravatar.com/avatar/0e3e4d3a8e69ccae1e9b9dcc219f3f1f?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-140.png",
     "id"=>572020}}}
```