Rails设计通过身份验证令牌查找用户

时间:2013-07-22 10:29:10

标签: ruby-on-rails authentication devise

我正在尝试这样做:

类NotesController< ApplicationController中

def index

@user = User.find_by_authentication_token(params [:token])

@notes = @ user.notes

...

但是我收到了一个错误:

Started POST "/api/login" for 10.0.0.4 at 2013-07-22 13:20:43 +0300
Processing by Api::LoginController#login as JSON
  Parameters: {"user"=>{"password"=>"[FILTERED]", "email"=>"pp@pp.pp"}, "login"=>{"user"=>{"password"=>"[FILTERED]", "email"=>"pp@pp.pp"}}}
  User Load (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."email" = 'pp@pp.pp' LIMIT 1
  User Load (1.0ms)  SELECT "users".* FROM "users" WHERE "users"."authentication_token" = 'GFRWkkLCq3xQx5rTRTFp' LIMIT 1
Completed 200 OK in 119ms (Views: 0.0ms | ActiveRecord: 3.0ms)


Started GET "/notes?token=GFRWkkLCq3xQx5rTRTFp" for 10.0.0.4 at 2013-07-22 13:20:44 +0300
Processing by NotesController#index as JSON
  Parameters: {"token"=>"GFRWkkLCq3xQx5rTRTFp", "note"=>{}}
  User Load (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."authentication_token" = 'GFRWkkLCq3xQx5rTRTFp' LIMIT 1
Completed 500 Internal Server Error in 1ms

NoMethodError (undefined method `notes' for nil:NilClass):
  app/controllers/notes_controller.rb:7:in `index'

如您所见,代码

User.find_by_authentication_token(params[:token])

保持回头零。

1 个答案:

答案 0 :(得分:0)

想出来: 问题是我忘记在方法 user.ensure_authentication_token

之后保存(提交)用户
def login
    user = User.find_for_database_authentication(:email => params[:user][:email])
    if user.nil?
      render :json => {:result => 'ERROR'}
    else
      if user.valid_password?(params[:user][:password])
        user.ensure_authentication_token
        user.save
        render :json => {:result => user.authentication_token}