1

我正在构建一个 Rails 应用程序,并且我已经使用 has_secure_password 构建了一个基本身份验证。但是我想在此基础上添加 facebook 和 twitter 身份验证。这是我的身份验证

用户.rb

class User < ActiveRecord::Base
  before_create :create_remember_token

  has_secure_password

  validates :name, presence: true
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, uniqueness: true, format: {with:  VALID_EMAIL_REGEX }
  validates :last_name, presence: true 

  def User.new_remember_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  private

  def create_remember_token
    self.remember_token = User.encrypt(User.new_remember_token)
  end
end

会话控制器

class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.find_by(email: params[:session][:email])
    if user && user.authenticate(params[:session][:password])
      sign_in user
      redirect_to users_path(user), success: 'Başarılı bir şekilde giriş yapıldı!'
    else
      redirect_to root_path, danger: 'Giriş sırasında sorun oluştu lütfen bilgilerin doğruluğunu kontrol et' 
    end
  end

  def destroy
    sign_out
    redirect_to root_path, success: 'Başarılı bir şekilde çıkış yapıldı.' 
  end
end

会话助手

模块 SessionsHelper

  def sign_in(user)
    remember_token = User.new_remember_token
    if params[:remember_me]
      cookies.permanent[:remember_token] = remember_token
    else 
      cookies[:remember_token] = remember_token
    end
    user.update_attribute(:remember_token, User.encrypt(remember_token))
    self.current_user = user
  end

  def current_user=(user)
    @current_user = user
  end

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

  def signed_in?
    !current_user.nil?
  end

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

因此,我想在此之上通过 Omniauth 添加 Facebook 和 Twitter 身份验证,但我不确定执行此操作的最佳策略是什么。有可能还是我必须完全改变我现在的身份验证方式?

4

1 回答 1

1

首先使用以下代码在 config/initializers 中创建一个 omniauth.rb 初始化程序:

Rails.application.config.middleware.use OmniAuth::Builder do

provider :facebook, "key", "secret"
provider :twitter, "key", "secret"

end

OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE

这就是我处理登录控制器的方式,非常简单:

class LoginsController < ApplicationController

def create

    data = request.env['omniauth.auth']

    session[:user_name] = data["info"]["name"]
    session[:user_image] = data["info"]["image"]

    redirect_to root_path
end

def destroy
    reset_session
    redirect_to root_path
end

end
于 2013-10-05T22:20:59.727 回答