要求用户在rails上使用omniauth登录

时间:2012-12-31 23:26:53

标签: ruby-on-rails ruby omniauth

我遇到一些困难,要求用户通过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

谢谢!

1 个答案:

答案 0 :(得分:1)

你很亲密,也许看this RailsCast会让你到那儿。我跟着它,像你一样走了推特路线。它对我有用,所以你也应该有成功。

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

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