1

我在要求用户通过omniauth(使用twitter)登录时遇到了一些困难。我有一个 session_controller、用户模型和授权模型设置。

问题似乎是我无法访问omniauth哈希。有什么理由吗?

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :check_sign_in

  def check_sign_in
    omniauth = request.env["omniauth.auth"] 
    authentication = Authorization.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
    unless authentication
        redirect_to signin_path
    end
  end
end

谢谢!

4

1 回答 1

1

你已经接近了,也许看这个 RailsCast会让你到达那里。我跟着它走,像你一样走 Twitter 路线。它对我有用,所以你也应该成功。

在我的应用程序控制器中,我有

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

而且,在我的会话模型中,

class SessionsController < ApplicationController
  def create
    user = User.from_omniauth(env["omniauth.auth"])
    session[:user_id] = user.id
    redirect_to root_url, :notice => "You are logged  in."
  end
  def destroy
    session[:user_id] = nil
    redirect_to root_url, :notice => 'You are logged out.'
  end
end

在我的用户模型中

def self.from_omniauth(auth)
  where(auth.slice("provider", "uid")).first || create_from_omniauth(auth)
end

def self.create_from_omniauth(auth)
  create! do |user|
    user.provider = auth["provider"]
    user.uid = auth["uid"]
    user.name = auth["info"]["name"]
    user.nickname = auth["info"]["nickname"]
    user.image = auth["info"]["image"]
  end
end
于 2013-01-01T19:35:09.937 回答