over 3 years ago

系統:

Mac OS X Yosemite 10.10
Ruby 2.1.4
Rails 4.1.7

相關連結

omniauth-github ( https://github.com/intridea/omniauth-github )
omniauth-facebook Rails ( https://github.com/mkdynamic/omniauth-facebook )
figaro ( https://github.com/laserlemon/figaro )

設定步驟如下

1. Gemfile 設定

添加必要的 gem 套件至 Gemfile 檔中

# Use Omniauth
gem 'omniauth-github', :github => 'intridea/omniauth-github'
gem 'omniauth-facebook'

# Use Figaro
gem 'figaro', :github => 'laserlemon/figaro'

2. omniauth config 設定

config/initializers/omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :github, ENV['github_key'], ENV['github_secret']
  provider :facebook, ENV['facebook_key'], ENV['facebook_secret'], :display => 'popup'
end

3. 新增 User model

rails g model user provider uid name image intro url
rake db:migrate

models/user.rb

def self.from_omniauth(auth)
  find_by_provider_and_uid(auth.provider, auth.uid) || create! do |user|
    user.provider = auth.provider
    user.uid      = auth.uid
    user.name     = auth.info.name
    user.image    = auth.info.image
    user.intro    = auth.info.description
    user.url      = auth.info.urls.Facebook if auth.provider == 'facebook'
    user.url      = auth.info.urls.GitHub if auth.provider == 'github'
  end
end

4. routes 設定

config/routes.rb

get 'auth/:provider/callback' => 'sessions#create'
get 'auth/failure' => redirect('/')
get 'signout' => 'sessions#destroy', as: :signout

5. controller 設定

sessions_controller.rb

class SessionsController < ApplicationController
  def create
    auth = request.env['omniauth.auth']
    user = User.from_omniauth(auth)
    session[:user_id] = user.id
    redirect_to root_url
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_url
  end
end

application_controller.rb

helper_method :current_user

private
  def current_user
      @current_user ||= User.find session[:user_id] if session[:user_id]
  end

6. view 設定

layouts/application.html.erb

<div id="user_nav">
  <% if current_user %>
    Signed in as <strong><%= current_user.name %></strong>!
    <%= link_to "Sign out", signout_path %>
  <% else %>
    <%= link_to "Sign in with Facebook", "/auth/facebook" %>
    <%= link_to "Sign in with GitHub", "/auth/github" %>
  <% end %>
</div>

7. 使用 figaro 管理 auth_key & auth_secret

$ figaro install

config/application.yml

facebook_key: 'insert_your_key_here'
facebook_secret: 'insert_your_secret_here'

development:
  github_key: 'insert_your_key_here'
  github_secret: 'insert_your_secret_here'

production:
  github_key: 'insert_your_key_here'
  github_secret: 'insert_your_secret_here'

8. 搞定!

← 設定 Rspec 測試環境 Globalize Model Data →
 
comments powered by Disqus