#003 Omniauth 1

| 21 minutes | omniauth 认证
介绍如何使用OmniAuth来做基于第三方服务的认证。

Gemfile:

Gemfile
gem 'omniauth'
gem 'omniauth-github'

初始化OmniAuth:

config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :github, 'd78181e1ec709f32d844',
    '7fd79b37dd8a4423c5989b6ae6d4fe358af11dc'
end

路由:

config/routes.rb
match "/auth/:provider/callback", :to => 'sessions#create'

User model(这段代码会在下一期进行重构,具体原因请看视频。):

app/models/user.rb
class User < ActiveRecord::Base
  validates :nickname, :presence => true
  validates :email, :presence => true, :uniqueness => true
  has_many :authentications

  accepts_nested_attributes_for :authentications

  class << self
    def from_auth(auth)
      Authentication.find_by_provider_and_uid(auth[:provider],
                                              auth[:uid]).try(:user) ||
        create!(
          :nickname => auth[:info][:nickname],
          :email => auth[:info][:email],
          :authentications_attributes => [
            Authentication.new(:provider => auth[:provider],
                               :uid => auth[:uid]
                              ).attributes
      ])
    end
  end

end

Authentication model:

app/models/authentication.rb
class Authentication < ActiveRecord::Base
  validates :provider, :presence => true, :uniqueness => {:scope => :user_id}
  validates :uid, :presence => true, :uniqueness => {:scope => :provider}
  belongs_to :user
end

Sessions Controller:

app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
  def create
    user = User.from_auth(request.env['omniauth.auth'])
    session[:user_id] = user.id
    flash[:notice] = "Welcome #{user.nickname}"
    redirect_to posts_path
  end
end
Similar Episodes