我是否应该从我的用户模型中删除所有身份验证代码,因为拥有身份模型?

时间:2012-11-04 00:44:09

标签: ruby-on-rails omniauth

我刚遇到omniauth-identity,用户无需使用Facebook,Twitter等即可登录和注册。

您必须创建一个Identity模型(我正在关注此Railscast):

class Identity < OmniAuth::Identity::Models::ActiveRecord

  validates :name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence:   true,
                format:     { with: VALID_EMAIL_REGEX },
                uniqueness: { case_sensitive: false }
  validates :password, presence: true, length: { minimum: 6 }
  validates :password_confirmation, presence: true
end

现在,我已经拥有User模型以及登录和注册系统(通过Ruby on Rails Tutorial创建):

user.rb:

class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation

  has_secure_password

  before_save { |user| user.email = email.downcase }
  before_save :create_remember_token

  validates :name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence:   true,
                    format:     { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  validates :password, presence: true, length: { minimum: 6 }
  validates :password_confirmation, presence: true

  private

  def create_remember_token
   self.remember_token = SecureRandom.urlsafe_base64
  end

所以我有点困惑。应删除与User模型中的身份验证有关的行(例如,验证,attr_accesiblecreate_remember_token等以及nameemail字段在用户表中)?

并删除 sessions_helper.rb 吗?

module SessionsHelper
  def sign_in(user)
    cookies.permanent[:remember_token] = user.remember_token
    self.current_user = user
  end

  def signed_in?
    !current_user.nil?
  end

  def sign_out
    self.current_user = nil
    cookies.delete(:remember_token)
  end

  def current_user=(user)
    @current_user = user
  end

  def current_user
    @current_user ||= User.find_by_remember_token(cookies[:remember_token])
  end

  def current_user?(user)
    user == current_user
  end

  def signed_in_user
    unless signed_in?
      store_location
      redirect_to signin_url, notice: "Please sign in."
    end
  end

  def redirect_back_or(default)
    redirect_to(session[:return_to] || default)
    session.delete(:return_to)
  end

  def store_location
    session[:return_to] = request.url
  end
end

因为如果我错了,请纠正我,但我认为omniauth-identity也会处理(current_user部分除外。

1 个答案:

答案 0 :(得分:0)

创建身份模型主要用于向多个提供程序进行身份验证。这里有一个很好的描述如何去做:

https://github.com/intridea/omniauth/wiki/Managing-Multiple-Providers

它回答了您的问题,用户模型中的内容以及身份模型中的内容。