#004 OmniAuth 2 Identity

| 21 minutes | omniauth identity authentication
介绍如何使用OmniAuth Identity 来做基于账号和密码的认证。

添加所需要的gems:

Gemfile
gem 'omniauth-identity'
gem 'bcrypt-ruby', '~> 3.0.0'

初始化Identity:

config/initializers/omniauth.rb
OmniAuth.config.on_failure do |env|
  [302, {'Location' => "/auth/#{env['omniauth.error.strategy'].name}/failure?message=#{env['omniauth.error.type']}"}, ["Redirecting..."]]
end

provider :identity, :fields => [:nickname, :email]#, on_failed_registration: UsersController.action(:new)

添加Identity model:

rails g model identity nickname:string email:string password_digest:string

重构并修改 User model:

app/models/user.rb
def add_auth(auth)
    authentications.create(:provider => auth[:provider],
                           :uid => auth[:uid])
end

class << self
  def from_auth(auth)
    locate_auth(auth) || locate_email(auth) || create_auth(auth)
  end

  def locate_auth(auth)
    Authentication.find_by_provider_and_uid(auth[:provider],
                                              auth[:uid]).try(:user)
  end

  def locate_email(auth)
    user = find_by_email(auth[:info][:email])
    return unless user
    user.add_auth(auth)
    user
  end

  def create_auth(auth)
    create!(
      :nickname => auth[:info][:nickname],
      :email => auth[:info][:email],
      :authentications_attributes => [
        Authentication.new(:provider => auth[:provider],
                           :uid => auth[:uid]
                          ).attributes
    ])

  end
end

update:
后来觉得createauth方法命名为 createuser 或者 createuserwith_auth更加合理.

Similar Episodes