devise + omniauth设计帮助器,如current_user,user_signed_in?不工作

时间:2012-03-28 14:03:52

标签: ruby-on-rails-3 devise omniauth

我正在使用设计并使用omniauth创建登录Facebook,但是有丢失设计帮助方法访问的问题,如current_user和user_signed_in?方法不起作用。

修改

AuthenticationController

def create
    omniauth = request.env["omniauth.auth"]    
    user = User.find_by_provider_and_uid(omniauth["provider"], omniauth["uid"]) ||       User.create_with_omniauth(omniauth)    
    session[:user_id] = user.id    
    redirect_to dashboard_path(user.id), :notice => "Signed in!"    
end  

redirect_to USercontroller仪表板方法

UserController中

before_filter  :logged_in

 def dashboard    
    @user = User.find(params[:id])   
    @comment = Comment.new    
    @comments = @user.comments.all.paginate(:page => params[:page], :per_page => 5)    
 end 

所以这里控制应该在检查ApplicationController中的logged_in方法后转到dashboard方法

ApplicationController中的

logged_in方法

应用程序控制器

def logged_in    
    if user_signed_in?     
       return true    
    else    
       redirect_to root_path    
       flash[:message] = "please login"    
    end     
  end 

当我使用facebook在控制台生成的代码

登录时
Started GET "/users/52/dashboard" for 127.0.0.1 at Thu Mar 29 12:51:55 +0530 2012     
Processing by UsersController#dashboard as HTML     
  Parameters: {"id"=>"52"}     
Redirected to http://localhost:3000/     
Filter chain halted as :logged_in rendered or redirected     
Completed 302 Found in 2ms (ActiveRecord: 0.0ms)     
上面的代码控件中的

是从logged_in方法渲染到root_path但是它展示了dashboard_path

所以我猜猜User_signed_in?帮助器不工作我也使用current_user代替生成相同的错误

2 个答案:

答案 0 :(得分:6)

正如我所见,user_signed_in?正在运行,但返回false,因为Devise用户未登录。要解决此问题,只需在控制器操作中用Devise sign_in方法替换存储的会话ID :

def create
    omniauth = request.env["omniauth.auth"]    
    user = User.find_by_provider_and_uid(omniauth["provider"], omniauth["uid"]) ||       User.create_with_omniauth(omniauth)    
    sign_in(:user, user)

    # actually if you really really need that id in the session, you can leave this line too :)
    session[:user_id] = user.id 

    redirect_to dashboard_path(user.id), :notice => "Signed in!"    
end 

答案 1 :(得分:0)

通过Facebook创建用户帐户后,如何登录用户?

你仍然应该使用像sign_in_and_redirect这样的设计助手。类似的东西:

user = User.build_from_omniauth(omniauth)
if user.save
  sign_in_and_redirect(:user, user)
end

然后你应该能够使用current_useruser_signed_in?等帮助者(只检查current_user是否为零)。


看看你的编辑,我的答案仍然有效。您需要做的是使用sign_in_and_redirect(:user, user)而不是仅在会话中设置ID。 使用设计登录后,您可以轻松自定义用户重定向的位置。

另外,删除这个logged_in过滤器,Devise有一个authenticate_user!方法可以用作before_filter。它会将用户重定向到登录页面,当他们登录时,会将用户重定向到他们尝试访问的页面。

你正在使用Devise,所以尽量利用它,然后去阅读doc;)

相关问题