如何验证经过身份验证的用户除会话控制器之外的所有资源

时间:2015-07-20 10:28:06

标签: ruby-on-rails

通过使用未经身份验证的用户

访问索引,我获得了无限循环

我怎么能摆脱它?感谢

错误

MyModel model = new MyModel();

 //1. using constructor
    Boolean blnObj1 = new Boolean(model.getBooleanStatus()); // This //getBooleanStatus will return 'boolean' value

    //2. using valueOf method of Boolean class. This is a static method.
    Boolean blnObj2 = Boolean.valueOf(model.getBooleanStatus());
  }

Intent targetIntent = new Intent(MyCalass.this, TargetClass.class);
targetIntent.putExtra("STATUS", new Boolean(model.getBooleanStatus()));
targetIntent.putExtra("STATUS", Boolean.valueOf(model.getBooleanStatus()));
startActivity(targetIntent);

片段

Intent receiverIntent = getIntent().getBoolean("STATUS");

1 个答案:

答案 0 :(得分:1)

我不喜欢您使用

检查经过身份验证的用户的方式
redirect_to index_url if current_user

我宁愿使用像current_user?user_logged_in?这样的布尔方法,明确地返回true或false

为什么?好吧,因为在大多数应用程序中,您仍然使用User实例处理未经身份验证或访客登录...所以,你总是有一个current_user实例变量,但可能有nil字段(如login: nilemail: nil)。

完全阻止current_user条件的if身份验证示例:

def current_user
  if @current_user 
    return @current_user
  else
    @current_user = User.new
    @current_user.try_to_authenticate_with_params
  end
end

所以基本上,当你打电话

redirect_to index_url if current_user

它将始终重定向,因为current_user将返回一个User对象,然后将其解释为true

所以我建议如下:

class ApplicationController

    before_action :verify_authenticity

    def verify_authenticity
      # Your code
    end

    def user_signed_in?
      current_user.is_authenticated? # or whatever
    end
    alias :user_logged_in? :user_signed_in?

class SessionController < ApplicationController

    skip_before_filter :verify_authenticity

    def new
      redirect_to index_url if user_signed_in?
    end